@seip/bluebird-js 0.1.2 → 0.1.5

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 (43) hide show
  1. package/.vscode/extensions.json +7 -0
  2. package/.vscode/settings.json +10 -0
  3. package/AGENTS.md +495 -454
  4. package/README.md +528 -353
  5. package/app/routes/web.js +47 -55
  6. package/app/views/about.jsx +98 -0
  7. package/app/views/components/Header.jsx +42 -0
  8. package/app/views/components/LiveCounter.jsx +66 -0
  9. package/app/views/dashboard.jsx +300 -0
  10. package/app/views/index.jsx +123 -0
  11. package/app/views/layouts/main/view.jsx +201 -0
  12. package/app/views/legal/terms.html +29 -19
  13. package/app/views/login.jsx +141 -0
  14. package/core/actions.d.ts +4 -0
  15. package/core/actions.js +329 -0
  16. package/core/app.js +38 -6
  17. package/core/cli/doctor.js +3 -4
  18. package/core/cli/init.js +20 -6
  19. package/core/cli/migrate.js +418 -145
  20. package/core/cli/view.js +76 -11
  21. package/core/database.js +6 -10
  22. package/core/debug.js +1 -1
  23. package/core/html.d.ts +54 -42
  24. package/core/html.js +473 -217
  25. package/core/index.d.ts +1385 -1190
  26. package/core/jsx.d.ts +38 -0
  27. package/core/jsx.js +1432 -0
  28. package/core/model.js +271 -61
  29. package/core/render-cache.js +212 -212
  30. package/core/render.d.ts +20 -2
  31. package/core/render.js +459 -51
  32. package/core/validate.js +1 -1
  33. package/core/view-loader.js +360 -24
  34. package/package.json +9 -3
  35. package/public/js/bluebird-client.js +3160 -1780
  36. package/public/js/tailwind.js +8 -0
  37. package/app/views/about.js +0 -63
  38. package/app/views/dashboard.js +0 -147
  39. package/app/views/index.js +0 -80
  40. package/app/views/layouts/main/view.js +0 -81
  41. package/app/views/login.js +0 -80
  42. package/public/css/bluebird.min.css +0 -2
  43. package/public/js/bluebird.min.js +0 -1073
package/core/render.js CHANGED
@@ -1,5 +1,21 @@
1
1
  import Config from "./config.js";
2
- import { html, SafeHtml, escapeHtml, safeJson } from "./html.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";
3
19
  import RenderCache from "./render-cache.js";
4
20
  import ViewLoader from "./view-loader.js";
5
21
 
@@ -8,31 +24,99 @@ const DEBUG = props.debug;
8
24
  const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
9
25
 
10
26
  /**
11
- * Modern JavaScript HTML rendering engine for Bluebird.js.
12
- * Standardizes on zero-build JS view modules, SafeHtml tagged templates,
13
- * progressive layouts, client hydration, and multi-tier caching.
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.
14
56
  */
15
57
  export class Render {
16
58
  /**
17
- * Generates declarative HTML markup for client-side island hydration.
18
- * @param {string} name - Island component name.
19
- * @param {Object} [props={}] - Initial props passed to the component.
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.
20
64
  * @param {Object} [options={}] - Island options.
21
65
  * @param {boolean} [options.persist=false] - Preserves island across View Transitions.
22
- * @param {string} [options.fallback=""] - Fallback HTML content.
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.
23
73
  * @param {string} [options.tag="div"] - Container tag name.
24
74
  * @returns {string} Declarative HTML markup.
25
75
  */
26
- static island(name, props = {}, options = {}) {
76
+ static island(name, islandProps = {}, options = {}) {
27
77
  const tag = options.tag || "div";
78
+ const resolvedName =
79
+ typeof name === "function"
80
+ ? name.displayName || name.name || "Island"
81
+ : String(name);
28
82
  const persistAttr = options.persist ? ' data-persist="true"' : "";
29
- const serializedProps = escapeHtml(safeJson(props));
30
- const fallback = options.fallback || "";
31
- return `<${tag} data-island="${escapeHtml(name)}" data-props="${serializedProps}"${persistAttr}>${fallback}</${tag}>`;
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}>`;
32
116
  }
33
117
 
34
118
  /**
35
- * Synchronously or asynchronously renders a component or view to a raw HTML string.
119
+ * Synchronously or asynchronously renders a component or view (`.jsx` or `.js`) to a raw HTML string.
36
120
  * @param {string} viewName - Component or view name.
37
121
  * @param {Object} [data={}] - Props and context.
38
122
  * @returns {Promise<string>}
@@ -41,11 +125,12 @@ export class Render {
41
125
  const view = await ViewLoader.load(viewName);
42
126
  if (!view) return "";
43
127
 
44
- if (view.type === "js") {
45
- const renderFn = typeof view.module.default === "function" ? view.module.default : view.module;
128
+ if (view.type === "js" || view.type === "jsx") {
129
+ const renderFn =
130
+ typeof view.module.default === "function" ? view.module.default : view.module;
46
131
  const ctx = { data };
47
132
  const output = await renderFn(data, ctx);
48
- return output instanceof SafeHtml ? output.toString() : String(output ?? "");
133
+ return resolveOutputToHtml(output, ctx);
49
134
  }
50
135
 
51
136
  return view.content || "";
@@ -87,7 +172,7 @@ export class Render {
87
172
  }
88
173
 
89
174
  /**
90
- * Sends a rendered HTML view response with full layout and head asset resolution.
175
+ * Sends a rendered HTML view response (`.jsx`, `.js`, or `.html`) with full layout and head asset resolution.
91
176
  *
92
177
  * @param {import('express').Response} res - Express response object.
93
178
  * @param {string} viewName - Logical view identifier.
@@ -103,6 +188,19 @@ export class Render {
103
188
  res.req?.headers?.["x-bluebird-partial"] === "1" ||
104
189
  res.req?.query?._partial === "1";
105
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
+
106
204
  const view = await ViewLoader.load(viewName);
107
205
  if (!view) {
108
206
  return res.status(404).json({ message: `View '${viewName}' not found.` });
@@ -110,32 +208,62 @@ export class Render {
110
208
 
111
209
  let rendered = "";
112
210
 
113
- if (view.type === "js") {
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
+
114
237
  const ctx = {
115
238
  req: res.req,
116
239
  res,
117
240
  user: res.req?.user,
241
+ csrfToken,
242
+ flash,
118
243
  locals,
119
244
  appLocals,
120
- data,
245
+ data: viewData,
121
246
  };
122
247
 
123
248
  if (typeof view.module.load === "function") {
124
249
  const loadedData = await view.module.load(ctx);
125
250
  if (loadedData && typeof loadedData === "object") {
126
- Object.assign(data, loadedData);
251
+ Object.assign(viewData, loadedData);
127
252
  }
128
253
  }
129
254
 
130
255
  const mergedData = {
131
256
  ...appLocals,
132
257
  ...locals,
133
- ...data,
258
+ csrfToken,
259
+ ...(flash ? { flash } : {}),
260
+ ...viewData,
134
261
  };
135
262
 
136
- const renderFn = typeof view.module.default === "function" ? view.module.default : view.module;
263
+ const renderFn =
264
+ typeof view.module.default === "function" ? view.module.default : view.module;
137
265
  const content = await renderFn(mergedData, ctx);
138
- const bodyHtml = content instanceof SafeHtml ? content.toString() : String(content ?? "");
266
+ const bodyHtml = await resolveOutputToHtml(content, ctx);
139
267
 
140
268
  const layoutName =
141
269
  data._layout !== undefined
@@ -148,13 +276,22 @@ export class Render {
148
276
  rendered = bodyHtml;
149
277
  } else {
150
278
  const layoutView = await ViewLoader.loadLayout(layoutName);
151
- if (layoutView && layoutView.type === "js") {
152
- let headData = { title: mergedData.title || "Bluebird App" };
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
+ };
153
284
  if (view.module.head) {
154
- headData =
285
+ const declaredHead =
155
286
  typeof view.module.head === "function"
156
287
  ? await view.module.head(mergedData, ctx)
157
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
+ }
158
295
  }
159
296
 
160
297
  const layoutFn =
@@ -162,15 +299,32 @@ export class Render {
162
299
  ? layoutView.module.default
163
300
  : layoutView.module;
164
301
 
302
+ const safeBody = html.raw(bodyHtml);
165
303
  const layoutOutput = await layoutFn({
166
- body: html.raw(bodyHtml),
167
- content: html.raw(bodyHtml),
304
+ body: safeBody,
305
+ content: safeBody,
306
+ children: safeBody,
168
307
  head: headData,
169
308
  ctx,
170
309
  data: mergedData,
171
310
  });
172
311
 
173
- rendered = layoutOutput instanceof SafeHtml ? layoutOutput.toString() : String(layoutOutput ?? "");
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
+ }
174
328
  } else {
175
329
  rendered = bodyHtml;
176
330
  }
@@ -180,7 +334,6 @@ export class Render {
180
334
  }
181
335
 
182
336
  if (ttl !== undefined && ttl > 0 && !DEBUG) {
183
- const cacheKey = `view:${viewName}`;
184
337
  await RenderCache.store(cacheKey, rendered, ttl);
185
338
  }
186
339
 
@@ -194,32 +347,47 @@ export class Render {
194
347
 
195
348
  /**
196
349
  * Express route handler generator.
350
+ * Supports static props object or a dynamic provider function (req, res) => Object | Promise<Object>.
197
351
  * @param {string} viewName - Logical view name.
198
- * @param {Object} [staticData={}] - Static props merged into data.
352
+ * @param {Object|Function} [dataOrFn={}] - Static props or dynamic provider function.
353
+ * @param {number} [ttl] - Optional route cache duration in seconds.
199
354
  * @returns {Function} Express route handler.
200
355
  */
201
- static view(viewName, staticData = {}) {
202
- return (req, res) => Render.send(res, viewName, staticData);
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
+ };
203
361
  }
204
362
 
205
363
  /**
206
364
  * Express middleware that caches the rendered HTML response for GET requests.
207
365
  * Respects partial requests with dedicated cache partitions.
208
366
  * @param {number} [seconds] - Cache duration in seconds.
367
+ * @param {Object} [options={}]
368
+ * @param {boolean} [options.allowAuthenticated=false]
209
369
  * @returns {Function}
210
370
  */
211
- static cache(seconds) {
371
+ static cache(seconds, options = {}) {
212
372
  const ttl = seconds ?? RENDER_CACHE_TTL;
373
+ const allowAuthenticated = options.allowAuthenticated === true;
213
374
 
214
375
  return async (req, res, next) => {
215
376
  if (DEBUG || req.method !== "GET") return next();
216
377
 
378
+ if (!allowAuthenticated && (req.headers.authorization || req.cookies?.auth || req.user)) {
379
+ return next();
380
+ }
381
+
217
382
  const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
218
383
  const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
219
384
  const cached = await RenderCache.lookup(key);
220
385
 
221
386
  if (cached) {
222
387
  res.set("Content-Type", "text/html; charset=utf-8");
388
+ if (isPartial) {
389
+ res.set("X-Bluebird-Partial", "1");
390
+ }
223
391
  res.set("X-Bluebird-Cache", "HIT");
224
392
  return res.send(cached);
225
393
  }
@@ -238,46 +406,193 @@ export class Render {
238
406
  }
239
407
 
240
408
  /**
241
- * Streams progressive HTML chunks with out-of-order deferred content resolution.
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
+ *
242
429
  * @param {import('express').Response} res - Express response object.
243
430
  * @param {string} viewName - Logical view identifier.
244
431
  * @param {Object} [data={}] - Initial data and promises.
432
+ * @param {number|Object} [options={}] - Cache duration (seconds) or options ({ ttl }).
245
433
  * @returns {Promise<void>}
246
434
  */
247
- static async stream(res, viewName, data = {}) {
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
+
248
468
  res.setHeader("Content-Type", "text/html; charset=utf-8");
249
469
  res.setHeader("Transfer-Encoding", "chunked");
250
470
  res.setHeader("X-Content-Type-Options", "nosniff");
471
+ res.setHeader("X-Bluebird-Cache", "MISS");
251
472
 
252
473
  const deferredTokens = [];
253
- const proxyData = new Proxy(data, {
474
+ const streamData = { ...data };
475
+ const proxyData = new Proxy(streamData, {
254
476
  get(target, prop) {
255
477
  const val = target[prop];
256
478
  if (val && typeof val === "object" && val.__bluebird_deferred__) {
257
- deferredTokens.push({ prop, ...val });
258
- return html.raw(`<div id="bb-defer-${prop}">${val.fallback}</div>`);
479
+ deferredTokens.push({ prop: String(prop), ...val });
480
+ return html.raw(`<div id="bb-defer-${String(prop)}">${val.fallback}</div>`);
259
481
  }
260
482
  return val;
261
483
  },
262
484
  });
263
485
 
264
- const view = await ViewLoader.load(viewName);
265
- if (!view) {
266
- res.status(404).json({ message: `View '${viewName}' not found.` });
267
- return;
268
- }
486
+ const locals = res.locals || {};
487
+ const appLocals = res.req?.app?.locals || {};
269
488
 
270
489
  let initialHtml = "";
271
- if (view.type === "js") {
272
- const renderFn = typeof view.module.default === "function" ? view.module.default : view.module;
273
- const ctx = { req: res.req, res, user: res.req?.user, data: proxyData };
274
- const out = await renderFn(proxyData, ctx);
275
- initialHtml = out instanceof SafeHtml ? out.toString() : String(out ?? "");
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
+ }
276
590
  } else {
277
591
  initialHtml = view.content || "";
278
592
  }
279
593
 
280
594
  res.write(initialHtml);
595
+ let assembledHtml = initialHtml;
281
596
 
282
597
  if (deferredTokens.length > 0) {
283
598
  await Promise.all(
@@ -285,9 +600,13 @@ export class Render {
285
600
  try {
286
601
  const resolved = await token.promise;
287
602
  const finalContent = await token.renderer(resolved);
288
- const strContent = finalContent instanceof SafeHtml ? finalContent.toString() : String(finalContent);
289
- 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();}})();</script>`;
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>`;
290
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
+ );
291
610
  } catch (err) {
292
611
  res.write(`<script>console.error("Deferred stream error on ${token.prop}:", ${safeJson(err.message)});</script>`);
293
612
  }
@@ -295,6 +614,32 @@ export class Render {
295
614
  );
296
615
  }
297
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
+
298
643
  res.end();
299
644
  }
300
645
 
@@ -315,6 +660,69 @@ export class Render {
315
660
  ViewLoader.clearCache();
316
661
  await RenderCache.invalidate(keys);
317
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
+ }
318
713
  }
319
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
+ };
320
728
  export default Render;