@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.
Files changed (79) hide show
  1. package/.env_example +54 -0
  2. package/AGENTS.md +426 -0
  3. package/LICENSE +21 -0
  4. package/README.md +292 -3
  5. package/app/routes/api.js +50 -0
  6. package/app/routes/web.js +55 -0
  7. package/app/views/about.js +63 -0
  8. package/app/views/dashboard.js +147 -0
  9. package/app/views/index.js +80 -0
  10. package/app/views/layouts/main/view.js +81 -0
  11. package/app/views/legal/terms.html +19 -0
  12. package/app/views/login.js +80 -0
  13. package/core/app.d.ts +18 -0
  14. package/core/app.js +684 -0
  15. package/core/auth.d.ts +13 -0
  16. package/core/auth.js +326 -0
  17. package/core/cache.d.ts +17 -0
  18. package/core/cache.js +475 -0
  19. package/core/cli/doctor.js +287 -0
  20. package/core/cli/ecosystem.js +162 -0
  21. package/core/cli/init.js +779 -0
  22. package/core/cli/migrate.js +541 -0
  23. package/core/cli/model.js +66 -0
  24. package/core/cli/nginx.js +199 -0
  25. package/core/cli/route.js +121 -0
  26. package/core/cli/swagger.js +45 -0
  27. package/core/cli/view.js +96 -0
  28. package/core/config.d.ts +3 -0
  29. package/core/config.js +111 -0
  30. package/core/csrf.d.ts +3 -0
  31. package/core/csrf.js +114 -0
  32. package/core/database.d.ts +15 -0
  33. package/core/database.js +636 -0
  34. package/core/debug.d.ts +3 -0
  35. package/core/debug.js +250 -0
  36. package/core/hash.d.ts +3 -0
  37. package/core/hash.js +194 -0
  38. package/core/html.d.ts +42 -0
  39. package/core/html.js +217 -0
  40. package/core/index.d.ts +1176 -0
  41. package/core/logger.d.ts +3 -0
  42. package/core/logger.js +127 -0
  43. package/core/middleware.d.ts +3 -0
  44. package/core/middleware.js +28 -0
  45. package/core/model.d.ts +19 -0
  46. package/core/model.js +600 -0
  47. package/core/queue.d.ts +13 -0
  48. package/core/queue.js +172 -0
  49. package/core/ratelimit.d.ts +3 -0
  50. package/core/ratelimit.js +145 -0
  51. package/core/redis.d.ts +21 -0
  52. package/core/redis.js +230 -0
  53. package/core/render-cache.js +212 -0
  54. package/core/render.d.ts +3 -0
  55. package/core/render.js +320 -0
  56. package/core/router.d.ts +3 -0
  57. package/core/router.js +171 -0
  58. package/core/seo.d.ts +3 -0
  59. package/core/seo.js +106 -0
  60. package/core/swagger.d.ts +3 -0
  61. package/core/swagger.js +60 -0
  62. package/core/upload.d.ts +13 -0
  63. package/core/upload.js +102 -0
  64. package/core/util/colors.js +82 -0
  65. package/core/validate.d.ts +15 -0
  66. package/core/validate.js +364 -0
  67. package/core/view-loader.js +162 -0
  68. package/core/vite.d.ts +3 -0
  69. package/core/vite.js +145 -0
  70. package/core/ws.d.ts +13 -0
  71. package/core/ws.js +245 -0
  72. package/index.js +18 -0
  73. package/jsconfig.json +15 -0
  74. package/package.json +85 -5
  75. package/production.md +273 -0
  76. package/public/css/bluebird.min.css +2 -0
  77. package/public/images/favicon.ico +0 -0
  78. package/public/js/bluebird-client.js +1781 -0
  79. package/public/js/bluebird.min.js +1073 -0
package/core/debug.js ADDED
@@ -0,0 +1,250 @@
1
+ import Router from "./router.js";
2
+
3
+ /**
4
+ * Advanced Debug module for Blue Bird.
5
+ * Provides metrics history, route statistics and live monitoring.
6
+ */
7
+ class Debug {
8
+
9
+ constructor() {
10
+ this.router = new Router("/debug");
11
+ this.limit = 50;
12
+ this.initStore();
13
+ this.registerRoutes();
14
+ }
15
+
16
+ initStore() {
17
+ if (!global.__bluebird_debug_store__) {
18
+ global.__bluebird_debug_store__ = {
19
+ requests: [],
20
+ routes: {},
21
+ errors4xx: 0,
22
+ errors5xx: 0
23
+ };
24
+ }
25
+ }
26
+
27
+ static shouldTrack(req) {
28
+ const url = req.originalUrl || "";
29
+
30
+ if (url.startsWith("/debug")) return false;
31
+
32
+ if (/\.(json|css|js|map|png|jpg|jpeg|gif|svg|ico|webp)$/i.test(url)) {
33
+ return false;
34
+ }
35
+
36
+ if (req.method === "OPTIONS") return false;
37
+
38
+ return true;
39
+ }
40
+
41
+ static middlewareMetrics(app) {
42
+ app.use((req, res, next) => {
43
+
44
+ if (!Debug.shouldTrack(req)) return next();
45
+
46
+ const start = process.hrtime();
47
+
48
+ res.on("finish", () => {
49
+
50
+ const diff = process.hrtime(start);
51
+ const responseTime = diff[0] * 1e3 + diff[1] / 1e6;
52
+
53
+ const memory = process.memoryUsage();
54
+ const ramUsedMB = memory.rss / 1024 / 1024;
55
+
56
+ const cpuUsage = process.cpuUsage();
57
+ const cpuUsedMS = (cpuUsage.user + cpuUsage.system) / 1000;
58
+
59
+ const record = {
60
+ method: req.method,
61
+ url: req.originalUrl,
62
+ status: res.statusCode,
63
+ responseTime: Number(responseTime.toFixed(2)),
64
+ ramUsedMB: Number(ramUsedMB.toFixed(2)),
65
+ cpuUsedMS: Number(cpuUsedMS.toFixed(2)),
66
+ date: new Date().toISOString()
67
+ };
68
+
69
+ const store = global.__bluebird_debug_store__;
70
+
71
+ store.requests.unshift(record);
72
+ if (store.requests.length > 50) store.requests.pop();
73
+
74
+ const routeKey = `${req.method} ${req.route?.path || req.path}`;
75
+
76
+ if (!store.routes[routeKey]) {
77
+ store.routes[routeKey] = {
78
+ count: 0,
79
+ totalTime: 0
80
+ };
81
+ }
82
+
83
+ store.routes[routeKey].count += 1;
84
+ store.routes[routeKey].totalTime += record.responseTime;
85
+
86
+ if (record.status >= 400 && record.status < 500) store.errors4xx++;
87
+ if (record.status >= 500) store.errors5xx++;
88
+ });
89
+
90
+ next();
91
+ });
92
+ }
93
+
94
+ registerRoutes() {
95
+
96
+ this.router.get("/", (req, res) => {
97
+
98
+ const store = global.__bluebird_debug_store__;
99
+
100
+ if (req.query.fetch === "true") {
101
+ return res.json(store);
102
+ }
103
+
104
+ if (req.query.reset === "true") {
105
+ global.__bluebird_debug_store__ = {
106
+ requests: [],
107
+ routes: {},
108
+ errors4xx: 0,
109
+ errors5xx: 0
110
+ };
111
+ return res.json({ ok: true });
112
+ }
113
+
114
+ res.send(`
115
+ <!DOCTYPE html>
116
+ <html>
117
+ <head>
118
+ <script src="https://cdn.tailwindcss.com"></script>
119
+ <title>Blue Bird Debug</title>
120
+ </head>
121
+ <body class="bg-gray-100 text-gray-800 p-10">
122
+
123
+ <div class="max-w-7xl mx-auto">
124
+
125
+ <div class="flex justify-between items-center mb-8">
126
+ <h1 class="text-3xl font-bold text-blue-600">Blue Bird Debug Panel</h1>
127
+ <button onclick="resetData()" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg shadow">
128
+ Reset
129
+ </button>
130
+ </div>
131
+
132
+ <div class="grid grid-cols-3 gap-6 mb-8">
133
+
134
+ <div class="bg-white p-6 rounded-xl shadow">
135
+ <h3 class="text-gray-500 text-sm">Total Requests</h3>
136
+ <p id="totalReq" class="text-2xl font-bold">0</p>
137
+ </div>
138
+
139
+ <div class="bg-yellow-100 p-6 rounded-xl shadow">
140
+ <h3 class="text-yellow-600 text-sm">4xx Errors</h3>
141
+ <p id="err4" class="text-2xl font-bold text-yellow-700">0</p>
142
+ </div>
143
+
144
+ <div class="bg-red-100 p-6 rounded-xl shadow">
145
+ <h3 class="text-red-600 text-sm">5xx Errors</h3>
146
+ <p id="err5" class="text-2xl font-bold text-red-700">0</p>
147
+ </div>
148
+
149
+ </div>
150
+
151
+ <div class="grid grid-cols-2 gap-10">
152
+
153
+ <div class="bg-white p-6 rounded-xl shadow">
154
+ <h2 class="text-lg font-semibold mb-4">Route Stats</h2>
155
+ <table class="table-fixed w-full text-sm">
156
+ <thead>
157
+ <tr class="border-b">
158
+ <th class="text-left w-1/2 py-2">Route</th>
159
+ <th class="text-left w-1/4">Hits</th>
160
+ <th class="text-left w-1/4">Avg Time</th>
161
+ </tr>
162
+ </thead>
163
+ <tbody id="routesBody"></tbody>
164
+ </table>
165
+ </div>
166
+
167
+ <div class="bg-white p-6 rounded-xl shadow">
168
+ <h2 class="text-lg font-semibold mb-4">Last Requests</h2>
169
+ <table class="table-fixed w-full text-sm">
170
+ <thead>
171
+ <tr class="border-b">
172
+ <th class="text-left w-1/2 py-2">URL</th>
173
+ <th class="text-left w-1/6">Method</th>
174
+ <th class="text-left w-1/6">Status</th>
175
+ <th class="text-left w-1/6">Time</th>
176
+ </tr>
177
+ </thead>
178
+ <tbody id="historyBody"></tbody>
179
+ </table>
180
+ </div>
181
+
182
+ </div>
183
+
184
+ </div>
185
+
186
+ <script>
187
+ async function loadData() {
188
+ const res = await fetch('/debug?fetch=true');
189
+ const data = await res.json();
190
+
191
+ document.getElementById("totalReq").innerText = data.requests.length;
192
+ document.getElementById("err4").innerText = data.errors4xx;
193
+ document.getElementById("err5").innerText = data.errors5xx;
194
+
195
+ const routesBody = document.getElementById("routesBody");
196
+ const historyBody = document.getElementById("historyBody");
197
+
198
+ routesBody.innerHTML = "";
199
+ historyBody.innerHTML = "";
200
+
201
+ Object.entries(data.routes).forEach(([key, value]) => {
202
+ const avg = (value.totalTime / value.count).toFixed(2);
203
+ let color = "";
204
+ if (avg > 500) color = "text-red-600 font-semibold";
205
+ else if (avg > 200) color = "text-yellow-600";
206
+
207
+ routesBody.innerHTML += \`
208
+ <tr class="border-b">
209
+ <td class="py-1 truncate">\${key}</td>
210
+ <td>\${value.count}</td>
211
+ <td class="\${color}">\${avg} ms</td>
212
+ </tr>\`;
213
+ });
214
+
215
+ data.requests.forEach(r => {
216
+ historyBody.innerHTML += \`
217
+ <tr class="border-b text-xs">
218
+ <td class="truncate">\${r.url}</td>
219
+ <td>\${r.method}</td>
220
+ <td>\${r.status}</td>
221
+ <td>\${r.responseTime} ms</td>
222
+ </tr>\`;
223
+ });
224
+ }
225
+
226
+ async function resetData() {
227
+ await fetch('/debug?reset=true');
228
+ loadData();
229
+ }
230
+
231
+ loadData();
232
+ setInterval(loadData, 3000);
233
+ </script>
234
+
235
+ </body>
236
+ </html>
237
+ `);
238
+ });
239
+ }
240
+
241
+ getRouter() {
242
+ return {
243
+ path: this.router.getPath(),
244
+ router: this.router.getRouter()
245
+ };
246
+ }
247
+ }
248
+
249
+ export { Debug };
250
+ export default Debug;
package/core/hash.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { Hash, HashMakeOptions } from "./index.js";
2
+ export default Hash;
3
+ export { Hash, HashMakeOptions };
package/core/hash.js ADDED
@@ -0,0 +1,194 @@
1
+ import crypto from "node:crypto";
2
+
3
+ let bcryptModule = null;
4
+ try {
5
+ bcryptModule = (await import("bcrypt")).default || (await import("bcrypt"));
6
+ } catch {}
7
+
8
+ /**
9
+ * High-performance Password Hashing class.
10
+ * Uses native node:crypto scrypt by default (zero npm dependencies, NIST recommended),
11
+ * with seamless support for bcrypt when installed or verifying bcrypt hashes.
12
+ */
13
+ class Hash {
14
+ /**
15
+ * Hashes a plain text password using scrypt (default) or bcrypt.
16
+ * @param {string} password - The plain text password.
17
+ * @param {Object} [options={}] - Hashing options.
18
+ * @param {string} [options.driver="scrypt"] - Hashing driver ('scrypt' or 'bcrypt').
19
+ * @param {number} [options.rounds=10] - Salt rounds for bcrypt (if driver is 'bcrypt').
20
+ * @param {number} [options.N=16384] - CPU/memory cost parameter for scrypt.
21
+ * @param {number} [options.r=8] - Block size for scrypt.
22
+ * @param {number} [options.p=1] - Parallelization parameter for scrypt.
23
+ * @returns {Promise<string>} Formatted password hash string.
24
+ * @example
25
+ * const hash = await Hash.make("mySecretPassword");
26
+ * const bcryptHash = await Hash.make("mySecretPassword", { driver: "bcrypt" });
27
+ */
28
+ static async make(password, options = {}) {
29
+ if (typeof password !== "string" || !password) {
30
+ throw new Error("[HASH ERROR] Password must be a non-empty string.");
31
+ }
32
+
33
+ const driver = (options.driver || "scrypt").toLowerCase();
34
+
35
+ if (driver === "bcrypt") {
36
+ if (!bcryptModule) {
37
+ throw new Error(
38
+ "[HASH ERROR] 'bcrypt' package is not installed. Run 'npm install bcrypt' or 'npx blue-bird add bcrypt', or use the default scrypt driver.",
39
+ );
40
+ }
41
+ const rounds = options.rounds || 10;
42
+ return bcryptModule.hash(password, rounds);
43
+ }
44
+ const N = options.N || 16384;
45
+ const r = options.r || 8;
46
+ const p = options.p || 1;
47
+ const keylen = 64;
48
+ const salt = crypto.randomBytes(16);
49
+
50
+ return new Promise((resolve, reject) => {
51
+ crypto.scrypt(
52
+ password,
53
+ salt,
54
+ keylen,
55
+ { N, r, p, maxmem: 32 * 1024 * 1024 },
56
+ (err, derivedKey) => {
57
+ if (err) return reject(err);
58
+ const hashString = `$scrypt$N=${N},r=${r},p=${p}$${salt.toString("hex")}$${derivedKey.toString("hex")}`;
59
+ resolve(hashString);
60
+ },
61
+ );
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Alias for make().
67
+ * @param {string} password - The plain text password.
68
+ * @param {Object} [options={}] - Options.
69
+ * @returns {Promise<string>}
70
+ */
71
+ static async hash(password, options = {}) {
72
+ return this.make(password, options);
73
+ }
74
+
75
+ /**
76
+ * Verifies a plain text password against a hash string.
77
+ * Automatically detects scrypt or bcrypt hash formats.
78
+ * Uses timing-safe comparison to protect against side-channel attacks.
79
+ *
80
+ * @param {string} password - The plain text password to check.
81
+ * @param {string} hash - The stored hash string.
82
+ * @returns {Promise<boolean>} True if password matches, false otherwise.
83
+ * @example
84
+ * const isValid = await Hash.verify("mySecretPassword", storedHash);
85
+ */
86
+ static async verify(password, hash) {
87
+ if (
88
+ typeof password !== "string" ||
89
+ !password ||
90
+ typeof hash !== "string" ||
91
+ !hash
92
+ ) {
93
+ return false;
94
+ }
95
+
96
+ if (/^\$2[aby]\$\d{2}\$/.test(hash)) {
97
+ if (!bcryptModule) {
98
+ console.error(
99
+ "[HASH ERROR] A bcrypt hash was detected, but the 'bcrypt' package is not installed. Run 'npm install bcrypt' or 'npx blue-bird add bcrypt'.",
100
+ );
101
+ return false;
102
+ }
103
+ try {
104
+ return await bcryptModule.compare(password, hash);
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ if (hash.startsWith("$scrypt$")) {
111
+ const parts = hash.split("$");
112
+ if (parts.length !== 5) return false;
113
+
114
+ const paramsStr = parts[2];
115
+ const saltHex = parts[3];
116
+ const originalHashHex = parts[4];
117
+
118
+ if (!paramsStr || !saltHex || !originalHashHex) return false;
119
+
120
+ let N = 16384,
121
+ r = 8,
122
+ p = 1;
123
+ paramsStr.split(",").forEach((param) => {
124
+ const [k, v] = param.split("=");
125
+ if (k === "N") N = parseInt(v, 10) || N;
126
+ if (k === "r") r = parseInt(v, 10) || r;
127
+ if (k === "p") p = parseInt(v, 10) || p;
128
+ });
129
+
130
+ const salt = Buffer.from(saltHex, "hex");
131
+ const originalHash = Buffer.from(originalHashHex, "hex");
132
+
133
+ return new Promise((resolve) => {
134
+ crypto.scrypt(
135
+ password,
136
+ salt,
137
+ originalHash.length,
138
+ { N, r, p, maxmem: 32 * 1024 * 1024 },
139
+ (err, derivedKey) => {
140
+ if (err) return resolve(false);
141
+ try {
142
+ const matches = crypto.timingSafeEqual(originalHash, derivedKey);
143
+ resolve(matches);
144
+ } catch {
145
+ resolve(false);
146
+ }
147
+ },
148
+ );
149
+ });
150
+ }
151
+
152
+ return false;
153
+ }
154
+
155
+ /**
156
+ * Alias for verify().
157
+ * @param {string} password - The plain text password.
158
+ * @param {string} hash - The stored hash string.
159
+ * @returns {Promise<boolean>}
160
+ */
161
+ static async check(password, hash) {
162
+ return this.verify(password, hash);
163
+ }
164
+
165
+ /**
166
+ * Checks if a given hash needs to be rehashed to match updated security parameters.
167
+ * @param {string} hash - The stored hash string.
168
+ * @param {Object} [options={}] - Target options.
169
+ * @returns {boolean} True if the hash should be regenerated.
170
+ */
171
+ static needsRehash(hash, options = {}) {
172
+ if (!hash || typeof hash !== "string") return true;
173
+ const targetDriver = (options.driver || "scrypt").toLowerCase();
174
+
175
+ if (targetDriver === "bcrypt") {
176
+ return !/^\$2[aby]\$\d{2}\$/.test(hash);
177
+ }
178
+
179
+ if (!hash.startsWith("$scrypt$")) return true;
180
+
181
+ const parts = hash.split("$");
182
+ if (parts.length !== 5) return true;
183
+
184
+ const paramsStr = parts[2];
185
+ const targetN = options.N || 16384;
186
+ const targetR = options.r || 8;
187
+ const targetP = options.p || 1;
188
+
189
+ return !paramsStr.includes(`N=${targetN},r=${targetR},p=${targetP}`);
190
+ }
191
+ }
192
+
193
+ export { Hash };
194
+ export default Hash;
package/core/html.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ export class SafeHtml {
2
+ value: string;
3
+ constructor(value: string);
4
+ toString(): string;
5
+ }
6
+
7
+ export function isSafeHtml(val: any): val is SafeHtml;
8
+
9
+ export function escapeHtml(value: any): string;
10
+
11
+ export function safeJson(data: any): string;
12
+
13
+ export interface HtmlTag {
14
+ (strings: TemplateStringsArray, ...values: any[]): SafeHtml;
15
+ raw(str: string): SafeHtml;
16
+ json(obj: any): SafeHtml;
17
+ script: typeof script;
18
+ }
19
+
20
+ export const html: HtmlTag;
21
+
22
+ export interface ScriptTag {
23
+ (strings: TemplateStringsArray, ...values: any[]): SafeHtml;
24
+ (src: string): SafeHtml;
25
+ (options: { src: string; defer?: boolean; module?: boolean }): SafeHtml;
26
+ }
27
+
28
+ export const script: ScriptTag;
29
+
30
+ export function cached(
31
+ key: string,
32
+ options: number | { ttl?: number; vary?: string[] },
33
+ renderFn: () => SafeHtml | string | Promise<SafeHtml | string>
34
+ ): Promise<SafeHtml>;
35
+
36
+ export function defer<T>(
37
+ promise: Promise<T>,
38
+ fallback: SafeHtml | string,
39
+ renderer: (data: T) => SafeHtml | string | Promise<SafeHtml | string>
40
+ ): { __bluebird_deferred__: true; promise: Promise<T>; fallback: string; renderer: Function };
41
+
42
+ export default html;
package/core/html.js ADDED
@@ -0,0 +1,217 @@
1
+ import RenderCache from "./render-cache.js";
2
+
3
+ const SAFE_HTML_KEY = Symbol.for("Bluebird.SafeHtml");
4
+
5
+ /**
6
+ * Wrapper class representing a trusted HTML string that bypasses escaping.
7
+ */
8
+ export class SafeHtml {
9
+ /**
10
+ * @param {string} value
11
+ */
12
+ constructor(value) {
13
+ this.value = typeof value === "string" ? value : String(value ?? "");
14
+ this[SAFE_HTML_KEY] = true;
15
+ }
16
+
17
+ /**
18
+ * Returns the raw inner HTML string.
19
+ * @returns {string}
20
+ */
21
+ toString() {
22
+ return this.value;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Checks whether a given value is an instance of SafeHtml.
28
+ * @param {any} val
29
+ * @returns {boolean}
30
+ */
31
+ export function isSafeHtml(val) {
32
+ return Boolean(val && (val instanceof SafeHtml || val[SAFE_HTML_KEY] === true));
33
+ }
34
+
35
+ /**
36
+ * Escapes HTML special characters to prevent XSS.
37
+ * @param {any} value
38
+ * @returns {string}
39
+ */
40
+ export function escapeHtml(value) {
41
+ if (value === null || value === undefined) return "";
42
+ const str = typeof value === "string" ? value : String(value);
43
+ return str
44
+ .replace(/&/g, "&amp;")
45
+ .replace(/</g, "&lt;")
46
+ .replace(/>/g, "&gt;")
47
+ .replace(/"/g, "&quot;")
48
+ .replace(/'/g, "&#39;");
49
+ }
50
+
51
+ /**
52
+ * Serializes data into a secure JSON string suitable for script tags and HTML attributes.
53
+ * Prevents HTML/script closing tag injection.
54
+ * @param {any} data
55
+ * @returns {string}
56
+ */
57
+ export function safeJson(data) {
58
+ return JSON.stringify(data)
59
+ .replace(/</g, "\\u003c")
60
+ .replace(/>/g, "\\u003e")
61
+ .replace(/&/g, "\\u0026")
62
+ .replace(/\u2028/g, "\\u2028")
63
+ .replace(/\u2029/g, "\\u2029");
64
+ }
65
+
66
+ /**
67
+ * Flattens and stringifies a template literal value.
68
+ * @param {any} val
69
+ * @returns {string}
70
+ */
71
+ function resolveValue(val) {
72
+ if (val === null || val === undefined || val === false) {
73
+ return "";
74
+ }
75
+ if (val === true) {
76
+ return "";
77
+ }
78
+ if (isSafeHtml(val)) {
79
+ return val.toString();
80
+ }
81
+ if (Array.isArray(val)) {
82
+ return val.map(resolveValue).join("");
83
+ }
84
+ if (typeof val === "function") {
85
+ throw new TypeError(
86
+ "[BLUEBIRD HTML] Functions cannot be interpolated directly in html`...`. Did you mean to call it like ${myFunc()}?"
87
+ );
88
+ }
89
+ return escapeHtml(val);
90
+ }
91
+
92
+ /**
93
+ * Tagged template literal for creating secure HTML strings.
94
+ * All interpolated values are escaped by default unless wrapped in SafeHtml or html.raw().
95
+ *
96
+ * @param {TemplateStringsArray} strings
97
+ * @param {...any} values
98
+ * @returns {SafeHtml}
99
+ */
100
+ export function html(strings, ...values) {
101
+ let result = "";
102
+ const len = strings.length;
103
+
104
+ for (let i = 0; i < len; i++) {
105
+ result += strings[i];
106
+ if (i < values.length) {
107
+ result += resolveValue(values[i]);
108
+ }
109
+ }
110
+
111
+ return new SafeHtml(result);
112
+ }
113
+
114
+ /**
115
+ * Marks a string as explicitly safe, bypassing HTML escaping.
116
+ * @param {string} str
117
+ * @returns {SafeHtml}
118
+ */
119
+ html.raw = function raw(str) {
120
+ return new SafeHtml(str);
121
+ };
122
+
123
+ /**
124
+ * Generates an escaped JSON string for embedding inside HTML attributes or scripts.
125
+ * @param {any} obj
126
+ * @returns {SafeHtml}
127
+ */
128
+ html.json = function json(obj) {
129
+ return new SafeHtml(safeJson(obj));
130
+ };
131
+
132
+ /**
133
+ * Tagged template literal and helper for creating inline client scripts safely.
134
+ * Interpolated values are safely converted to JSON literals to prevent code injection.
135
+ * Escapes closing </script> tags automatically.
136
+ *
137
+ * @param {TemplateStringsArray|string|Object} first
138
+ * @param {...any} values
139
+ * @returns {SafeHtml}
140
+ */
141
+ export function script(first, ...values) {
142
+ if (Array.isArray(first) && "raw" in first) {
143
+ let code = "";
144
+ for (let i = 0; i < first.length; i++) {
145
+ code += first[i];
146
+ if (i < values.length) {
147
+ const val = values[i];
148
+ if (isSafeHtml(val)) {
149
+ code += val.toString();
150
+ } else {
151
+ code += safeJson(val);
152
+ }
153
+ }
154
+ }
155
+ const safeCode = code.replace(/<\/script/gi, "<\\/script");
156
+ return new SafeHtml(`<script>${safeCode}</script>`);
157
+ }
158
+
159
+ if (typeof first === "string") {
160
+ const src = first.replace(/"/g, "&quot;");
161
+ return new SafeHtml(`<script type="module" src="${src}"></script>`);
162
+ }
163
+
164
+ if (first && typeof first === "object" && first.src) {
165
+ const src = String(first.src).replace(/"/g, "&quot;");
166
+ const defer = first.defer ? " defer" : "";
167
+ const type = first.module ? ' type="module"' : "";
168
+ return new SafeHtml(`<script${type} src="${src}"${defer}></script>`);
169
+ }
170
+
171
+ return new SafeHtml("");
172
+ }
173
+
174
+ html.script = script;
175
+
176
+ /**
177
+ * Cached fragment helper. Evaluates renderFn only on cache miss.
178
+ *
179
+ * @param {string} key - Cache key identifier.
180
+ * @param {number|{ttl?: number, vary?: string[]}} options - TTL in seconds or options object.
181
+ * @param {Function} renderFn - Callback returning SafeHtml or string.
182
+ * @returns {Promise<SafeHtml>}
183
+ */
184
+ export async function cached(key, options, renderFn) {
185
+ const ttl = typeof options === "number" ? options : options?.ttl || 300;
186
+ const cacheKey = `fragment:${key}`;
187
+
188
+ const existing = await RenderCache.lookup(cacheKey);
189
+ if (existing !== null) {
190
+ return new SafeHtml(existing);
191
+ }
192
+
193
+ const output = await renderFn();
194
+ const renderedString = output instanceof SafeHtml ? output.toString() : String(output ?? "");
195
+ await RenderCache.store(cacheKey, renderedString, ttl);
196
+
197
+ return new SafeHtml(renderedString);
198
+ }
199
+
200
+ /**
201
+ * Deferred streaming token for progressive chunked rendering.
202
+ *
203
+ * @param {Promise<any>} promise - Asynchronous data promise.
204
+ * @param {SafeHtml|string} fallback - Initial placeholder HTML chunk.
205
+ * @param {Function} renderer - Callback taking resolved data and returning SafeHtml or string.
206
+ * @returns {Object}
207
+ */
208
+ export function defer(promise, fallback, renderer) {
209
+ return {
210
+ __bluebird_deferred__: true,
211
+ promise,
212
+ fallback: fallback instanceof SafeHtml ? fallback.toString() : String(fallback ?? ""),
213
+ renderer,
214
+ };
215
+ }
216
+
217
+ export default html;