@seip/bluebird-js 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env_example +54 -0
- package/AGENTS.md +426 -0
- package/LICENSE +21 -0
- package/README.md +292 -3
- package/app/routes/api.js +50 -0
- package/app/routes/web.js +55 -0
- 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 -0
- package/core/app.js +684 -0
- package/core/auth.d.ts +13 -0
- package/core/auth.js +326 -0
- package/core/cache.d.ts +17 -0
- package/core/cache.js +475 -0
- package/core/cli/doctor.js +287 -0
- package/core/cli/ecosystem.js +162 -0
- package/core/cli/init.js +779 -0
- package/core/cli/migrate.js +541 -0
- package/core/cli/model.js +66 -0
- package/core/cli/nginx.js +199 -0
- package/core/cli/route.js +121 -0
- package/core/cli/swagger.js +45 -0
- package/core/cli/view.js +96 -0
- package/core/config.d.ts +3 -0
- package/core/config.js +111 -0
- package/core/csrf.d.ts +3 -0
- package/core/csrf.js +114 -0
- package/core/database.d.ts +15 -0
- package/core/database.js +636 -0
- package/core/debug.d.ts +3 -0
- package/core/debug.js +250 -0
- package/core/hash.d.ts +3 -0
- package/core/hash.js +194 -0
- package/core/html.d.ts +42 -0
- package/core/html.js +217 -0
- package/core/index.d.ts +1176 -0
- package/core/logger.d.ts +3 -0
- package/core/logger.js +127 -0
- package/core/middleware.d.ts +3 -0
- package/core/middleware.js +28 -0
- package/core/model.d.ts +19 -0
- package/core/model.js +600 -0
- package/core/queue.d.ts +13 -0
- package/core/queue.js +172 -0
- package/core/ratelimit.d.ts +3 -0
- package/core/ratelimit.js +145 -0
- package/core/redis.d.ts +21 -0
- package/core/redis.js +230 -0
- package/core/render-cache.js +212 -0
- package/core/render.d.ts +3 -0
- package/core/render.js +320 -0
- package/core/router.d.ts +3 -0
- package/core/router.js +171 -0
- package/core/seo.d.ts +3 -0
- package/core/seo.js +106 -0
- package/core/swagger.d.ts +3 -0
- package/core/swagger.js +60 -0
- package/core/upload.d.ts +13 -0
- package/core/upload.js +102 -0
- package/core/util/colors.js +82 -0
- package/core/validate.d.ts +15 -0
- package/core/validate.js +364 -0
- package/core/view-loader.js +162 -0
- package/core/vite.d.ts +3 -0
- package/core/vite.js +145 -0
- package/core/ws.d.ts +13 -0
- package/core/ws.js +245 -0
- package/index.js +18 -0
- package/jsconfig.json +15 -0
- package/package.json +85 -5
- package/production.md +273 -0
- package/public/css/bluebird.min.css +2 -0
- package/public/images/favicon.ico +0 -0
- package/public/js/bluebird-client.js +1781 -0
- package/public/js/bluebird.min.js +1073 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { getRedisClient } from "./cache.js";
|
|
4
|
+
import Config from "./config.js";
|
|
5
|
+
|
|
6
|
+
const props = Config.props();
|
|
7
|
+
const DEBUG = props.debug;
|
|
8
|
+
const PM2_INSTANCES = parseInt(process.env.PM2_INSTANCES || "1", 10);
|
|
9
|
+
const RENDER_CACHE_MAX = parseInt(process.env.RENDER_CACHE_MAX || "500", 10);
|
|
10
|
+
const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
|
|
11
|
+
|
|
12
|
+
const isMultiInstance = PM2_INSTANCES > 1;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Resolves the writable render file cache directory.
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
function getFileCacheDir() {
|
|
19
|
+
return path.join(Config.userDataDir(), "app/cache");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let fileCacheEnabled = false;
|
|
23
|
+
|
|
24
|
+
if (!DEBUG) {
|
|
25
|
+
try {
|
|
26
|
+
const cacheDir = getFileCacheDir();
|
|
27
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
28
|
+
fs.accessSync(cacheDir, fs.constants.W_OK);
|
|
29
|
+
fileCacheEnabled = true;
|
|
30
|
+
} catch {
|
|
31
|
+
console.warn("[RENDER CACHE] app/cache/ is not writable — file cache disabled.");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* In-memory LRU cache map.
|
|
37
|
+
* @type {Map<string, {value: string, expiry: number}>}
|
|
38
|
+
*/
|
|
39
|
+
const lru = new Map();
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Evicts the oldest LRU entry when the cap is exceeded.
|
|
43
|
+
*/
|
|
44
|
+
function evictLru() {
|
|
45
|
+
if (lru.size >= RENDER_CACHE_MAX) {
|
|
46
|
+
const key = lru.keys().next().value;
|
|
47
|
+
if (key !== undefined) lru.delete(key);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Returns a safe filesystem key derived from the cache key string.
|
|
53
|
+
* @param {string} key
|
|
54
|
+
* @returns {string}
|
|
55
|
+
*/
|
|
56
|
+
function toCacheFileName(key) {
|
|
57
|
+
return key.replace(/[^a-z0-9_-]/gi, "_").substring(0, 200) + ".html";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Reads a cached string from the file cache, respecting TTL.
|
|
62
|
+
* @param {string} key
|
|
63
|
+
* @returns {string|null}
|
|
64
|
+
*/
|
|
65
|
+
function readFileCache(key) {
|
|
66
|
+
if (!fileCacheEnabled) return null;
|
|
67
|
+
const file = path.join(getFileCacheDir(), toCacheFileName(key));
|
|
68
|
+
try {
|
|
69
|
+
const stats = fs.statSync(file);
|
|
70
|
+
const age = (Date.now() - stats.mtimeMs) / 1000;
|
|
71
|
+
if (age > RENDER_CACHE_TTL) return null;
|
|
72
|
+
return fs.readFileSync(file, "utf8");
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Writes a string to the file cache.
|
|
80
|
+
* @param {string} key
|
|
81
|
+
* @param {string} value
|
|
82
|
+
*/
|
|
83
|
+
function writeFileCache(key, value) {
|
|
84
|
+
if (!fileCacheEnabled) return;
|
|
85
|
+
try {
|
|
86
|
+
const file = path.join(getFileCacheDir(), toCacheFileName(key));
|
|
87
|
+
fs.writeFileSync(file, value, "utf8");
|
|
88
|
+
} catch {}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Multi-layer rendering cache manager.
|
|
93
|
+
* Provides L1 (In-Memory LRU), L2 (Redis), and L3 (File) caching layers.
|
|
94
|
+
*/
|
|
95
|
+
export class RenderCache {
|
|
96
|
+
/**
|
|
97
|
+
* Looks up a cached HTML string across memory, Redis, and file cache.
|
|
98
|
+
* @param {string} key - Cache key.
|
|
99
|
+
* @returns {Promise<string|null>}
|
|
100
|
+
*/
|
|
101
|
+
static async lookup(key) {
|
|
102
|
+
const entry = lru.get(key);
|
|
103
|
+
if (entry && entry.expiry > Date.now()) {
|
|
104
|
+
lru.delete(key);
|
|
105
|
+
lru.set(key, entry);
|
|
106
|
+
return entry.value;
|
|
107
|
+
}
|
|
108
|
+
if (entry) lru.delete(key);
|
|
109
|
+
|
|
110
|
+
if (isMultiInstance) {
|
|
111
|
+
const redis = getRedisClient();
|
|
112
|
+
if (redis) {
|
|
113
|
+
try {
|
|
114
|
+
const val = await redis.get(`render:${key}`);
|
|
115
|
+
if (val) {
|
|
116
|
+
evictLru();
|
|
117
|
+
lru.set(key, { value: val, expiry: Date.now() + RENDER_CACHE_TTL * 1000 });
|
|
118
|
+
return val;
|
|
119
|
+
}
|
|
120
|
+
} catch {}
|
|
121
|
+
} else {
|
|
122
|
+
const fromFile = readFileCache(key);
|
|
123
|
+
if (fromFile) {
|
|
124
|
+
evictLru();
|
|
125
|
+
lru.set(key, { value: fromFile, expiry: Date.now() + RENDER_CACHE_TTL * 1000 });
|
|
126
|
+
return fromFile;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Stores a rendered string in all active cache layers.
|
|
136
|
+
* @param {string} key - Cache key.
|
|
137
|
+
* @param {string} value - HTML string to store.
|
|
138
|
+
* @param {number} [ttl=RENDER_CACHE_TTL] - Time to live in seconds.
|
|
139
|
+
* @returns {Promise<void>}
|
|
140
|
+
*/
|
|
141
|
+
static async store(key, value, ttl = RENDER_CACHE_TTL) {
|
|
142
|
+
evictLru();
|
|
143
|
+
lru.set(key, { value, expiry: Date.now() + ttl * 1000 });
|
|
144
|
+
|
|
145
|
+
if (isMultiInstance) {
|
|
146
|
+
const redis = getRedisClient();
|
|
147
|
+
if (redis) {
|
|
148
|
+
try {
|
|
149
|
+
await redis.set(`render:${key}`, value, { EX: ttl });
|
|
150
|
+
return;
|
|
151
|
+
} catch {}
|
|
152
|
+
}
|
|
153
|
+
writeFileCache(key, value);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Clears in-memory LRU cache.
|
|
159
|
+
*/
|
|
160
|
+
static clearMemory() {
|
|
161
|
+
lru.clear();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Invalidates one or more keys across all cache layers.
|
|
166
|
+
* @param {string|string[]} [keys]
|
|
167
|
+
* @returns {Promise<void>}
|
|
168
|
+
*/
|
|
169
|
+
static async invalidate(keys) {
|
|
170
|
+
if (!keys) {
|
|
171
|
+
lru.clear();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const list = Array.isArray(keys) ? keys : [keys];
|
|
176
|
+
for (const key of list) {
|
|
177
|
+
const viewKey = `view:${key}`;
|
|
178
|
+
const routeKey = `route:${key}`;
|
|
179
|
+
const partialRouteKey = `route:partial:${key}`;
|
|
180
|
+
const fragmentKey = `fragment:${key}`;
|
|
181
|
+
|
|
182
|
+
lru.delete(key);
|
|
183
|
+
lru.delete(viewKey);
|
|
184
|
+
lru.delete(routeKey);
|
|
185
|
+
lru.delete(partialRouteKey);
|
|
186
|
+
lru.delete(fragmentKey);
|
|
187
|
+
|
|
188
|
+
const redis = getRedisClient();
|
|
189
|
+
if (redis) {
|
|
190
|
+
try {
|
|
191
|
+
await redis.del(`render:${key}`);
|
|
192
|
+
await redis.del(`render:${viewKey}`);
|
|
193
|
+
await redis.del(`render:${routeKey}`);
|
|
194
|
+
await redis.del(`render:${partialRouteKey}`);
|
|
195
|
+
await redis.del(`render:${fragmentKey}`);
|
|
196
|
+
} catch {}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (fileCacheEnabled) {
|
|
200
|
+
const cacheDir = getFileCacheDir();
|
|
201
|
+
for (const k of [key, viewKey, routeKey, partialRouteKey, fragmentKey]) {
|
|
202
|
+
try {
|
|
203
|
+
const f = path.join(cacheDir, toCacheFileName(k));
|
|
204
|
+
if (fs.existsSync(f)) fs.unlinkSync(f);
|
|
205
|
+
} catch {}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export default RenderCache;
|
package/core/render.d.ts
ADDED
package/core/render.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import Config from "./config.js";
|
|
2
|
+
import { html, SafeHtml, escapeHtml, safeJson } from "./html.js";
|
|
3
|
+
import RenderCache from "./render-cache.js";
|
|
4
|
+
import ViewLoader from "./view-loader.js";
|
|
5
|
+
|
|
6
|
+
const props = Config.props();
|
|
7
|
+
const DEBUG = props.debug;
|
|
8
|
+
const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
|
|
9
|
+
|
|
10
|
+
/**
|
|
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.
|
|
14
|
+
*/
|
|
15
|
+
export class Render {
|
|
16
|
+
/**
|
|
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.
|
|
20
|
+
* @param {Object} [options={}] - Island options.
|
|
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.
|
|
24
|
+
* @returns {string} Declarative HTML markup.
|
|
25
|
+
*/
|
|
26
|
+
static island(name, props = {}, options = {}) {
|
|
27
|
+
const tag = options.tag || "div";
|
|
28
|
+
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}>`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
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>}
|
|
39
|
+
*/
|
|
40
|
+
static async component(viewName, data = {}) {
|
|
41
|
+
const view = await ViewLoader.load(viewName);
|
|
42
|
+
if (!view) return "";
|
|
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 || "";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Sends a rendered partial fragment without applying a layout.
|
|
56
|
+
* @param {import('express').Response} res - Express response object.
|
|
57
|
+
* @param {string} partialName - View or component name.
|
|
58
|
+
* @param {Object} [data={}] - Data to pass.
|
|
59
|
+
* @returns {Promise<any>}
|
|
60
|
+
*/
|
|
61
|
+
static async partial(res, partialName, data = {}) {
|
|
62
|
+
return this.send(res, partialName, { ...data, _layout: false });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
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
|
+
*
|
|
92
|
+
* @param {import('express').Response} res - Express response object.
|
|
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.
|
|
96
|
+
* @returns {Promise<any>}
|
|
97
|
+
*/
|
|
98
|
+
static async send(res, viewName, data = {}, ttl) {
|
|
99
|
+
const locals = res.locals || {};
|
|
100
|
+
const appLocals = res.req?.app?.locals || {};
|
|
101
|
+
const isPartialRequest =
|
|
102
|
+
data._layout === false ||
|
|
103
|
+
res.req?.headers?.["x-bluebird-partial"] === "1" ||
|
|
104
|
+
res.req?.query?._partial === "1";
|
|
105
|
+
|
|
106
|
+
const view = await ViewLoader.load(viewName);
|
|
107
|
+
if (!view) {
|
|
108
|
+
return res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let rendered = "";
|
|
112
|
+
|
|
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);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
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
|
+
}
|
|
159
|
+
|
|
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,
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
rendered = layoutOutput instanceof SafeHtml ? layoutOutput.toString() : String(layoutOutput ?? "");
|
|
174
|
+
} else {
|
|
175
|
+
rendered = bodyHtml;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
} else {
|
|
179
|
+
rendered = view.content || "";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (ttl !== undefined && ttl > 0 && !DEBUG) {
|
|
183
|
+
const cacheKey = `view:${viewName}`;
|
|
184
|
+
await RenderCache.store(cacheKey, rendered, ttl);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
188
|
+
if (isPartialRequest) {
|
|
189
|
+
res.set("X-Bluebird-Partial", "1");
|
|
190
|
+
}
|
|
191
|
+
res.set("X-Bluebird-Cache", "MISS");
|
|
192
|
+
return res.send(rendered);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
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.
|
|
200
|
+
*/
|
|
201
|
+
static view(viewName, staticData = {}) {
|
|
202
|
+
return (req, res) => Render.send(res, viewName, staticData);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
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}
|
|
210
|
+
*/
|
|
211
|
+
static cache(seconds) {
|
|
212
|
+
const ttl = seconds ?? RENDER_CACHE_TTL;
|
|
213
|
+
|
|
214
|
+
return async (req, res, next) => {
|
|
215
|
+
if (DEBUG || req.method !== "GET") return next();
|
|
216
|
+
|
|
217
|
+
const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
|
|
218
|
+
const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
|
|
219
|
+
const cached = await RenderCache.lookup(key);
|
|
220
|
+
|
|
221
|
+
if (cached) {
|
|
222
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
223
|
+
res.set("X-Bluebird-Cache", "HIT");
|
|
224
|
+
return res.send(cached);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const originalSend = res.send.bind(res);
|
|
228
|
+
res.send = async (body) => {
|
|
229
|
+
if (typeof body === "string" && res.statusCode === 200) {
|
|
230
|
+
await RenderCache.store(key, body, ttl);
|
|
231
|
+
}
|
|
232
|
+
res.set("X-Bluebird-Cache", "MISS");
|
|
233
|
+
return originalSend(body);
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
next();
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
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.
|
|
245
|
+
* @returns {Promise<void>}
|
|
246
|
+
*/
|
|
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.` });
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
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);
|
|
281
|
+
|
|
282
|
+
if (deferredTokens.length > 0) {
|
|
283
|
+
await Promise.all(
|
|
284
|
+
deferredTokens.map(async (token) => {
|
|
285
|
+
try {
|
|
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
|
+
);
|
|
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);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export default Render;
|
package/core/router.d.ts
ADDED
package/core/router.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import Config from "./config.js";
|
|
3
|
+
import Seo from "./seo.js";
|
|
4
|
+
|
|
5
|
+
const props = Config.props();
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Wraps route handlers to automatically catch async rejections and forward them to next(err).
|
|
9
|
+
* @param {Function} fn - Handler function.
|
|
10
|
+
* @returns {Function} Wrapped handler.
|
|
11
|
+
*/
|
|
12
|
+
function wrapAsync(fn) {
|
|
13
|
+
if (typeof fn !== "function") return fn;
|
|
14
|
+
return (req, res, next) => {
|
|
15
|
+
try {
|
|
16
|
+
const result = fn(req, res, next);
|
|
17
|
+
if (result && typeof result.catch === "function") {
|
|
18
|
+
result.catch(next);
|
|
19
|
+
}
|
|
20
|
+
} catch (err) {
|
|
21
|
+
next(err);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Router wrapper class for handling Express routing logic.
|
|
28
|
+
* When created with { seo: true }, all GET routes registered on this router
|
|
29
|
+
* are automatically included in the generated sitemap.xml and robots.txt.
|
|
30
|
+
*/
|
|
31
|
+
class Router {
|
|
32
|
+
/**
|
|
33
|
+
* Creates a new Router instance.
|
|
34
|
+
* @param {string} [path="/"] - The base path for this router.
|
|
35
|
+
* @param {Object} [options={}] - Router configuration options.
|
|
36
|
+
* @param {boolean} [options.seo=false] - When true, GET routes on this router are included in sitemap/robots.txt.
|
|
37
|
+
* @param {string[]} [options.languages=[]] - Language prefixes for SEO route generation (e.g., ["en", "es"]).
|
|
38
|
+
* @example
|
|
39
|
+
* const router = new Router("/", { seo: true, languages: ["en", "es"] });
|
|
40
|
+
* router.get("/", (req, res) => {
|
|
41
|
+
* Render.send(res, "index", { title: "Home" });
|
|
42
|
+
* });
|
|
43
|
+
*/
|
|
44
|
+
constructor(path = "/", options = {}) {
|
|
45
|
+
this.router = express.Router();
|
|
46
|
+
this.path = path;
|
|
47
|
+
this._seo = options.seo ?? false;
|
|
48
|
+
this._languages = options.languages || [];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Registers a middleware on this router.
|
|
53
|
+
* @param {...Function} middleware - Middleware functions.
|
|
54
|
+
* @example
|
|
55
|
+
* router.use(Auth.protect());
|
|
56
|
+
* router.use(App.helmet());
|
|
57
|
+
*/
|
|
58
|
+
use(...middleware) {
|
|
59
|
+
const handlers = middleware.map(wrapAsync);
|
|
60
|
+
this.router.use(...handlers);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Registers a GET route handler.
|
|
65
|
+
* If this router was created with { seo: true }, the route path is automatically
|
|
66
|
+
* registered for sitemap.xml and robots.txt generation.
|
|
67
|
+
* @param {string|RegExp} path - The relative path for the GET route.
|
|
68
|
+
* @param {...Function} callback - One or more handler functions (middlewares and controller).
|
|
69
|
+
* @example
|
|
70
|
+
* router.get("/about", (req, res) => {
|
|
71
|
+
* Render.send(res, "about", { title: "About Us" });
|
|
72
|
+
* });
|
|
73
|
+
*/
|
|
74
|
+
get(path, ...callback) {
|
|
75
|
+
if (this._seo && typeof path === "string") {
|
|
76
|
+
Seo.registerRoute(this.path, path, this._languages);
|
|
77
|
+
}
|
|
78
|
+
if (path === "/*" || path === "*") {
|
|
79
|
+
path = /.*/;
|
|
80
|
+
}
|
|
81
|
+
const handlers = callback.map(wrapAsync);
|
|
82
|
+
this.router.get(path, ...handlers);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Registers a POST route handler.
|
|
87
|
+
* @param {string} path - The relative path for the POST route.
|
|
88
|
+
* @param {...Function} callback - One or more handler functions (middlewares and controller).
|
|
89
|
+
* @example
|
|
90
|
+
* router.post("/users", (req, res) => {
|
|
91
|
+
* res.json({ message: "User created successfully" })
|
|
92
|
+
* })
|
|
93
|
+
*/
|
|
94
|
+
post(path, ...callback) {
|
|
95
|
+
if (path === "/*" || path === "*") {
|
|
96
|
+
path = /.*/;
|
|
97
|
+
}
|
|
98
|
+
const handlers = callback.map(wrapAsync);
|
|
99
|
+
this.router.post(path, ...handlers);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Registers a PUT route handler.
|
|
104
|
+
* @param {string} path - The relative path for the PUT route.
|
|
105
|
+
* @param {...Function} callback - One or more handler functions (middlewares and controller).
|
|
106
|
+
* @example
|
|
107
|
+
* router.put("/users/:id", (req, res) => {
|
|
108
|
+
* res.json({ message: "User updated successfully" })
|
|
109
|
+
* })
|
|
110
|
+
*/
|
|
111
|
+
put(path, ...callback) {
|
|
112
|
+
const handlers = callback.map(wrapAsync);
|
|
113
|
+
this.router.put(path, ...handlers);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Registers a DELETE route handler.
|
|
118
|
+
* @param {string} path - The relative path for the DELETE route.
|
|
119
|
+
* @param {...Function} callback - One or more handler functions (middlewares and controller).
|
|
120
|
+
* @example
|
|
121
|
+
* router.delete("/users/:id", (req, res) => {
|
|
122
|
+
* res.json({ message: "User deleted successfully" })
|
|
123
|
+
* })
|
|
124
|
+
*/
|
|
125
|
+
delete(path, ...callback) {
|
|
126
|
+
const handlers = callback.map(wrapAsync);
|
|
127
|
+
this.router.delete(path, ...handlers);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Registers a PATCH route handler.
|
|
132
|
+
* @param {string} path - The relative path for the PATCH route.
|
|
133
|
+
* @param {...Function} callback - One or more handler functions (middlewares and controller).
|
|
134
|
+
* @example
|
|
135
|
+
* router.patch("/users/:id", (req, res) => {
|
|
136
|
+
* res.json({ message: "User patched successfully" })
|
|
137
|
+
* })
|
|
138
|
+
*/
|
|
139
|
+
patch(path, ...callback) {
|
|
140
|
+
const handlers = callback.map(wrapAsync);
|
|
141
|
+
this.router.patch(path, ...handlers);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Registers an OPTIONS route handler.
|
|
146
|
+
* @param {string} path - The relative path for the OPTIONS route.
|
|
147
|
+
* @param {...Function} callback - One or more handler functions (middlewares and controller).
|
|
148
|
+
*/
|
|
149
|
+
options(path, ...callback) {
|
|
150
|
+
const handlers = callback.map(wrapAsync);
|
|
151
|
+
this.router.options(path, ...handlers);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Returns the underlying Express router instance.
|
|
156
|
+
* @returns {import('express').Router}
|
|
157
|
+
*/
|
|
158
|
+
getRouter() {
|
|
159
|
+
return this.router;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Returns the base path associated with this router.
|
|
164
|
+
* @returns {string}
|
|
165
|
+
*/
|
|
166
|
+
getPath() {
|
|
167
|
+
return this.path;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export { Router };
|
|
171
|
+
export default Router;
|