@seip/bluebird-js 0.0.1 → 0.1.1
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/.env_example +53 -53
- package/AGENTS.md +426 -403
- package/LICENSE +1 -1
- package/README.md +292 -285
- package/app/routes/api.js +50 -50
- package/app/routes/web.js +55 -53
- package/app/views/about.js +63 -0
- package/app/views/dashboard.js +147 -0
- package/app/views/index.js +80 -0
- package/app/views/layouts/main/view.js +81 -0
- package/app/views/legal/terms.html +19 -0
- package/app/views/login.js +80 -0
- package/core/app.d.ts +18 -18
- package/core/app.js +684 -644
- package/core/auth.d.ts +13 -13
- package/core/auth.js +326 -326
- package/core/cache.d.ts +17 -17
- package/core/cache.js +475 -475
- package/core/cli/doctor.js +287 -287
- package/core/cli/ecosystem.js +162 -162
- package/core/cli/init.js +779 -779
- package/core/cli/migrate.js +541 -541
- package/core/cli/model.js +66 -66
- package/core/cli/nginx.js +199 -199
- package/core/cli/route.js +120 -120
- package/core/cli/view.js +55 -36
- package/core/config.d.ts +3 -3
- package/core/config.js +111 -111
- package/core/csrf.d.ts +3 -3
- package/core/csrf.js +114 -114
- package/core/database.d.ts +15 -15
- package/core/database.js +636 -636
- package/core/debug.d.ts +3 -3
- package/core/debug.js +249 -249
- package/core/hash.d.ts +3 -3
- package/core/hash.js +194 -194
- package/core/html.d.ts +42 -0
- package/core/html.js +217 -0
- package/core/index.d.ts +1176 -1071
- package/core/logger.d.ts +3 -3
- package/core/logger.js +127 -124
- package/core/middleware.d.ts +3 -3
- package/core/middleware.js +28 -28
- package/core/model.d.ts +19 -19
- package/core/model.js +600 -600
- package/core/queue.d.ts +13 -13
- package/core/queue.js +172 -172
- package/core/ratelimit.d.ts +3 -3
- package/core/ratelimit.js +145 -145
- package/core/redis.d.ts +21 -21
- package/core/redis.js +230 -230
- package/core/render-cache.js +212 -0
- package/core/render.d.ts +3 -3
- package/core/render.js +199 -555
- package/core/router.d.ts +3 -3
- package/core/router.js +171 -171
- package/core/seo.d.ts +3 -3
- package/core/seo.js +106 -106
- package/core/swagger.d.ts +3 -3
- package/core/swagger.js +60 -60
- package/core/upload.d.ts +13 -13
- package/core/upload.js +102 -102
- package/core/util/colors.js +82 -82
- package/core/validate.d.ts +15 -15
- package/core/validate.js +364 -364
- package/core/view-loader.js +162 -0
- package/core/vite.d.ts +3 -3
- package/core/vite.js +145 -145
- package/core/ws.d.ts +13 -13
- package/core/ws.js +245 -245
- package/index.js +18 -18
- package/jsconfig.json +15 -15
- package/package.json +85 -86
- package/production.md +273 -273
- package/public/css/bluebird.min.css +1 -1
- package/public/js/bluebird-client.js +1780 -1662
- package/public/js/bluebird.min.js +1072 -1072
- package/app/views/about.html +0 -161
- package/app/views/dashboard.html +0 -140
- package/app/views/index.html +0 -150
- package/app/views/login.html +0 -144
package/core/render.js
CHANGED
|
@@ -1,436 +1,61 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { getRedisClient } from "./cache.js";
|
|
4
1
|
import Config from "./config.js";
|
|
5
|
-
import
|
|
2
|
+
import { html, SafeHtml, escapeHtml, safeJson } from "./html.js";
|
|
3
|
+
import RenderCache from "./render-cache.js";
|
|
4
|
+
import ViewLoader from "./view-loader.js";
|
|
6
5
|
|
|
7
6
|
const props = Config.props();
|
|
8
7
|
const DEBUG = props.debug;
|
|
9
|
-
const PM2_INSTANCES = parseInt(process.env.PM2_INSTANCES || "1", 10);
|
|
10
|
-
const RENDER_CACHE_MAX = parseInt(process.env.RENDER_CACHE_MAX || "500", 10);
|
|
11
8
|
const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
|
|
12
|
-
const VIEWS_DIR = path.join(process.cwd(), process.env.VIEWS_PATH || "app/views");
|
|
13
9
|
|
|
14
10
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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.
|
|
17
14
|
*/
|
|
18
|
-
|
|
19
|
-
return path.join(Config.userDataDir(), "app/cache");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const isMultiInstance = PM2_INSTANCES > 1;
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* In-memory LRU cache for rendered route HTML strings.
|
|
26
|
-
* @type {Map<string, {html: string, expiry: number}>}
|
|
27
|
-
*/
|
|
28
|
-
const lru = new Map();
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* In-memory template file cache (L0) to avoid disk I/O on dynamic uncached routes in production.
|
|
32
|
-
* @type {Map<string, {content: string, ext: string}>}
|
|
33
|
-
*/
|
|
34
|
-
const templateMemoryCache = new Map();
|
|
35
|
-
|
|
36
|
-
let fileCacheEnabled = false;
|
|
37
|
-
|
|
38
|
-
if (!DEBUG) {
|
|
39
|
-
try {
|
|
40
|
-
const cacheDir = getFileCacheDir();
|
|
41
|
-
fs.mkdirSync(cacheDir, { recursive: true });
|
|
42
|
-
fs.accessSync(cacheDir, fs.constants.W_OK);
|
|
43
|
-
fileCacheEnabled = true;
|
|
44
|
-
} catch {
|
|
45
|
-
console.warn("[RENDER] app/cache/ is not writable — file cache disabled.");
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Evicts the oldest LRU entry when the cap is exceeded.
|
|
51
|
-
*/
|
|
52
|
-
function evictLru() {
|
|
53
|
-
if (lru.size >= RENDER_CACHE_MAX) {
|
|
54
|
-
const key = lru.keys().next().value;
|
|
55
|
-
if (key !== undefined) lru.delete(key);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Returns a safe filesystem key derived from the cache key string.
|
|
61
|
-
* @param {string} key
|
|
62
|
-
* @returns {string}
|
|
63
|
-
*/
|
|
64
|
-
function toCacheFileName(key) {
|
|
65
|
-
return key.replace(/[^a-z0-9_-]/gi, "_").substring(0, 200) + ".html";
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Reads an HTML string from the file cache, respecting TTL.
|
|
70
|
-
* @param {string} key
|
|
71
|
-
* @returns {string|null}
|
|
72
|
-
*/
|
|
73
|
-
function readFileCache(key) {
|
|
74
|
-
if (!fileCacheEnabled) return null;
|
|
75
|
-
const file = path.join(getFileCacheDir(), toCacheFileName(key));
|
|
76
|
-
try {
|
|
77
|
-
const stats = fs.statSync(file);
|
|
78
|
-
const age = (Date.now() - stats.mtimeMs) / 1000;
|
|
79
|
-
if (age > RENDER_CACHE_TTL) return null;
|
|
80
|
-
return fs.readFileSync(file, "utf8");
|
|
81
|
-
} catch {
|
|
82
|
-
return null;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Writes an HTML string to the file cache.
|
|
88
|
-
* @param {string} key
|
|
89
|
-
* @param {string} html
|
|
90
|
-
*/
|
|
91
|
-
function writeFileCache(key, html) {
|
|
92
|
-
if (!fileCacheEnabled) return;
|
|
93
|
-
try {
|
|
94
|
-
const file = path.join(getFileCacheDir(), toCacheFileName(key));
|
|
95
|
-
fs.writeFileSync(file, html, "utf8");
|
|
96
|
-
} catch {}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Resolves a dot-notation key against a data object.
|
|
101
|
-
* @param {Object} obj
|
|
102
|
-
* @param {string} keyPath
|
|
103
|
-
* @returns {any}
|
|
104
|
-
*/
|
|
105
|
-
function resolvePath(obj, keyPath) {
|
|
106
|
-
if (!obj || typeof obj !== "object" || !keyPath) return undefined;
|
|
107
|
-
if (keyPath === "this" || keyPath === ".") return obj.this !== undefined ? obj.this : obj;
|
|
108
|
-
return keyPath.split(".").reduce((acc, k) => (acc && acc[k] !== undefined ? acc[k] : undefined), obj);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Escapes HTML special characters to prevent XSS in interpolated values.
|
|
113
|
-
* @param {string} str
|
|
114
|
-
* @returns {string}
|
|
115
|
-
*/
|
|
116
|
-
function escapeHtml(str) {
|
|
117
|
-
return str
|
|
118
|
-
.replace(/&/g, "&")
|
|
119
|
-
.replace(/</g, "<")
|
|
120
|
-
.replace(/>/g, ">")
|
|
121
|
-
.replace(/"/g, """)
|
|
122
|
-
.replace(/'/g, "'");
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Parses inline partial/component arguments like: title="Hello" count=10 user=currentUser
|
|
127
|
-
* @param {string} argsStr
|
|
128
|
-
* @param {Object} scopeData
|
|
129
|
-
* @returns {Object}
|
|
130
|
-
*/
|
|
131
|
-
function parsePartialProps(argsStr, scopeData) {
|
|
132
|
-
const propsObj = {};
|
|
133
|
-
if (!argsStr || !argsStr.trim()) return propsObj;
|
|
134
|
-
|
|
135
|
-
const propRegex = /([a-zA-Z0-9_$-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"']+))/g;
|
|
136
|
-
let match;
|
|
137
|
-
while ((match = propRegex.exec(argsStr)) !== null) {
|
|
138
|
-
const key = match[1];
|
|
139
|
-
if (match[2] !== undefined) {
|
|
140
|
-
propsObj[key] = match[2];
|
|
141
|
-
} else if (match[3] !== undefined) {
|
|
142
|
-
propsObj[key] = match[3];
|
|
143
|
-
} else if (match[4] !== undefined) {
|
|
144
|
-
const rawVal = match[4];
|
|
145
|
-
if (rawVal === "true") propsObj[key] = true;
|
|
146
|
-
else if (rawVal === "false") propsObj[key] = false;
|
|
147
|
-
else if (rawVal === "null") propsObj[key] = null;
|
|
148
|
-
else if (!Number.isNaN(Number(rawVal)) && rawVal.trim() !== "") propsObj[key] = Number(rawVal);
|
|
149
|
-
else propsObj[key] = resolvePath(scopeData, rawVal);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
return propsObj;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Evaluates a conditional expression from {{#if expr}} against the current scope.
|
|
157
|
-
* Supports negation (!expr) and simple equality (a == "b").
|
|
158
|
-
* @param {string} expr
|
|
159
|
-
* @param {Object} data
|
|
160
|
-
* @returns {boolean}
|
|
161
|
-
*/
|
|
162
|
-
function evaluateCondition(expr, data) {
|
|
163
|
-
const clean = expr.trim();
|
|
164
|
-
if (!clean) return false;
|
|
165
|
-
|
|
166
|
-
if (clean.startsWith("!")) {
|
|
167
|
-
return !evaluateCondition(clean.slice(1), data);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const eqMatch = clean.match(/^([\w.]+)\s*(===|==|!==|!=)\s*(?:"([^"]*)"|'([^']*)'|(\S+))$/);
|
|
171
|
-
if (eqMatch) {
|
|
172
|
-
const leftVal = resolvePath(data, eqMatch[1]);
|
|
173
|
-
const op = eqMatch[2];
|
|
174
|
-
let rightVal;
|
|
175
|
-
if (eqMatch[3] !== undefined) rightVal = eqMatch[3];
|
|
176
|
-
else if (eqMatch[4] !== undefined) rightVal = eqMatch[4];
|
|
177
|
-
else {
|
|
178
|
-
const raw = eqMatch[5];
|
|
179
|
-
if (raw === "true") rightVal = true;
|
|
180
|
-
else if (raw === "false") rightVal = false;
|
|
181
|
-
else if (raw === "null") rightVal = null;
|
|
182
|
-
else if (!Number.isNaN(Number(raw))) rightVal = Number(raw);
|
|
183
|
-
else rightVal = resolvePath(data, raw);
|
|
184
|
-
}
|
|
185
|
-
if (op === "===" || op === "==") return leftVal == rightVal;
|
|
186
|
-
if (op === "!==" || op === "!=") return leftVal != rightVal;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const val = resolvePath(data, clean);
|
|
190
|
-
if (Array.isArray(val)) return val.length > 0;
|
|
191
|
-
return Boolean(val);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* Reads a view, partial, or layout file from disk (or L0 memory cache in production).
|
|
196
|
-
* Searches direct path, partials/<name>, components/<name>, and layouts/<name>.
|
|
197
|
-
* @param {string} viewName
|
|
198
|
-
* @returns {{content: string, ext: string}|null}
|
|
199
|
-
*/
|
|
200
|
-
function readViewFile(viewName) {
|
|
201
|
-
if (!DEBUG && templateMemoryCache.has(viewName)) {
|
|
202
|
-
return templateMemoryCache.get(viewName);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
const cleanName = viewName.replace(/^\/+/, "");
|
|
206
|
-
const candidates = [
|
|
207
|
-
cleanName,
|
|
208
|
-
path.join("partials", cleanName),
|
|
209
|
-
path.join("components", cleanName),
|
|
210
|
-
path.join("layouts", cleanName),
|
|
211
|
-
];
|
|
212
|
-
|
|
213
|
-
for (const candidate of candidates) {
|
|
214
|
-
const htmlPath = path.join(VIEWS_DIR, `${candidate}.html`);
|
|
215
|
-
if (fs.existsSync(htmlPath)) {
|
|
216
|
-
const result = { content: fs.readFileSync(htmlPath, "utf8"), ext: "html" };
|
|
217
|
-
if (!DEBUG) templateMemoryCache.set(viewName, result);
|
|
218
|
-
return result;
|
|
219
|
-
}
|
|
220
|
-
const ejsPath = path.join(VIEWS_DIR, `${candidate}.ejs`);
|
|
221
|
-
if (fs.existsSync(ejsPath)) {
|
|
222
|
-
const result = { content: fs.readFileSync(ejsPath, "utf8"), ext: "ejs" };
|
|
223
|
-
if (!DEBUG) templateMemoryCache.set(viewName, result);
|
|
224
|
-
return result;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
return null;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Processes loops ({{#each}}), conditionals ({{#if}}), partials ({{> name props}}),
|
|
233
|
-
* and variable interpolations ({{{raw}}} and {{escaped}}) in an HTML template string.
|
|
234
|
-
* @param {string} html - Raw HTML template string.
|
|
235
|
-
* @param {Object} data - Key-value pairs to inject.
|
|
236
|
-
* @param {number} [depth=0] - Recursion depth guard for nested partials.
|
|
237
|
-
* @returns {string} Interpolated HTML.
|
|
238
|
-
*/
|
|
239
|
-
function interpolate(html, data, depth = 0) {
|
|
240
|
-
if (!html || typeof html !== "string") return "";
|
|
241
|
-
if (!data || typeof data !== "object") data = {};
|
|
242
|
-
if (depth > 15) return html;
|
|
243
|
-
|
|
244
|
-
let result = html;
|
|
245
|
-
|
|
246
|
-
const eachRegex = /\{\{#each\s+([\w.]+)(?:\s+as\s+(\w+))?(?:\s*,\s*(\w+))?\s*\}\}([\s\S]*?)\{\{\/each\}\}/g;
|
|
247
|
-
let safetyCounter = 0;
|
|
248
|
-
while (eachRegex.test(result) && safetyCounter++ < 50) {
|
|
249
|
-
result = result.replace(eachRegex, (_, listKey, itemVar, indexVar, innerBlock) => {
|
|
250
|
-
const list = resolvePath(data, listKey);
|
|
251
|
-
if (!Array.isArray(list) || list.length === 0) return "";
|
|
252
|
-
return list
|
|
253
|
-
.map((item, idx) => {
|
|
254
|
-
const itemScope = {
|
|
255
|
-
...data,
|
|
256
|
-
this: item,
|
|
257
|
-
"@index": idx,
|
|
258
|
-
"@first": idx === 0,
|
|
259
|
-
"@last": idx === list.length - 1,
|
|
260
|
-
};
|
|
261
|
-
if (typeof item === "object" && item !== null && !itemVar) {
|
|
262
|
-
Object.assign(itemScope, item);
|
|
263
|
-
}
|
|
264
|
-
if (itemVar) {
|
|
265
|
-
itemScope[itemVar] = item;
|
|
266
|
-
itemScope[`${itemVar}_index`] = idx;
|
|
267
|
-
}
|
|
268
|
-
if (indexVar) itemScope[indexVar] = idx;
|
|
269
|
-
return interpolate(innerBlock, itemScope, depth + 1);
|
|
270
|
-
})
|
|
271
|
-
.join("");
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const ifRegex = /\{\{#if\s+([^}]+)\}\}((?:(?!\{\{#if\b)[\s\S])*?)\{\{\/if\}\}/g;
|
|
276
|
-
safetyCounter = 0;
|
|
277
|
-
while (ifRegex.test(result) && safetyCounter++ < 50) {
|
|
278
|
-
result = result.replace(ifRegex, (_, conditionExpr, innerContent) => {
|
|
279
|
-
const parts = innerContent.split(/\{\{\s*else\s*\}\}/);
|
|
280
|
-
const trueBranch = parts[0] || "";
|
|
281
|
-
const falseBranch = parts[1] || "";
|
|
282
|
-
const isTruthy = evaluateCondition(conditionExpr, data);
|
|
283
|
-
return interpolate(isTruthy ? trueBranch : falseBranch, data, depth + 1);
|
|
284
|
-
});
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
result = result.replace(/\{\{>\s*([a-zA-Z0-9_/-]+)((?:\s+[^}]*)?)\}\}/g, (_, partialName, argsStr) => {
|
|
288
|
-
const partialView = readViewFile(partialName.trim());
|
|
289
|
-
if (!partialView) return "";
|
|
290
|
-
const inlineProps = parsePartialProps(argsStr, data);
|
|
291
|
-
const partialScope = { ...data, ...inlineProps };
|
|
292
|
-
return interpolate(partialView.content, partialScope, depth + 1);
|
|
293
|
-
});
|
|
294
|
-
|
|
295
|
-
result = result.replace(/\{\{\{\s*([\w.@]+)\s*\}\}\}/g, (_, key) => {
|
|
296
|
-
const val = key.startsWith("@") ? data[key] : resolvePath(data, key);
|
|
297
|
-
if (val === undefined || val === null) return "";
|
|
298
|
-
if (typeof val === "object") {
|
|
299
|
-
try {
|
|
300
|
-
return JSON.stringify(val);
|
|
301
|
-
} catch {
|
|
302
|
-
return String(val);
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
return String(val);
|
|
306
|
-
});
|
|
307
|
-
|
|
308
|
-
result = result.replace(/\{\{\s*([\w.@]+)\s*\}\}/g, (_, key) => {
|
|
309
|
-
const val = key.startsWith("@") ? data[key] : resolvePath(data, key);
|
|
310
|
-
if (val === undefined || val === null) return "";
|
|
311
|
-
if (typeof val === "object") {
|
|
312
|
-
try {
|
|
313
|
-
return escapeHtml(JSON.stringify(val));
|
|
314
|
-
} catch {
|
|
315
|
-
return escapeHtml(String(val));
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
return escapeHtml(String(val));
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
return result;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* Looks up a rendered HTML string from L1 (memory LRU), L2 (Redis), or L3 (file).
|
|
326
|
-
* @param {string} key
|
|
327
|
-
* @returns {Promise<string|null>}
|
|
328
|
-
*/
|
|
329
|
-
async function lookupCache(key) {
|
|
330
|
-
const entry = lru.get(key);
|
|
331
|
-
if (entry && entry.expiry > Date.now()) {
|
|
332
|
-
lru.delete(key);
|
|
333
|
-
lru.set(key, entry);
|
|
334
|
-
return entry.html;
|
|
335
|
-
}
|
|
336
|
-
if (entry) lru.delete(key);
|
|
337
|
-
|
|
338
|
-
if (isMultiInstance) {
|
|
339
|
-
const redis = getRedisClient();
|
|
340
|
-
if (redis) {
|
|
341
|
-
try {
|
|
342
|
-
const val = await redis.get(`render:${key}`);
|
|
343
|
-
if (val) {
|
|
344
|
-
evictLru();
|
|
345
|
-
lru.set(key, { html: val, expiry: Date.now() + RENDER_CACHE_TTL * 1000 });
|
|
346
|
-
return val;
|
|
347
|
-
}
|
|
348
|
-
} catch {}
|
|
349
|
-
} else {
|
|
350
|
-
const fromFile = readFileCache(key);
|
|
351
|
-
if (fromFile) {
|
|
352
|
-
evictLru();
|
|
353
|
-
lru.set(key, { html: fromFile, expiry: Date.now() + RENDER_CACHE_TTL * 1000 });
|
|
354
|
-
return fromFile;
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
return null;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Stores a rendered HTML string in all available cache layers.
|
|
364
|
-
* @param {string} key
|
|
365
|
-
* @param {string} html
|
|
366
|
-
* @param {number} [ttl=RENDER_CACHE_TTL]
|
|
367
|
-
* @returns {Promise<void>}
|
|
368
|
-
*/
|
|
369
|
-
async function storeCache(key, html, ttl = RENDER_CACHE_TTL) {
|
|
370
|
-
evictLru();
|
|
371
|
-
lru.set(key, { html, expiry: Date.now() + ttl * 1000 });
|
|
372
|
-
|
|
373
|
-
if (isMultiInstance) {
|
|
374
|
-
const redis = getRedisClient();
|
|
375
|
-
if (redis) {
|
|
376
|
-
try {
|
|
377
|
-
await redis.set(`render:${key}`, html, { EX: ttl });
|
|
378
|
-
return;
|
|
379
|
-
} catch {}
|
|
380
|
-
}
|
|
381
|
-
writeFileCache(key, html);
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/**
|
|
386
|
-
* HTML render engine for Bluebird.
|
|
387
|
-
*
|
|
388
|
-
* Features:
|
|
389
|
-
* - L0 In-Memory Template Caching (zero disk I/O in production even for dynamic routes)
|
|
390
|
-
* - Built-in Partials & Server Components: {{> card title="Users" count=stats.users }}
|
|
391
|
-
* - Shared Layouts: {{!< main }} at top of view or { _layout: "main" }
|
|
392
|
-
* - Loops & Conditionals: {{#each items as item}}...{{/each}} and {{#if cond}}...{{else}}...{{/if}}
|
|
393
|
-
* - Fragment / Partial responses for SPA & Dashboard updates: Render.partial()
|
|
394
|
-
* - React Islands helper: Render.island()
|
|
395
|
-
*/
|
|
396
|
-
class Render {
|
|
15
|
+
export class Render {
|
|
397
16
|
/**
|
|
398
|
-
* Generates
|
|
17
|
+
* Generates declarative HTML markup for client-side island hydration.
|
|
399
18
|
* @param {string} name - Island component name.
|
|
400
19
|
* @param {Object} [props={}] - Initial props passed to the component.
|
|
401
20
|
* @param {Object} [options={}] - Island options.
|
|
402
|
-
* @param {boolean} [options.persist=false] -
|
|
403
|
-
* @param {string} [options.fallback=""] - HTML
|
|
404
|
-
* @param {string} [options.tag="div"] -
|
|
21
|
+
* @param {boolean} [options.persist=false] - Preserves island across View Transitions.
|
|
22
|
+
* @param {string} [options.fallback=""] - Fallback HTML content.
|
|
23
|
+
* @param {string} [options.tag="div"] - Container tag name.
|
|
405
24
|
* @returns {string} Declarative HTML markup.
|
|
406
25
|
*/
|
|
407
26
|
static island(name, props = {}, options = {}) {
|
|
408
27
|
const tag = options.tag || "div";
|
|
409
28
|
const persistAttr = options.persist ? ' data-persist="true"' : "";
|
|
410
|
-
const serializedProps = escapeHtml(
|
|
29
|
+
const serializedProps = escapeHtml(safeJson(props));
|
|
411
30
|
const fallback = options.fallback || "";
|
|
412
31
|
return `<${tag} data-island="${escapeHtml(name)}" data-props="${serializedProps}"${persistAttr}>${fallback}</${tag}>`;
|
|
413
32
|
}
|
|
414
33
|
|
|
415
34
|
/**
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
* @param {
|
|
419
|
-
* @
|
|
420
|
-
* @returns {string} Rendered HTML string.
|
|
35
|
+
* Synchronously or asynchronously renders a component or view to a raw HTML string.
|
|
36
|
+
* @param {string} viewName - Component or view name.
|
|
37
|
+
* @param {Object} [data={}] - Props and context.
|
|
38
|
+
* @returns {Promise<string>}
|
|
421
39
|
*/
|
|
422
|
-
static component(viewName, data = {}) {
|
|
423
|
-
const view =
|
|
40
|
+
static async component(viewName, data = {}) {
|
|
41
|
+
const view = await ViewLoader.load(viewName);
|
|
424
42
|
if (!view) return "";
|
|
425
|
-
|
|
43
|
+
|
|
44
|
+
if (view.type === "js") {
|
|
45
|
+
const renderFn = typeof view.module.default === "function" ? view.module.default : view.module;
|
|
46
|
+
const ctx = { data };
|
|
47
|
+
const output = await renderFn(data, ctx);
|
|
48
|
+
return output instanceof SafeHtml ? output.toString() : String(output ?? "");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return view.content || "";
|
|
426
52
|
}
|
|
427
53
|
|
|
428
54
|
/**
|
|
429
|
-
* Sends a rendered
|
|
430
|
-
* Ideal for dynamic dashboard updates and AJAX/fetch partial swaps.
|
|
55
|
+
* Sends a rendered partial fragment without applying a layout.
|
|
431
56
|
* @param {import('express').Response} res - Express response object.
|
|
432
|
-
* @param {string} partialName -
|
|
433
|
-
* @param {Object} [data={}] - Data to
|
|
57
|
+
* @param {string} partialName - View or component name.
|
|
58
|
+
* @param {Object} [data={}] - Data to pass.
|
|
434
59
|
* @returns {Promise<any>}
|
|
435
60
|
*/
|
|
436
61
|
static async partial(res, partialName, data = {}) {
|
|
@@ -438,13 +63,36 @@ class Render {
|
|
|
438
63
|
}
|
|
439
64
|
|
|
440
65
|
/**
|
|
441
|
-
*
|
|
442
|
-
*
|
|
443
|
-
*
|
|
66
|
+
* Serves an unparsed, raw HTML file without layouts or server interpolation.
|
|
67
|
+
* Ideal for legal policies, static terms, or offline pages.
|
|
68
|
+
*
|
|
69
|
+
* @param {import('express').Response} res - Express response object.
|
|
70
|
+
* @param {string} relativePath - Path to HTML file inside app/views.
|
|
71
|
+
* @param {Object} [options={}] - Optional HTTP cache settings.
|
|
72
|
+
* @param {number} [options.ttl] - Cache TTL in seconds.
|
|
73
|
+
* @returns {Promise<any>}
|
|
74
|
+
*/
|
|
75
|
+
static async html(res, relativePath, options = {}) {
|
|
76
|
+
const view = await ViewLoader.load(relativePath);
|
|
77
|
+
if (!view || !view.content) {
|
|
78
|
+
return res.status(404).json({ message: `Static HTML '${relativePath}' not found.` });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (options.ttl && options.ttl > 0 && !DEBUG) {
|
|
82
|
+
res.set("Cache-Control", `public, max-age=${options.ttl}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
86
|
+
return res.send(view.content);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Sends a rendered HTML view response with full layout and head asset resolution.
|
|
91
|
+
*
|
|
444
92
|
* @param {import('express').Response} res - Express response object.
|
|
445
|
-
* @param {string} viewName -
|
|
446
|
-
* @param {Object} [data={}] - Data to
|
|
447
|
-
* @param {number} [ttl] - Optional route cache TTL in seconds
|
|
93
|
+
* @param {string} viewName - Logical view identifier.
|
|
94
|
+
* @param {Object} [data={}] - Data passed to the view and layout.
|
|
95
|
+
* @param {number} [ttl] - Optional route cache TTL in seconds.
|
|
448
96
|
* @returns {Promise<any>}
|
|
449
97
|
*/
|
|
450
98
|
static async send(res, viewName, data = {}, ttl) {
|
|
@@ -455,60 +103,85 @@ class Render {
|
|
|
455
103
|
res.req?.headers?.["x-bluebird-partial"] === "1" ||
|
|
456
104
|
res.req?.query?._partial === "1";
|
|
457
105
|
|
|
458
|
-
const
|
|
459
|
-
bluebirdHead: Vite.tags(),
|
|
460
|
-
...appLocals,
|
|
461
|
-
...locals,
|
|
462
|
-
...data,
|
|
463
|
-
};
|
|
464
|
-
|
|
465
|
-
const view = readViewFile(viewName);
|
|
106
|
+
const view = await ViewLoader.load(viewName);
|
|
466
107
|
if (!view) {
|
|
467
108
|
return res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
468
109
|
}
|
|
469
110
|
|
|
470
|
-
let rendered;
|
|
111
|
+
let rendered = "";
|
|
471
112
|
|
|
472
|
-
if (view.
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
if (layoutName === null) {
|
|
487
|
-
layoutName = layoutDirective[1].trim();
|
|
113
|
+
if (view.type === "js") {
|
|
114
|
+
const ctx = {
|
|
115
|
+
req: res.req,
|
|
116
|
+
res,
|
|
117
|
+
user: res.req?.user,
|
|
118
|
+
locals,
|
|
119
|
+
appLocals,
|
|
120
|
+
data,
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
if (typeof view.module.load === "function") {
|
|
124
|
+
const loadedData = await view.module.load(ctx);
|
|
125
|
+
if (loadedData && typeof loadedData === "object") {
|
|
126
|
+
Object.assign(data, loadedData);
|
|
488
127
|
}
|
|
489
128
|
}
|
|
490
129
|
|
|
491
|
-
const
|
|
130
|
+
const mergedData = {
|
|
131
|
+
...appLocals,
|
|
132
|
+
...locals,
|
|
133
|
+
...data,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const renderFn = typeof view.module.default === "function" ? view.module.default : view.module;
|
|
137
|
+
const content = await renderFn(mergedData, ctx);
|
|
138
|
+
const bodyHtml = content instanceof SafeHtml ? content.toString() : String(content ?? "");
|
|
139
|
+
|
|
140
|
+
const layoutName =
|
|
141
|
+
data._layout !== undefined
|
|
142
|
+
? data._layout
|
|
143
|
+
: view.module.layout !== undefined
|
|
144
|
+
? view.module.layout
|
|
145
|
+
: "main";
|
|
146
|
+
|
|
147
|
+
if (isPartialRequest || layoutName === false) {
|
|
148
|
+
rendered = bodyHtml;
|
|
149
|
+
} else {
|
|
150
|
+
const layoutView = await ViewLoader.loadLayout(layoutName);
|
|
151
|
+
if (layoutView && layoutView.type === "js") {
|
|
152
|
+
let headData = { title: mergedData.title || "Bluebird App" };
|
|
153
|
+
if (view.module.head) {
|
|
154
|
+
headData =
|
|
155
|
+
typeof view.module.head === "function"
|
|
156
|
+
? await view.module.head(mergedData, ctx)
|
|
157
|
+
: view.module.head;
|
|
158
|
+
}
|
|
492
159
|
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
160
|
+
const layoutFn =
|
|
161
|
+
typeof layoutView.module.default === "function"
|
|
162
|
+
? layoutView.module.default
|
|
163
|
+
: layoutView.module;
|
|
164
|
+
|
|
165
|
+
const layoutOutput = await layoutFn({
|
|
166
|
+
body: html.raw(bodyHtml),
|
|
167
|
+
content: html.raw(bodyHtml),
|
|
168
|
+
head: headData,
|
|
169
|
+
ctx,
|
|
170
|
+
data: mergedData,
|
|
500
171
|
});
|
|
172
|
+
|
|
173
|
+
rendered = layoutOutput instanceof SafeHtml ? layoutOutput.toString() : String(layoutOutput ?? "");
|
|
501
174
|
} else {
|
|
502
175
|
rendered = bodyHtml;
|
|
503
176
|
}
|
|
504
|
-
} else {
|
|
505
|
-
rendered = bodyHtml;
|
|
506
177
|
}
|
|
178
|
+
} else {
|
|
179
|
+
rendered = view.content || "";
|
|
507
180
|
}
|
|
508
181
|
|
|
509
182
|
if (ttl !== undefined && ttl > 0 && !DEBUG) {
|
|
510
183
|
const cacheKey = `view:${viewName}`;
|
|
511
|
-
await
|
|
184
|
+
await RenderCache.store(cacheKey, rendered, ttl);
|
|
512
185
|
}
|
|
513
186
|
|
|
514
187
|
res.set("Content-Type", "text/html; charset=utf-8");
|
|
@@ -520,76 +193,20 @@ class Render {
|
|
|
520
193
|
}
|
|
521
194
|
|
|
522
195
|
/**
|
|
523
|
-
*
|
|
524
|
-
*
|
|
525
|
-
* @param {
|
|
526
|
-
* @
|
|
527
|
-
* @param {Object} [data={}] - Data object (values may be Promises).
|
|
528
|
-
* @returns {Promise<void>}
|
|
529
|
-
*/
|
|
530
|
-
static async stream(res, viewName, data = {}) {
|
|
531
|
-
const view = readViewFile(viewName);
|
|
532
|
-
if (!view) {
|
|
533
|
-
res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
534
|
-
return;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
538
|
-
res.setHeader("Transfer-Encoding", "chunked");
|
|
539
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
540
|
-
|
|
541
|
-
const resolvedData = {};
|
|
542
|
-
const entries = Object.entries(data);
|
|
543
|
-
await Promise.all(
|
|
544
|
-
entries.map(async ([k, v]) => {
|
|
545
|
-
resolvedData[k] = v instanceof Promise || (v && typeof v.then === "function") ? await v : v;
|
|
546
|
-
})
|
|
547
|
-
);
|
|
548
|
-
|
|
549
|
-
const locals = res.locals || {};
|
|
550
|
-
const appLocals = res.req?.app?.locals || {};
|
|
551
|
-
const mergedData = {
|
|
552
|
-
bluebirdHead: Vite.tags(),
|
|
553
|
-
...appLocals,
|
|
554
|
-
...locals,
|
|
555
|
-
...resolvedData,
|
|
556
|
-
};
|
|
557
|
-
|
|
558
|
-
const html = interpolate(view.content, mergedData);
|
|
559
|
-
const headCloseIdx = html.indexOf("</head>");
|
|
560
|
-
if (headCloseIdx !== -1) {
|
|
561
|
-
const headChunk = html.slice(0, headCloseIdx + 7);
|
|
562
|
-
const bodyChunk = html.slice(headCloseIdx + 7);
|
|
563
|
-
res.write(headChunk);
|
|
564
|
-
res.write(bodyChunk);
|
|
565
|
-
res.end();
|
|
566
|
-
} else {
|
|
567
|
-
res.write(html);
|
|
568
|
-
res.end();
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
/**
|
|
573
|
-
* Returns an Express route handler that renders a view.
|
|
574
|
-
* Designed to be used directly as a route callback.
|
|
575
|
-
* @param {string} viewName - View file name without extension.
|
|
576
|
-
* @param {Object} [staticData={}] - Static data merged before request-time data.
|
|
577
|
-
* @returns {Function} Express route handler (req, res) => void.
|
|
578
|
-
* @example
|
|
579
|
-
* web.get("/", Render.view("index"));
|
|
580
|
-
* web.get("/about", Render.view("about", { company: "Blue Bird" }));
|
|
196
|
+
* Express route handler generator.
|
|
197
|
+
* @param {string} viewName - Logical view name.
|
|
198
|
+
* @param {Object} [staticData={}] - Static props merged into data.
|
|
199
|
+
* @returns {Function} Express route handler.
|
|
581
200
|
*/
|
|
582
201
|
static view(viewName, staticData = {}) {
|
|
583
202
|
return (req, res) => Render.send(res, viewName, staticData);
|
|
584
203
|
}
|
|
585
204
|
|
|
586
205
|
/**
|
|
587
|
-
* Express middleware that caches the
|
|
588
|
-
* Respects partial requests
|
|
589
|
-
* @param {number} [seconds] - Cache duration in seconds
|
|
590
|
-
* @returns {Function}
|
|
591
|
-
* @example
|
|
592
|
-
* web.get("/dashboard", Auth.protect(), Render.cache(600), Render.view("dashboard"));
|
|
206
|
+
* Express middleware that caches the rendered HTML response for GET requests.
|
|
207
|
+
* Respects partial requests with dedicated cache partitions.
|
|
208
|
+
* @param {number} [seconds] - Cache duration in seconds.
|
|
209
|
+
* @returns {Function}
|
|
593
210
|
*/
|
|
594
211
|
static cache(seconds) {
|
|
595
212
|
const ttl = seconds ?? RENDER_CACHE_TTL;
|
|
@@ -599,7 +216,8 @@ class Render {
|
|
|
599
216
|
|
|
600
217
|
const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
|
|
601
218
|
const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
|
|
602
|
-
const cached = await
|
|
219
|
+
const cached = await RenderCache.lookup(key);
|
|
220
|
+
|
|
603
221
|
if (cached) {
|
|
604
222
|
res.set("Content-Type", "text/html; charset=utf-8");
|
|
605
223
|
res.set("X-Bluebird-Cache", "HIT");
|
|
@@ -609,7 +227,7 @@ class Render {
|
|
|
609
227
|
const originalSend = res.send.bind(res);
|
|
610
228
|
res.send = async (body) => {
|
|
611
229
|
if (typeof body === "string" && res.statusCode === 200) {
|
|
612
|
-
await
|
|
230
|
+
await RenderCache.store(key, body, ttl);
|
|
613
231
|
}
|
|
614
232
|
res.set("X-Bluebird-Cache", "MISS");
|
|
615
233
|
return originalSend(body);
|
|
@@ -620,57 +238,83 @@ class Render {
|
|
|
620
238
|
}
|
|
621
239
|
|
|
622
240
|
/**
|
|
623
|
-
*
|
|
624
|
-
* @
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
templateMemoryCache.clear();
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
/**
|
|
631
|
-
* Invalidates the render cache for one or more view names or route URLs.
|
|
632
|
-
* Also clears L0 template memory cache entries.
|
|
633
|
-
* @param {string|string[]} [keys] - View names or route URLs to invalidate. If omitted, clears all template cache.
|
|
241
|
+
* Streams progressive HTML chunks with out-of-order deferred content resolution.
|
|
242
|
+
* @param {import('express').Response} res - Express response object.
|
|
243
|
+
* @param {string} viewName - Logical view identifier.
|
|
244
|
+
* @param {Object} [data={}] - Initial data and promises.
|
|
634
245
|
* @returns {Promise<void>}
|
|
635
246
|
*/
|
|
636
|
-
static async
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
247
|
+
static async stream(res, viewName, data = {}) {
|
|
248
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
249
|
+
res.setHeader("Transfer-Encoding", "chunked");
|
|
250
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
251
|
+
|
|
252
|
+
const deferredTokens = [];
|
|
253
|
+
const proxyData = new Proxy(data, {
|
|
254
|
+
get(target, prop) {
|
|
255
|
+
const val = target[prop];
|
|
256
|
+
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>`);
|
|
259
|
+
}
|
|
260
|
+
return val;
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
const view = await ViewLoader.load(viewName);
|
|
265
|
+
if (!view) {
|
|
266
|
+
res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
640
267
|
return;
|
|
641
268
|
}
|
|
642
269
|
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
const
|
|
646
|
-
const
|
|
647
|
-
const
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
if (redis) {
|
|
655
|
-
try {
|
|
656
|
-
await redis.del(`render:${viewKey}`);
|
|
657
|
-
await redis.del(`render:${routeKey}`);
|
|
658
|
-
await redis.del(`render:${partialRouteKey}`);
|
|
659
|
-
} catch {}
|
|
660
|
-
}
|
|
270
|
+
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 ?? "");
|
|
276
|
+
} else {
|
|
277
|
+
initialHtml = view.content || "";
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
res.write(initialHtml);
|
|
661
281
|
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
282
|
+
if (deferredTokens.length > 0) {
|
|
283
|
+
await Promise.all(
|
|
284
|
+
deferredTokens.map(async (token) => {
|
|
665
285
|
try {
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
286
|
+
const resolved = await token.promise;
|
|
287
|
+
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>`;
|
|
290
|
+
res.write(script);
|
|
291
|
+
} catch (err) {
|
|
292
|
+
res.write(`<script>console.error("Deferred stream error on ${token.prop}:", ${safeJson(err.message)});</script>`);
|
|
293
|
+
}
|
|
294
|
+
})
|
|
295
|
+
);
|
|
671
296
|
}
|
|
297
|
+
|
|
298
|
+
res.end();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Clears all in-memory view and template caches.
|
|
303
|
+
*/
|
|
304
|
+
static clearTemplateCache() {
|
|
305
|
+
ViewLoader.clearCache();
|
|
306
|
+
RenderCache.clearMemory();
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Invalidates caches for specific views or route keys.
|
|
311
|
+
* @param {string|string[]} [keys]
|
|
312
|
+
* @returns {Promise<void>}
|
|
313
|
+
*/
|
|
314
|
+
static async invalidate(keys) {
|
|
315
|
+
ViewLoader.clearCache();
|
|
316
|
+
await RenderCache.invalidate(keys);
|
|
672
317
|
}
|
|
673
318
|
}
|
|
674
319
|
|
|
675
|
-
export { Render };
|
|
676
320
|
export default Render;
|