@seip/bluebird-js 0.1.7 → 0.2.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 (148) hide show
  1. package/AGENTS.md +726 -620
  2. package/README.md +615 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +54 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/terms.html +46 -0
  8. package/app/resources/index.html +27 -0
  9. package/app/resources/layouts/AppLayout.jsx +89 -0
  10. package/app/resources/main.jsx +18 -0
  11. package/app/resources/pages/Dashboard.jsx +98 -0
  12. package/app/resources/pages/Home.jsx +140 -0
  13. package/app/resources/pages/Login.jsx +35 -0
  14. package/app/resources/pages/NotFound.jsx +16 -0
  15. package/app/resources/pages/Register.jsx +55 -0
  16. package/app/resources/routes.jsx +54 -0
  17. package/app/resources/spa.js +67 -0
  18. package/app/resources/styles.css +9 -0
  19. package/app/routes/api.js +85 -50
  20. package/app/routes/auth.js +209 -0
  21. package/app/routes/web.js +59 -47
  22. package/core/ai.js +30 -10
  23. package/core/app.d.ts +2 -18
  24. package/core/app.js +987 -801
  25. package/core/auth.d.ts +2 -13
  26. package/core/auth.js +444 -326
  27. package/core/cli/build.js +37 -0
  28. package/core/cli/dev.js +155 -0
  29. package/core/cli/doctor.js +37 -2
  30. package/core/cli/export.js +191 -0
  31. package/core/cli/init.js +91 -322
  32. package/core/cli/nginx.js +1 -1
  33. package/core/cli/templates.js +139 -0
  34. package/core/cli/view.js +98 -161
  35. package/core/config.js +44 -2
  36. package/core/csrf.js +156 -24
  37. package/core/database.js +1184 -1131
  38. package/core/debug.js +1 -1
  39. package/core/html.js +8 -1
  40. package/core/index.d.ts +126 -310
  41. package/core/paths.js +55 -0
  42. package/core/ratelimit.js +10 -1
  43. package/core/react/client/api.js +237 -0
  44. package/core/react/client/auth.js +236 -0
  45. package/core/react/client/components.js +1321 -0
  46. package/core/react/client/i18n.js +338 -0
  47. package/core/react/client/index.d.ts +249 -0
  48. package/core/react/client/index.js +49 -0
  49. package/core/react/client/router.js +26 -0
  50. package/core/react/client/theme.css +512 -0
  51. package/core/render-cache.js +250 -212
  52. package/core/render.d.ts +25 -21
  53. package/core/render.js +738 -736
  54. package/core/router.d.ts +2 -3
  55. package/core/router.js +171 -171
  56. package/core/seo.js +10 -0
  57. package/core/spa.js +599 -0
  58. package/core/view-loader.js +155 -613
  59. package/core/vite-plugin.d.ts +18 -0
  60. package/core/vite-plugin.js +162 -0
  61. package/core/vite.js +250 -145
  62. package/index.js +22 -18
  63. package/jsconfig.json +5 -3
  64. package/package.json +114 -92
  65. package/production.md +8 -3
  66. package/public/js/bluebird.js +1160 -0
  67. package/templates/_auth/app/database.js +19 -0
  68. package/templates/_auth/app/models/user.js +22 -0
  69. package/templates/_auth/app/routes/auth-router.js +304 -0
  70. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  71. package/templates/_base/app/resources/html/notFound.html +14 -0
  72. package/templates/_base/app/resources/index.html +27 -0
  73. package/templates/_base/app/resources/styles.css +9 -0
  74. package/templates/api/app/models/note.js +18 -0
  75. package/templates/api/app/routes/api.js +82 -0
  76. package/templates/api/app/routes/auth.js +11 -0
  77. package/templates/api/index.js +19 -0
  78. package/templates/api/template.json +13 -0
  79. package/templates/auth/app/mail.js +11 -0
  80. package/templates/auth/app/models/password_reset.js +18 -0
  81. package/templates/auth/app/resources/html/home.html +21 -0
  82. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  83. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  84. package/templates/auth/app/resources/main.jsx +18 -0
  85. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  86. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  87. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  88. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  89. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  90. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  91. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  92. package/templates/auth/app/resources/routes.jsx +54 -0
  93. package/templates/auth/app/resources/spa.js +29 -0
  94. package/templates/auth/app/routes/api.js +17 -0
  95. package/templates/auth/app/routes/auth.js +13 -0
  96. package/templates/auth/app/routes/web.js +21 -0
  97. package/templates/auth/index.js +19 -0
  98. package/templates/auth/template.json +15 -0
  99. package/templates/blank/app/models/.gitkeep +0 -0
  100. package/templates/blank/app/resources/html/home.html +27 -0
  101. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  102. package/templates/blank/app/resources/main.jsx +16 -0
  103. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  104. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  105. package/templates/blank/app/resources/routes.jsx +15 -0
  106. package/templates/blank/app/resources/spa.js +24 -0
  107. package/templates/blank/app/routes/api.js +11 -0
  108. package/templates/blank/app/routes/web.js +21 -0
  109. package/templates/blank/index.js +13 -0
  110. package/templates/blank/template.json +12 -0
  111. package/templates/blog/app/lib/blog.js +149 -0
  112. package/templates/blog/app/models/post.js +22 -0
  113. package/templates/blog/app/resources/html/home.html +28 -0
  114. package/templates/blog/app/resources/html/not-found.html +5 -0
  115. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  116. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  117. package/templates/blog/app/resources/html/post.html +8 -0
  118. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  119. package/templates/blog/app/resources/main.jsx +18 -0
  120. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  121. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  122. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  123. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  124. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  125. package/templates/blog/app/resources/routes.jsx +51 -0
  126. package/templates/blog/app/resources/spa.js +25 -0
  127. package/templates/blog/app/resources/styles.css +40 -0
  128. package/templates/blog/app/routes/api.js +77 -0
  129. package/templates/blog/app/routes/auth.js +10 -0
  130. package/templates/blog/app/routes/web.js +114 -0
  131. package/templates/blog/index.js +21 -0
  132. package/templates/blog/template.json +14 -0
  133. package/vite.config.js +11 -0
  134. package/app/views/components/Header.jsx +0 -42
  135. package/app/views/components/LiveCounter.jsx +0 -67
  136. package/app/views/layouts/main/view.jsx +0 -201
  137. package/app/views/legal/terms.html +0 -29
  138. package/app/views/pages/about.jsx +0 -98
  139. package/app/views/pages/dashboard.jsx +0 -278
  140. package/app/views/pages/index.jsx +0 -123
  141. package/app/views/pages/login.jsx +0 -141
  142. package/core/actions.d.ts +0 -4
  143. package/core/actions.js +0 -355
  144. package/core/jsx.d.ts +0 -38
  145. package/core/jsx.js +0 -1597
  146. package/core/vite.d.ts +0 -3
  147. package/public/js/bluebird-client.js +0 -3265
  148. package/public/js/tailwind.js +0 -8
package/core/app.js CHANGED
@@ -1,801 +1,987 @@
1
- import http from "node:http";
2
- import express from "express";
3
- import path from "node:path";
4
- import fs from "node:fs";
5
- import os from "node:os";
6
- import colors from "./util/colors.js";
7
- import Config from "./config.js";
8
- import Logger from "./logger.js";
9
- import Debug from "./debug.js";
10
- import WebSocketManager from "./ws.js";
11
- import RateLimit from "./ratelimit.js";
12
- import Seo from "./seo.js";
13
- import AI, { ai } from "./ai.js";
14
-
15
- const props = Config.props();
16
- const SERVER_BOOT_ID = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
17
-
18
- /**
19
- * Detects the primary local network IPv4 address.
20
- * @returns {string}
21
- */
22
- function getLanIp() {
23
- const interfaces = os.networkInterfaces();
24
- for (const name of Object.keys(interfaces)) {
25
- for (const iface of interfaces[name] || []) {
26
- if (iface.family === "IPv4" && !iface.internal) {
27
- return iface.address;
28
- }
29
- }
30
- }
31
- return "127.0.0.1";
32
- }
33
-
34
- /**
35
- * Lightweight native cookie parser middleware.
36
- * @param {import('express').Request} req
37
- * @param {import('express').Response} res
38
- * @param {import('express').NextFunction} next
39
- */
40
- function nativeCookieParser(req, res, next) {
41
- if (req.cookies) return next();
42
- const cookieHeader = req.headers.cookie;
43
- const cookies = {};
44
- if (cookieHeader) {
45
- const pairs = cookieHeader.split(";");
46
- for (let i = 0; i < pairs.length; i++) {
47
- const idx = pairs[i].indexOf("=");
48
- if (idx > 0) {
49
- const key = pairs[i].slice(0, idx).trim();
50
- const val = pairs[i].slice(idx + 1).trim();
51
- try {
52
- cookies[key] = decodeURIComponent(val);
53
- } catch {
54
- cookies[key] = val;
55
- }
56
- }
57
- }
58
- }
59
- req.cookies = cookies;
60
- next();
61
- }
62
-
63
- /**
64
- * Lightweight native CORS middleware.
65
- * @param {Object|boolean} [corsOptions={}]
66
- * @returns {Function} Express middleware.
67
- */
68
- function nativeCors(corsOptions = {}) {
69
- if (corsOptions === false) {
70
- return (req, res, next) => next();
71
- }
72
-
73
- const origin = corsOptions.origin ?? "*";
74
- const methods = corsOptions.methods ?? "GET,HEAD,PUT,PATCH,POST,DELETE";
75
- const allowedHeaders = corsOptions.allowedHeaders ?? "Content-Type,Authorization";
76
- const credentials = corsOptions.credentials ?? true;
77
-
78
- return (req, res, next) => {
79
- const reqOrigin = req.headers.origin;
80
-
81
- if (credentials && reqOrigin) {
82
- if (origin === "*" || origin === true) {
83
- res.setHeader("Access-Control-Allow-Origin", reqOrigin);
84
- res.setHeader("Vary", "Origin");
85
- } else if (typeof origin === "string") {
86
- res.setHeader("Access-Control-Allow-Origin", origin);
87
- } else if (Array.isArray(origin) && origin.includes(reqOrigin)) {
88
- res.setHeader("Access-Control-Allow-Origin", reqOrigin);
89
- res.setHeader("Vary", "Origin");
90
- } else if (typeof origin === "function" && origin(reqOrigin, req)) {
91
- res.setHeader("Access-Control-Allow-Origin", reqOrigin);
92
- res.setHeader("Vary", "Origin");
93
- }
94
- } else if (origin === "*") {
95
- res.setHeader("Access-Control-Allow-Origin", "*");
96
- } else if (typeof origin === "string") {
97
- res.setHeader("Access-Control-Allow-Origin", origin);
98
- } else if (Array.isArray(origin) && reqOrigin && origin.includes(reqOrigin)) {
99
- res.setHeader("Access-Control-Allow-Origin", reqOrigin);
100
- res.setHeader("Vary", "Origin");
101
- } else if (typeof origin === "function" && reqOrigin) {
102
- if (origin(reqOrigin, req)) {
103
- res.setHeader("Access-Control-Allow-Origin", reqOrigin);
104
- res.setHeader("Vary", "Origin");
105
- }
106
- } else if (reqOrigin) {
107
- res.setHeader("Access-Control-Allow-Origin", reqOrigin);
108
- res.setHeader("Vary", "Origin");
109
- }
110
-
111
- if (credentials) {
112
- res.setHeader("Access-Control-Allow-Credentials", "true");
113
- }
114
-
115
- if (corsOptions.exposedHeaders) {
116
- res.setHeader(
117
- "Access-Control-Expose-Headers",
118
- Array.isArray(corsOptions.exposedHeaders)
119
- ? corsOptions.exposedHeaders.join(",")
120
- : corsOptions.exposedHeaders
121
- );
122
- }
123
-
124
- if (req.method === "OPTIONS") {
125
- res.setHeader(
126
- "Access-Control-Allow-Methods",
127
- Array.isArray(methods) ? methods.join(",") : methods
128
- );
129
- res.setHeader(
130
- "Access-Control-Allow-Headers",
131
- Array.isArray(allowedHeaders) ? allowedHeaders.join(",") : allowedHeaders
132
- );
133
- if (corsOptions.maxAge) {
134
- res.setHeader("Access-Control-Max-Age", String(corsOptions.maxAge));
135
- }
136
- return res.status(204).end();
137
- }
138
-
139
- next();
140
- };
141
- }
142
-
143
- /**
144
- * Generates middleware that applies modern HTTP security response headers.
145
- * @param {Object} [options={}] - Options to override header values.
146
- * @param {string|false} [options.csp=false] - Content-Security-Policy value.
147
- * @returns {Function} Express middleware.
148
- */
149
- function securityHeaders(options = {}) {
150
- return (req, res, next) => {
151
- res.setHeader("X-Frame-Options", options.frameOptions ?? "SAMEORIGIN");
152
- res.setHeader("X-Content-Type-Options", "nosniff");
153
- res.setHeader("X-XSS-Protection", "0");
154
- res.setHeader("Referrer-Policy", options.referrerPolicy ?? "strict-origin-when-cross-origin");
155
- res.setHeader(
156
- "Permissions-Policy",
157
- options.permissionsPolicy ?? "camera=(), microphone=(), geolocation=()"
158
- );
159
- if (options.csp) {
160
- res.setHeader("Content-Security-Policy", options.csp);
161
- }
162
- next();
163
- };
164
- }
165
-
166
- /**
167
- * Main Application class to manage Express server, routes, and middlewares.
168
- */
169
- class App {
170
- /**
171
- * Initializes the App instance with the provided options.
172
- * @param {Object} [options={}] - Configuration options for the application.
173
- * @param {Array<{path: string, router: import('express').Router}>} [options.routes=[]] - Route objects.
174
- * @param {Object|boolean} [options.cors={}] - CORS configuration options.
175
- * @param {Array<Function>} [options.middlewares=[]] - Global middleware functions.
176
- * @param {number|string} [options.port=3000] - Server port (use 0 for dynamic free port in Electron).
177
- * @param {string} [options.host="http://localhost"] - Server host URL.
178
- * @param {string} [options.appUrl] - Public application URL.
179
- * @param {boolean} [options.logger=false] - Whether to enable the request logger.
180
- * @param {boolean} [options.notFound=true] - Whether to enable the default 404 handler.
181
- * @param {boolean} [options.json=true] - Whether to enable JSON body parsing.
182
- * @param {boolean} [options.urlencoded=true] - Whether to enable URL-encoded body parsing.
183
- * @param {Object} [options.static] - Static file configuration for public/ directory.
184
- * @param {boolean} [options.cookieParser=true] - Whether to enable cookie parsing.
185
- * @param {boolean} [options.swagger=false] - Enable Swagger documentation.
186
- * @param {boolean} [options.compression=false] - Enable gzip/brotli compression.
187
- * @param {boolean|Object} [options.security=true] - Enable built-in security headers middleware.
188
- * @param {boolean|Object} [options.rateLimit=false] - Enable built-in rate limiting middleware.
189
- * @param {boolean} [options.trustProxy=true] - Enable Express trust proxy for accurate IP behind reverse proxies.
190
- * @param {boolean} [options.desktop=false] - Enable Electron/Desktop mode (binds 127.0.0.1 and uses writable userDataDir).
191
- * @param {string} [options.userDataPath] - Custom writable directory path for SQLite, logs, and file cache in Electron.
192
- * @param {string} [options.appPath] - Custom application root directory for views and static assets (ideal for Electron app.getAppPath()).
193
- * @param {boolean} [options.allowLan=false] - Whether to allow local network / mobile access (binds 0.0.0.0 in desktop mode).
194
- */
195
- constructor(options = {}) {
196
- if (options.appPath) {
197
- Config.setAppDir(options.appPath);
198
- }
199
- if (options.userDataPath) {
200
- Config.setUserDataDir(options.userDataPath);
201
- } else if (options.desktop) {
202
- process.env.DESKTOP_MODE = "true";
203
- Config.reload();
204
- }
205
-
206
- this.app = express();
207
- this.app.disable("x-powered-by");
208
- this.server = http.createServer(this.app);
209
- this.wsManager = null;
210
- this.routes = options.routes || [];
211
- this.cors = options.cors || {};
212
- this.middlewares = options.middlewares || [];
213
- this.desktop = options.desktop ?? Config.isDesktop();
214
- this.allowLan = Boolean(options.allowLan);
215
- this.port = options.port !== undefined ? options.port : (this.desktop && !process.env.PORT ? 0 : props.port);
216
- this.host = options.host || (this.desktop ? (this.allowLan ? "http://0.0.0.0" : "http://127.0.0.1") : props.host);
217
- this.appUrl = options.appUrl || props.appUrl;
218
- this.logger = options.logger ?? false;
219
- this.notFound = options.notFound ?? true;
220
- this.json = options.json ?? true;
221
- this.urlencoded = options.urlencoded ?? true;
222
- this.static = options.static || props.static;
223
- this.cookieParser = options.cookieParser ?? true;
224
- this.swagger = options.swagger ?? false;
225
- this.compression = options.compression ?? false;
226
- this.security = options.security ?? true;
227
- this.rateLimit = options.rateLimit ?? false;
228
- this.noAutoDiscoverRoutes = Boolean(options.noAutoDiscoverRoutes);
229
- this.autoRoutes = this.noAutoDiscoverRoutes ? false : (options.autoRoutes ?? true);
230
- this.trustProxy = options.trustProxy ?? !this.desktop;
231
- this.debug = options.debug !== undefined ? Boolean(options.debug) : (props.debug || process.env.DEBUG === "true");
232
- this._loggerInstance = null;
233
- this._finalized = false;
234
-
235
- if (this.trustProxy) {
236
- this.app.enable("trust proxy");
237
- }
238
-
239
- this._setupCoreMiddlewares();
240
- }
241
-
242
- /**
243
- * Lazily initializes and returns the Logger instance.
244
- * @returns {Logger}
245
- */
246
- get loggerInstance() {
247
- if (!this._loggerInstance) {
248
- this._loggerInstance = new Logger();
249
- }
250
- return this._loggerInstance;
251
- }
252
-
253
- set loggerInstance(val) {
254
- this._loggerInstance = val;
255
- }
256
-
257
- /**
258
- * Registers a custom middleware or router in the Express application.
259
- * @param {Function|import('express').Router} record - Middleware function or Express router.
260
- */
261
- use(record) {
262
- this.app.use(record);
263
- }
264
-
265
- /**
266
- * Sets a configuration value in the Express application.
267
- * @param {string} key - Configuration key.
268
- * @param {*} value - Configuration value.
269
- */
270
- set(key, value) {
271
- this.app.set(key, value);
272
- }
273
-
274
- /**
275
- * Returns the active port number after the server starts listening.
276
- * @returns {number}
277
- */
278
- getPort() {
279
- const addr = this.server?.address?.();
280
- if (addr && typeof addr === "object" && addr.port) {
281
- return addr.port;
282
- }
283
- return Number(this.port) || 3000;
284
- }
285
-
286
- /**
287
- * Returns the active internal URL of the server.
288
- * @returns {string}
289
- */
290
- getUrl() {
291
- const port = this.getPort();
292
- const cleanHost = this.host.replace(/:\d+$/, "");
293
- return `${cleanHost}:${port}`;
294
- }
295
-
296
- /**
297
- * Sets up base middleware stack.
298
- * @private
299
- */
300
- _setupCoreMiddlewares() {
301
- if (this.compression) {
302
- let compressionMiddleware = null;
303
- import("compression")
304
- .then((mod) => {
305
- const comp = mod.default || mod;
306
- compressionMiddleware = comp();
307
- })
308
- .catch(() => {});
309
-
310
- this.app.use((req, res, next) => {
311
- if (compressionMiddleware) {
312
- return compressionMiddleware(req, res, next);
313
- }
314
- next();
315
- });
316
- }
317
-
318
- if (this.json) {
319
- const jsonOpts = typeof this.json === "object" ? this.json : { limit: "256kb" };
320
- this.app.use(express.json(jsonOpts));
321
- }
322
- if (this.urlencoded) {
323
- const urlOpts = typeof this.urlencoded === "object" ? { extended: true, ...this.urlencoded } : { extended: true, limit: "256kb" };
324
- this.app.use(express.urlencoded(urlOpts));
325
- }
326
- if (this.cookieParser) this.app.use(nativeCookieParser);
327
-
328
- if (this.security) {
329
- this.app.use(securityHeaders(typeof this.security === "object" ? this.security : {}));
330
- }
331
-
332
- if (this.cors !== false) {
333
- this.app.use(nativeCors(this.cors));
334
- }
335
-
336
- if (this.rateLimit) {
337
- this.app.use(RateLimit.middleware(typeof this.rateLimit === "object" ? this.rateLimit : {}));
338
- }
339
-
340
- this.app.use((req, res, next) => {
341
- req.lang = req.query?.lang || req.body?.lang || req.cookies?.lang || "en";
342
- res.locals.lang = req.lang;
343
-
344
- res.success = (data = null, message = "Success", statusCode = 200) =>
345
- res.status(statusCode).json({ status: "success", message, data });
346
-
347
- res.error = (message = "Error", statusCode = 400, errors = []) =>
348
- res.status(statusCode).json({ status: "error", message, errors });
349
-
350
- res.ok = (data = null, message = "Success") => res.success(data, message, 200);
351
-
352
- res.created = (data = null, message = "Created") => res.success(data, message, 201);
353
-
354
- res.badRequest = (message = "Bad Request", errors = []) => res.error(message, 400, errors);
355
-
356
- res.unauthorized = (message = "Unauthorized") => res.error(message, 401);
357
-
358
- res.forbidden = (message = "Forbidden") => res.error(message, 403);
359
-
360
- res.notFound = (message = "Not Found") => res.error(message, 404);
361
-
362
- res.serverError = (message = "Internal Server Error", errors = []) => res.error(message, 500, errors);
363
-
364
- res.paginate = (data = [], pagination = {}, message = "Success") => {
365
- const page = Number(pagination.page) || 1;
366
- const limit = Number(pagination.limit) || data.length;
367
- const total = Number(pagination.total) || data.length;
368
- const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;
369
- return res.status(200).json({ status: "success", message, data, pagination: { page, limit, total, totalPages } });
370
- };
371
-
372
- res.setHeader("X-Powered-By", "Blue Bird");
373
- next();
374
- });
375
-
376
- this.app.get("/api/health", (req, res) =>
377
- res.json({
378
- status: "ok",
379
- timestamp: new Date().toISOString(),
380
- uptime: Math.floor(process.uptime()),
381
- environment: this.debug ? "development" : "production",
382
- desktop: this.desktop,
383
- memory: {
384
- rss: `${Math.round(process.memoryUsage().rss / 1024 / 1024)}MB`,
385
- heapUsed: `${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`,
386
- },
387
- })
388
- );
389
-
390
- if (this.debug) {
391
- this.app.get("/_bb/dev-reload", (req, res) => {
392
- res.writeHead(200, {
393
- "Content-Type": "text/event-stream",
394
- "Cache-Control": "no-cache, no-transform",
395
- Connection: "keep-alive",
396
- "Access-Control-Allow-Origin": "*",
397
- });
398
-
399
- res.write(`data: ${JSON.stringify({ type: "connected", bootId: SERVER_BOOT_ID })}\n\n`);
400
-
401
- const interval = setInterval(() => {
402
- res.write(":ping\n\n");
403
- }, 15000);
404
-
405
- req.on("close", () => {
406
- clearInterval(interval);
407
- });
408
- });
409
- }
410
-
411
- const staticPath = this.static?.path || "public";
412
- const staticOptions = this.static?.options || {};
413
- const isDebug = this.debug;
414
- const resolvedStaticDir = path.isAbsolute(staticPath)
415
- ? staticPath
416
- : path.resolve(Config.appDir(), staticPath);
417
-
418
- this.app.use(
419
- express.static(resolvedStaticDir, {
420
- ...staticOptions,
421
- setHeaders: (res) => {
422
- res.setHeader("X-Powered-By", "Blue Bird");
423
- res.setHeader(
424
- "Cache-Control",
425
- isDebug ? "no-cache" : "public, max-age=2592000, immutable"
426
- );
427
- },
428
- })
429
- );
430
-
431
- if (this.desktop) {
432
- const uploadsDir = path.join(Config.userDataDir(), "uploads");
433
- if (!fs.existsSync(uploadsDir)) {
434
- try {
435
- fs.mkdirSync(uploadsDir, { recursive: true });
436
- } catch {}
437
- }
438
- this.app.use("/uploads", express.static(uploadsDir));
439
- }
440
-
441
- this.middlewares.forEach((middleware) => {
442
- this.app.use(middleware);
443
- });
444
-
445
- if (this.logger || props.debug) this._middlewareLogger(this.logger);
446
-
447
- if (props.debug) {
448
- Debug.middlewareMetrics(this.app);
449
- }
450
- }
451
-
452
- /**
453
- * Finalizes application routes, 404, and error handling.
454
- * Called automatically before listening.
455
- * @private
456
- */
457
- async _finalize() {
458
- if (this._finalized) return;
459
- this._finalized = true;
460
-
461
- if (this.swagger) {
462
- const { default: Swagger } = await import("./swagger.js");
463
- const defaultSwaggerOptions = {
464
- info: { title: "Blue Bird API", version: "1.0.0", description: "Blue Bird Framework API Documentation" },
465
- url: this.appUrl ? this.appUrl : `${this.host}:${this.port}`,
466
- route: "/docs",
467
- };
468
- Swagger.init(this.app, {
469
- ...defaultSwaggerOptions,
470
- ...(typeof this.swagger === "object" ? this.swagger : {}),
471
- });
472
- }
473
-
474
- await this._dispatchRoutes();
475
-
476
- if (this.notFound) this._notFoundDefault();
477
-
478
- this._errorHandler();
479
- }
480
-
481
- /**
482
- * Middleware that logs incoming HTTP requests.
483
- * @private
484
- * @param {boolean} [logger=false]
485
- */
486
- _middlewareLogger(logger = false) {
487
- this.app.use((req, res, next) => {
488
- const method = req.method;
489
- const url = req.url.replace(/(password|token|authorization)=([^&]+)/gi, "$1=***");
490
- if (url.includes("chrome")) return next();
491
- const params = Object.keys(req.params).length > 0 ? ` ${JSON.stringify(req.params)}` : "";
492
- const ip = req.ip || req.socket?.remoteAddress;
493
- const now = new Date().toISOString();
494
- const time = `${now.split("T")[0]} ${now.split("T")[1].split(".")[0]}`;
495
- let message = ` ${time} -${ip} -[${method}] ${url} ${params}`;
496
-
497
- if (logger) this.loggerInstance.info(message);
498
-
499
- if (props.debug) {
500
- message = `${colors.bold.green(time)} - ${colors.bold.cyan(ip)} -[${colors.bold.red(method)}] ${colors.bold.blue(url)} ${colors.bold.yellow(params)}`;
501
- console.log(message);
502
- }
503
- next();
504
- });
505
- }
506
-
507
- /**
508
- * Global error handler for the application.
509
- * @private
510
- */
511
- _errorHandler() {
512
- this.app.use((err, req, res, next) => {
513
- const statusCode = err.statusCode || err.status || 500;
514
- const message = err.message || "Internal Server Error";
515
- const errors = err.errors || [];
516
-
517
- if (this.logger) {
518
- this.loggerInstance.error(`[${statusCode}] ${message} - ${err.stack}`);
519
- }
520
-
521
- const payload = {
522
- status: "error",
523
- message: statusCode === 500 && !props.debug ? "Internal Server Error" : message,
524
- errors,
525
- };
526
-
527
- if (props.debug && err.stack) payload.stack = err.stack;
528
-
529
- return res.status(statusCode).json(payload);
530
- });
531
- }
532
-
533
- /**
534
- * Attaches all registered routes to the Express application, including automatic view routes and SEO routes.
535
- * @private
536
- */
537
- async _dispatchRoutes() {
538
- if (props.debug) {
539
- const debug = new Debug();
540
- const debugRouter = debug.getRouter();
541
- this.app.use(debugRouter.path, debugRouter.router);
542
- }
543
-
544
- let autoViewRouter = null;
545
- if (this.autoRoutes) {
546
- try {
547
- const [{ default: Router }, { default: Render }] = await Promise.all([
548
- import("./router.js"),
549
- import("./render.js"),
550
- ]);
551
- autoViewRouter = new Router("/");
552
- await Render.autoRoutes(autoViewRouter);
553
- } catch {}
554
- }
555
-
556
- const hasSeoRouter = this.routes.some((r) => r._seo) || Seo.getRoutes().length > 0;
557
- if (hasSeoRouter) {
558
- this.app.get("/sitemap.xml", (req, res) => {
559
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
560
- res.send(Seo.generateSitemap(this.appUrl));
561
- });
562
- this.app.get("/robots.txt", (req, res) => {
563
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
564
- res.send(Seo.generateRobots(this.appUrl));
565
- });
566
- }
567
-
568
- this.routes.forEach((route) => {
569
- this.app.use(route.path, route.router);
570
- });
571
-
572
- if (autoViewRouter) {
573
- this.app.use(autoViewRouter.path, autoViewRouter.router);
574
- }
575
- }
576
-
577
- /**
578
- * Default 404 handler for unmatched routes.
579
- * @private
580
- */
581
- _notFoundDefault() {
582
- this.app.use((req, res) => {
583
- const expectsHtml = req.headers.accept?.includes("text/html") && !req.path.startsWith("/api");
584
- if (expectsHtml) return res.status(404).send("<h1>404 Not Found</h1>");
585
- return res.status(404).json({ message: "Not Found" });
586
- });
587
- }
588
-
589
- /**
590
- * Starts the HTTP server and listens for incoming connections.
591
- * In desktop mode, binds to 127.0.0.1 (or 0.0.0.0 if allowLan is true).
592
- * @returns {Promise<import('http').Server>}
593
- */
594
- async run() {
595
- await this._finalize();
596
-
597
- return new Promise((resolve, reject) => {
598
- const onListening = () => {
599
- const activePort = this.getPort();
600
- this.port = activePort;
601
- if (this.desktop) {
602
- this.appUrl = `http://127.0.0.1:${activePort}`;
603
- }
604
- let banner =
605
- colors.bold.blue("Blue Bird Server Online\n") +
606
- colors.bold.cyan("App URL: ") +
607
- colors.green(`${this.appUrl}`) +
608
- "\n" +
609
- colors.bold.cyan("Internal: ") +
610
- colors.green(`${this.host}:${activePort}`) +
611
- "\n";
612
-
613
- if (this.desktop && this.allowLan) {
614
- const lanIp = getLanIp();
615
- banner +=
616
- colors.bold.cyan("LAN / QR: ") +
617
- colors.yellow(`http://${lanIp}:${activePort}`) +
618
- "\n";
619
- }
620
-
621
- banner += colors.gray("────────────────────────────────");
622
- console.log(banner);
623
- resolve(this.server);
624
- };
625
-
626
- this.server.on("error", reject);
627
-
628
- if (this.desktop) {
629
- const bindAddress = this.allowLan ? "0.0.0.0" : "127.0.0.1";
630
- this.server.listen(this.port, bindAddress, onListening);
631
- } else {
632
- this.server.listen(this.port, onListening);
633
- }
634
- });
635
- }
636
-
637
- /**
638
- * Starts the server in Electron / Desktop mode, binding to 127.0.0.1 (or 0.0.0.0 if allowLan is true),
639
- * using a dynamic port if port is 0, and returning the server, resolved port, local URL, and optional LAN URL
640
- * ready for Electron's mainWindow.loadURL(url) and mobile QR code access.
641
- * @param {Object} [options={}]
642
- * @param {string} [options.appPath] - Optional path from Electron app.getAppPath().
643
- * @param {string} [options.userDataPath] - Optional path from Electron app.getPath("userData").
644
- * @param {boolean} [options.allowLan=false] - Whether to allow local network / mobile access (binds 0.0.0.0).
645
- * @param {string} [options.host] - Optional custom host override.
646
- * @param {number} [options.port] - Optional custom port override.
647
- * @returns {Promise<{server: import('http').Server, port: number, url: string, lanUrl?: string, lanIp?: string}>}
648
- */
649
- async runDesktop(options = {}) {
650
- if (options.appPath) {
651
- Config.setAppDir(options.appPath);
652
- }
653
- if (options.userDataPath) {
654
- Config.setUserDataDir(options.userDataPath);
655
- }
656
- if (options.port !== undefined) {
657
- this.port = options.port;
658
- }
659
- if (options.allowLan !== undefined) {
660
- this.allowLan = Boolean(options.allowLan);
661
- }
662
- this.desktop = true;
663
- this.host = options.host || (this.allowLan ? "http://0.0.0.0" : "http://127.0.0.1");
664
- await this.run();
665
- const port = this.getPort();
666
- const url = `http://127.0.0.1:${port}`;
667
- const result = { server: this.server, port, url };
668
- if (this.allowLan) {
669
- const lanIp = getLanIp();
670
- result.lanIp = lanIp;
671
- result.lanUrl = `http://${lanIp}:${port}`;
672
- }
673
- return result;
674
- }
675
-
676
- /**
677
- * Closes the running HTTP server and cleans up database connections.
678
- * @returns {Promise<void>}
679
- */
680
- async close() {
681
- try {
682
- const { Database } = await import("./database.js");
683
- await Database.closeAll();
684
- } catch {}
685
- try {
686
- const { default: Model } = await import("./model.js");
687
- await Model.close();
688
- } catch {}
689
-
690
- return new Promise((resolve, reject) => {
691
- if (this.server) {
692
- this.server.close((err) => (err ? reject(err) : resolve()));
693
- } else {
694
- resolve();
695
- }
696
- });
697
- }
698
-
699
- /**
700
- * Initializes and returns the WebSocket manager attached to the HTTP server.
701
- * @param {Function|Object} [options] - Connection callback or options object.
702
- * @returns {WebSocketManager}
703
- */
704
- websocket(options = {}) {
705
- const handler = typeof options === "function" ? options : null;
706
- const wsOptions = typeof options === "object" && options !== null ? options : {};
707
-
708
- if (!this.wsManager) {
709
- this.wsManager = new WebSocketManager(this.server, wsOptions);
710
- }
711
- if (handler) {
712
- this.wsManager.onConnection(handler);
713
- }
714
- return this.wsManager;
715
- }
716
-
717
- /**
718
- * Returns a pre-configured Helmet middleware function synchronously.
719
- * Dynamically loads helmet on first request if installed, or passes through with warning.
720
- * @param {Object} [options={}] - Helmet options.
721
- * @returns {Function} Express middleware.
722
- */
723
- static helmet(options = {}) {
724
- let helmetMiddleware = null;
725
- let loadPromise = null;
726
-
727
- return (req, res, next) => {
728
- if (helmetMiddleware) return helmetMiddleware(req, res, next);
729
-
730
- if (!loadPromise) {
731
- loadPromise = import("helmet")
732
- .then((mod) => {
733
- const helmetFn = mod.default || mod;
734
- helmetMiddleware = helmetFn({
735
- contentSecurityPolicy: props.debug ? false : undefined,
736
- hidePoweredBy: false,
737
- ...options,
738
- });
739
- })
740
- .catch(() => {
741
- console.error("[APP WARN] 'helmet' is not installed. Run: npx bluebird-js add helmet");
742
- });
743
- }
744
-
745
- loadPromise.then(() => {
746
- if (helmetMiddleware) helmetMiddleware(req, res, next);
747
- else next();
748
- });
749
- };
750
- }
751
-
752
- /**
753
- * Returns the built-in security headers middleware without requiring helmet.
754
- * @param {Object} [options={}] - Options for header values.
755
- * @returns {Function} Express middleware.
756
- */
757
- static securityHeaders(options = {}) {
758
- return securityHeaders(options);
759
- }
760
-
761
- /**
762
- * Returns the native rate-limiting middleware for protecting specific routes or routers.
763
- * @param {Object} [options={}] - Rate limit options (windowMs, max, message, driver, keyGenerator).
764
- * @returns {Function} Express middleware.
765
- */
766
- /**
767
- * Returns a new or default unified AI instance.
768
- * @param {Object} [options={}] - AI configuration options.
769
- * @returns {AI}
770
- */
771
- static ai(options = {}) {
772
- return Object.keys(options).length > 0 ? new AI(options) : ai;
773
- }
774
-
775
- static rateLimit(options = {}) {
776
- return RateLimit.middleware(options);
777
- }
778
- }
779
-
780
- /**
781
- * Operational application error class for standardizing custom API errors.
782
- */
783
- export class AppError extends Error {
784
- /**
785
- * Creates an AppError instance.
786
- * @param {string} message - Error message.
787
- * @param {number} [statusCode=500] - HTTP status code.
788
- * @param {Array|Object} [errors=[]] - Detailed error list.
789
- */
790
- constructor(message, statusCode = 500, errors = []) {
791
- super(message);
792
- this.name = "AppError";
793
- this.statusCode = statusCode;
794
- this.errors = errors;
795
- this.isOperational = true;
796
- Error.captureStackTrace(this, this.constructor);
797
- }
798
- }
799
-
800
- export { App, AI, ai };
801
- export default App;
1
+ import http from "node:http";
2
+ import express from "express";
3
+ import path from "node:path";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import net from "node:net";
7
+ import { randomBytes } from "node:crypto";
8
+ import colors from "./util/colors.js";
9
+ import Config from "./config.js";
10
+ import Logger from "./logger.js";
11
+ import Debug from "./debug.js";
12
+ import WebSocketManager from "./ws.js";
13
+ import RateLimit from "./ratelimit.js";
14
+ import Seo from "./seo.js";
15
+ import AI, { ai } from "./ai.js";
16
+ import ViteBridge from "./vite.js";
17
+
18
+ const props = Config.props();
19
+
20
+ /**
21
+ * Accepted `lang` values (`?lang=`, body, or `lang` cookie): BCP 47 style tags such as `en`, `es`, `pt-BR`.
22
+ */
23
+ const LANG_PATTERN = /^[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?$/;
24
+
25
+ /**
26
+ * Detects the primary local network IPv4 address.
27
+ * @returns {string}
28
+ */
29
+ function getLanIp() {
30
+ const interfaces = os.networkInterfaces();
31
+ for (const name of Object.keys(interfaces)) {
32
+ for (const iface of interfaces[name] || []) {
33
+ if (iface.family === "IPv4" && !iface.internal) {
34
+ return iface.address;
35
+ }
36
+ }
37
+ }
38
+ return "127.0.0.1";
39
+ }
40
+
41
+ /**
42
+ * Self-contained 404 page (light and dark) used when `app/resources/html/notFound.html` does not exist.
43
+ */
44
+ const NOT_FOUND_HTML = `<!DOCTYPE html>
45
+ <html lang="%LANG%">
46
+ <head>
47
+ <meta charset="UTF-8">
48
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
49
+ <meta name="color-scheme" content="light dark">
50
+ <meta name="robots" content="noindex">
51
+ <title>404 - Page not found</title>
52
+ <style>
53
+ body{margin:0;min-height:100vh;display:grid;place-items:center;font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;background:#fafafa;color:#18181b}
54
+ main{text-align:center;padding:2rem}
55
+ p.code{margin:0;font-size:.8rem;font-weight:600;letter-spacing:.2em;color:#71717a}
56
+ h1{margin:.75rem 0 0;font-size:1.75rem;font-weight:600;letter-spacing:-.02em}
57
+ p.text{margin:.75rem 0 0;color:#71717a}
58
+ a{display:inline-flex;margin-top:1.5rem;padding:.55rem 1.1rem;border-radius:.75rem;background:#18181b;color:#fafafa;text-decoration:none;font-size:.875rem;font-weight:500}
59
+ @media (prefers-color-scheme:dark){body{background:#09090b;color:#fafafa}a{background:#fafafa;color:#18181b}p.code,p.text{color:#a1a1aa}}
60
+ </style>
61
+ </head>
62
+ <body>
63
+ <main>
64
+ <p class="code">404</p>
65
+ <h1>Page not found</h1>
66
+ <p class="text">The page you are looking for does not exist or was moved.</p>
67
+ <a href="/">Back to home</a>
68
+ </main>
69
+ </body>
70
+ </html>`;
71
+
72
+ /**
73
+ * Checks whether `127.0.0.1:<port>` reaches this server. On Windows a dual-stack `::` listener can share
74
+ * the port with another process bound to `127.0.0.1` (VS Code Live Preview, another dev server), and
75
+ * `http://localhost:<port>` then opens that other process instead of the app.
76
+ * @param {import('http').Server} server
77
+ * @param {number} port
78
+ * @returns {Promise<boolean>} `false` only when another process answers on the IPv4 loopback.
79
+ */
80
+ function loopbackReachesServer(server, port) {
81
+ return new Promise((resolve) => {
82
+ let mine = false;
83
+ let settled = false;
84
+ const client = net.connect({ port, host: "127.0.0.1" });
85
+ const onConnection = (socket) => {
86
+ if (socket.remotePort === client.localPort) mine = true;
87
+ };
88
+ const finish = (result) => {
89
+ if (settled) return;
90
+ settled = true;
91
+ server.off("connection", onConnection);
92
+ client.destroy();
93
+ resolve(result);
94
+ };
95
+ server.on("connection", onConnection);
96
+ client.once("connect", () => setTimeout(() => finish(mine), 100));
97
+ client.once("error", () => finish(true));
98
+ setTimeout(() => finish(true), 1500).unref();
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Lightweight native cookie parser middleware.
104
+ * @param {import('express').Request} req
105
+ * @param {import('express').Response} res
106
+ * @param {import('express').NextFunction} next
107
+ */
108
+ function nativeCookieParser(req, res, next) {
109
+ if (req.cookies) return next();
110
+ const cookieHeader = req.headers.cookie;
111
+ const cookies = {};
112
+ if (cookieHeader) {
113
+ const pairs = cookieHeader.split(";");
114
+ for (let i = 0; i < pairs.length; i++) {
115
+ const idx = pairs[i].indexOf("=");
116
+ if (idx > 0) {
117
+ const key = pairs[i].slice(0, idx).trim();
118
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
119
+ const val = pairs[i].slice(idx + 1).trim();
120
+ try {
121
+ cookies[key] = decodeURIComponent(val);
122
+ } catch {
123
+ cookies[key] = val;
124
+ }
125
+ }
126
+ }
127
+ }
128
+ req.cookies = cookies;
129
+ next();
130
+ }
131
+
132
+ /**
133
+ * Lightweight native CORS middleware.
134
+ * Secure by default: `origin: "*"` never reflects the request origin and never sends credentials.
135
+ * @param {Object|boolean} [corsOptions={}]
136
+ * @returns {Function} Express middleware.
137
+ */
138
+ function nativeCors(corsOptions = {}) {
139
+ if (corsOptions === false) {
140
+ return (req, res, next) => next();
141
+ }
142
+
143
+ const opts = corsOptions === true ? {} : corsOptions || {};
144
+ const origin = opts.origin ?? "*";
145
+ const methods = opts.methods ?? "GET,HEAD,PUT,PATCH,POST,DELETE";
146
+ const allowedHeaders =
147
+ opts.allowedHeaders ??
148
+ "Content-Type,Authorization,X-CSRF-Token,X-Auth-Mode,X-Requested-With,X-Bluebird-Partial";
149
+ const wildcard = origin === "*";
150
+ let credentials = opts.credentials ?? false;
151
+
152
+ if (credentials && wildcard) {
153
+ console.warn(
154
+ "[CORS] `credentials: true` is ignored with `origin: \"*\"`. Provide an explicit origin allowlist (array or function) to allow credentialed cross-origin requests."
155
+ );
156
+ credentials = false;
157
+ }
158
+
159
+ /**
160
+ * Resolves the allowed origin value for the request, or null when not allowed.
161
+ * @param {string|undefined} reqOrigin
162
+ * @param {import('express').Request} req
163
+ * @returns {string|null}
164
+ */
165
+ const resolveOrigin = (reqOrigin, req) => {
166
+ if (wildcard) return "*";
167
+ if (!reqOrigin) return null;
168
+ if (origin === true) return reqOrigin;
169
+ if (typeof origin === "string") return origin === reqOrigin ? reqOrigin : null;
170
+ if (Array.isArray(origin)) return origin.includes(reqOrigin) ? reqOrigin : null;
171
+ if (origin instanceof RegExp) return origin.test(reqOrigin) ? reqOrigin : null;
172
+ if (typeof origin === "function") return origin(reqOrigin, req) ? reqOrigin : null;
173
+ return null;
174
+ };
175
+
176
+ return (req, res, next) => {
177
+ const reqOrigin = req.headers.origin;
178
+ const allowed = resolveOrigin(reqOrigin, req);
179
+
180
+ if (allowed) {
181
+ res.setHeader("Access-Control-Allow-Origin", allowed);
182
+ if (allowed !== "*") {
183
+ res.setHeader("Vary", "Origin");
184
+ if (credentials) {
185
+ res.setHeader("Access-Control-Allow-Credentials", "true");
186
+ }
187
+ }
188
+ }
189
+
190
+ if (allowed && opts.exposedHeaders) {
191
+ res.setHeader(
192
+ "Access-Control-Expose-Headers",
193
+ Array.isArray(opts.exposedHeaders) ? opts.exposedHeaders.join(",") : opts.exposedHeaders
194
+ );
195
+ }
196
+
197
+ if (req.method === "OPTIONS" && reqOrigin && req.headers["access-control-request-method"]) {
198
+ if (allowed) {
199
+ res.setHeader("Access-Control-Allow-Methods", Array.isArray(methods) ? methods.join(",") : methods);
200
+ res.setHeader(
201
+ "Access-Control-Allow-Headers",
202
+ Array.isArray(allowedHeaders) ? allowedHeaders.join(",") : allowedHeaders
203
+ );
204
+ if (opts.maxAge) {
205
+ res.setHeader("Access-Control-Max-Age", String(opts.maxAge));
206
+ }
207
+ }
208
+ return res.status(204).end();
209
+ }
210
+
211
+ next();
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Generates middleware that applies HTTP security headers and optional per-request CSP nonces.
217
+ * When the CSP contains `{nonce}` (e.g. `script-src 'self' 'nonce-{nonce}'`) or `nonce: true` is set,
218
+ * a random per-request nonce is exposed as `res.locals.cspNonce` and added to every inline
219
+ * `<script>` / `<style>` rendered by Bluebird views and the SPA shell.
220
+ * @param {Object} [options={}] - Options to override header values.
221
+ * @param {string|false} [options.csp=false] - Content-Security-Policy value.
222
+ * @param {boolean} [options.nonce=false] - Generate a per-request CSP nonce even without `{nonce}` in the policy.
223
+ * @returns {Function} Express middleware.
224
+ */
225
+ function securityHeaders(options = {}) {
226
+ const wantsNonce = Boolean(options.nonce || (typeof options.csp === "string" && options.csp.includes("{nonce}")));
227
+ return (req, res, next) => {
228
+ if (wantsNonce) {
229
+ res.locals.cspNonce = randomBytes(16).toString("base64");
230
+ }
231
+ res.setHeader("X-Frame-Options", options.frameOptions ?? "SAMEORIGIN");
232
+ res.setHeader("X-Content-Type-Options", "nosniff");
233
+ res.setHeader("X-XSS-Protection", "0");
234
+ res.setHeader("Referrer-Policy", options.referrerPolicy ?? "strict-origin-when-cross-origin");
235
+ res.setHeader(
236
+ "Permissions-Policy",
237
+ options.permissionsPolicy ?? "camera=(), microphone=(), geolocation=()"
238
+ );
239
+ if (options.csp) {
240
+ const policy = res.locals.cspNonce
241
+ ? options.csp.split("{nonce}").join(res.locals.cspNonce)
242
+ : options.csp;
243
+ res.setHeader("Content-Security-Policy", policy);
244
+ }
245
+ next();
246
+ };
247
+ }
248
+
249
+ /**
250
+ * Main Application class to manage Express server, Vite assets, routes, and middlewares.
251
+ */
252
+ class App {
253
+ /**
254
+ * Initializes the App instance with the provided options.
255
+ * @param {Object} [options={}] - Configuration options for the application.
256
+ * @param {Array<{path: string, router: import('express').Router}>} [options.routes=[]] - Route objects.
257
+ * @param {Object|boolean} [options.cors={}] - CORS configuration (`false` disables CORS headers).
258
+ * @param {Array<Function>} [options.middlewares=[]] - Global middleware functions.
259
+ * @param {number|string} [options.port=3000] - Server port (use 0 for a dynamic free port in Electron).
260
+ * @param {string} [options.host="http://localhost"] - Server host URL.
261
+ * @param {string} [options.appUrl] - Public application URL.
262
+ * @param {boolean} [options.logger=false] - Whether to enable the request logger.
263
+ * @param {boolean} [options.notFound=true] - Whether to enable the default 404 handler (JSON under `/api`,
264
+ * otherwise the `app/resources/html/notFound.html` view inside the `main` layout, or a built-in page).
265
+ * @param {boolean|Object} [options.json=true] - JSON body parsing (object = express.json options).
266
+ * @param {boolean|Object} [options.urlencoded=true] - URL-encoded body parsing (object = express.urlencoded options).
267
+ * @param {Object} [options.static] - Static file configuration for the `public/` directory.
268
+ * @param {boolean} [options.cookieParser=true] - Whether to enable cookie parsing.
269
+ * @param {boolean|Object} [options.swagger=false] - Enable Swagger documentation.
270
+ * @param {boolean} [options.compression=false] - Enable gzip/brotli compression.
271
+ * @param {boolean|Object} [options.security=true] - Built-in security headers (object = `{ csp, nonce, ... }`).
272
+ * @param {boolean|Object} [options.rateLimit=false] - Built-in rate limiting middleware.
273
+ * @param {boolean|Object} [options.vite=true] - Vite dev middleware / build manifest (object = ViteBridge options).
274
+ * @param {boolean|number|string|string[]} [options.trustProxy="loopback, linklocal, uniquelocal"] - Express `trust proxy`.
275
+ * The default trusts only local/private reverse proxies (Nginx on the same host, Docker), so clients cannot spoof
276
+ * `X-Forwarded-For` to dodge rate limits. Behind a CDN pass its hop count (e.g. `2`) or address list; `true` trusts every hop.
277
+ * @param {boolean} [options.desktop=false] - Electron/Desktop mode (binds 127.0.0.1 and uses a writable userDataDir).
278
+ * @param {string} [options.userDataPath] - Writable directory for SQLite, logs, and file cache in Electron.
279
+ * @param {string} [options.appPath] - Application root for `app/resources/` and `public/` (Electron `app.getAppPath()`).
280
+ * @param {boolean} [options.allowLan=false] - Allow local network / mobile access (binds 0.0.0.0 in desktop mode).
281
+ * @param {boolean} [options.debug] - Force development mode (defaults to `DEBUG=true`).
282
+ */
283
+ constructor(options = {}) {
284
+ if (options.appPath) {
285
+ Config.setAppDir(options.appPath);
286
+ }
287
+ if (options.userDataPath) {
288
+ Config.setUserDataDir(options.userDataPath);
289
+ } else if (options.desktop) {
290
+ process.env.DESKTOP_MODE = "true";
291
+ Config.reload();
292
+ }
293
+
294
+ this.app = express();
295
+ this.app.disable("x-powered-by");
296
+ this.server = http.createServer(this.app);
297
+ this.wsManager = null;
298
+ this.routes = options.routes || [];
299
+ this.cors = options.cors ?? {};
300
+ this.middlewares = options.middlewares || [];
301
+ this.desktop = options.desktop ?? Config.isDesktop();
302
+ this.allowLan = Boolean(options.allowLan);
303
+ this.port = options.port !== undefined ? options.port : (this.desktop ? Number(process.env.DESKTOP_PORT || 0) : props.port);
304
+ this.host = options.host || (this.desktop ? (this.allowLan ? "http://0.0.0.0" : "http://127.0.0.1") : props.host);
305
+ this.appUrl = options.appUrl || props.appUrl;
306
+ this.logger = options.logger ?? false;
307
+ this.notFound = options.notFound ?? true;
308
+ this.json = options.json ?? true;
309
+ this.urlencoded = options.urlencoded ?? true;
310
+ this.static = options.static || props.static;
311
+ this.cookieParser = options.cookieParser ?? true;
312
+ this.swagger = options.swagger ?? false;
313
+ this.compression = options.compression ?? false;
314
+ this.security = options.security ?? true;
315
+ this.rateLimit = options.rateLimit ?? false;
316
+ this.vite = options.vite ?? true;
317
+ this.viteBridge = null;
318
+ this.trustProxy = options.trustProxy ?? (this.desktop ? false : "loopback, linklocal, uniquelocal");
319
+ this.debug = options.debug !== undefined ? Boolean(options.debug) : (props.debug || process.env.DEBUG === "true");
320
+ this._loggerInstance = null;
321
+ this._finalized = false;
322
+
323
+ if (this.trustProxy) {
324
+ this.app.set("trust proxy", this.trustProxy);
325
+ }
326
+
327
+ this._setupCoreMiddlewares();
328
+ }
329
+
330
+ /**
331
+ * Lazily initializes and returns the Logger instance.
332
+ * @returns {Logger}
333
+ */
334
+ get loggerInstance() {
335
+ if (!this._loggerInstance) {
336
+ this._loggerInstance = new Logger();
337
+ }
338
+ return this._loggerInstance;
339
+ }
340
+
341
+ set loggerInstance(val) {
342
+ this._loggerInstance = val;
343
+ }
344
+
345
+ /**
346
+ * Registers a custom middleware or router in the Express application.
347
+ * @param {Function|import('express').Router} record
348
+ */
349
+ use(record) {
350
+ this.app.use(record);
351
+ }
352
+
353
+ /**
354
+ * Sets a configuration value in the Express application.
355
+ * @param {string} key
356
+ * @param {*} value
357
+ */
358
+ set(key, value) {
359
+ this.app.set(key, value);
360
+ }
361
+
362
+ /**
363
+ * Returns the active port number after the server starts listening.
364
+ * @returns {number}
365
+ */
366
+ getPort() {
367
+ const addr = this.server?.address?.();
368
+ if (addr && typeof addr === "object" && addr.port) {
369
+ return addr.port;
370
+ }
371
+ return Number(this.port) || 3000;
372
+ }
373
+
374
+ /**
375
+ * Returns the active internal URL of the server.
376
+ * @returns {string}
377
+ */
378
+ getUrl() {
379
+ const port = this.getPort();
380
+ const cleanHost = this.host.replace(/:\d+$/, "");
381
+ return `${cleanHost}:${port}`;
382
+ }
383
+
384
+ /**
385
+ * Sets up base middleware stack.
386
+ * @private
387
+ */
388
+ _setupCoreMiddlewares() {
389
+ if (this.compression) {
390
+ let compressionMiddleware = null;
391
+ import("compression")
392
+ .then((mod) => {
393
+ const comp = mod.default || mod;
394
+ compressionMiddleware = comp();
395
+ })
396
+ .catch(() => {});
397
+
398
+ this.app.use((req, res, next) => {
399
+ if (compressionMiddleware) {
400
+ return compressionMiddleware(req, res, next);
401
+ }
402
+ next();
403
+ });
404
+ }
405
+
406
+ if (this.json) {
407
+ const jsonOpts = typeof this.json === "object" ? this.json : { limit: "256kb" };
408
+ this.app.use(express.json(jsonOpts));
409
+ }
410
+ if (this.urlencoded) {
411
+ const urlOpts = typeof this.urlencoded === "object" ? { extended: true, ...this.urlencoded } : { extended: true, limit: "256kb" };
412
+ this.app.use(express.urlencoded(urlOpts));
413
+ }
414
+ if (this.cookieParser) this.app.use(nativeCookieParser);
415
+
416
+ if (this.security) {
417
+ this.app.use(securityHeaders(typeof this.security === "object" ? this.security : {}));
418
+ }
419
+
420
+ if (this.cors !== false) {
421
+ this.app.use(nativeCors(this.cors));
422
+ }
423
+
424
+ if (this.rateLimit) {
425
+ this.app.use(RateLimit.middleware(typeof this.rateLimit === "object" ? this.rateLimit : {}));
426
+ }
427
+
428
+ this.app.use((req, res, next) => {
429
+ const requestedLang = [req.query?.lang, req.body?.lang, req.cookies?.lang].find(
430
+ (value) => typeof value === "string" && LANG_PATTERN.test(value)
431
+ );
432
+ req.lang = requestedLang || "en";
433
+ res.locals.lang = req.lang;
434
+
435
+ res.success = (data = null, message = "Success", statusCode = 200) =>
436
+ res.status(statusCode).json({ status: "success", message, data });
437
+
438
+ res.error = (message = "Error", statusCode = 400, errors = []) =>
439
+ res.status(statusCode).json({ status: "error", message, errors });
440
+
441
+ res.ok = (data = null, message = "Success") => res.success(data, message, 200);
442
+
443
+ res.created = (data = null, message = "Created") => res.success(data, message, 201);
444
+
445
+ res.badRequest = (message = "Bad Request", errors = []) => res.error(message, 400, errors);
446
+
447
+ res.unauthorized = (message = "Unauthorized") => res.error(message, 401);
448
+
449
+ res.forbidden = (message = "Forbidden") => res.error(message, 403);
450
+
451
+ res.notFound = (message = "Not Found") => res.error(message, 404);
452
+
453
+ res.serverError = (message = "Internal Server Error", errors = []) => res.error(message, 500, errors);
454
+
455
+ res.paginate = (data = [], pagination = {}, message = "Success") => {
456
+ const page = Number(pagination.page) || 1;
457
+ const limit = Number(pagination.limit) || data.length;
458
+ const total = Number(pagination.total) || data.length;
459
+ const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;
460
+ return res.status(200).json({ status: "success", message, data, pagination: { page, limit, total, totalPages } });
461
+ };
462
+
463
+ res.sse = (options = {}) => {
464
+ const retryMs = Number(options.retry) || 3000;
465
+ const keepAliveMs = options.keepAliveMs !== undefined ? Number(options.keepAliveMs) : 15000;
466
+
467
+ res.writeHead(200, {
468
+ "Content-Type": "text/event-stream; charset=utf-8",
469
+ "Cache-Control": "no-cache, no-transform",
470
+ Connection: "keep-alive",
471
+ "X-Accel-Buffering": "no",
472
+ ...(options.headers || {}),
473
+ });
474
+ res.write(`retry: ${retryMs}\n\n`);
475
+
476
+ let closed = false;
477
+ const closeCallbacks = new Set();
478
+
479
+ const keepAliveTimer =
480
+ keepAliveMs > 0
481
+ ? setInterval(() => {
482
+ if (!closed && !res.writableEnded) {
483
+ res.write(":ping\n\n");
484
+ }
485
+ }, keepAliveMs)
486
+ : null;
487
+
488
+ const cleanup = () => {
489
+ if (closed) return;
490
+ closed = true;
491
+ if (keepAliveTimer) clearInterval(keepAliveTimer);
492
+ for (const fn of closeCallbacks) {
493
+ try {
494
+ fn();
495
+ } catch {}
496
+ }
497
+ };
498
+
499
+ req.on("close", cleanup);
500
+
501
+ const writeEvent = (event, data, id) => {
502
+ if (closed || res.writableEnded) return false;
503
+ if (id !== undefined && id !== null) {
504
+ res.write(`id: ${String(id)}\n`);
505
+ }
506
+ if (event && event !== "message") {
507
+ res.write(`event: ${String(event)}\n`);
508
+ }
509
+ const payload = typeof data === "string" ? data : JSON.stringify(data ?? {});
510
+ const lines = String(payload).split(/\r?\n/);
511
+ for (let i = 0; i < lines.length; i++) {
512
+ res.write(`data: ${lines[i]}\n`);
513
+ }
514
+ res.write("\n");
515
+ return true;
516
+ };
517
+
518
+ return {
519
+ send(dataOrEvent, maybeData, maybeId) {
520
+ if (arguments.length >= 2) {
521
+ return writeEvent(dataOrEvent, maybeData, maybeId);
522
+ }
523
+ return writeEvent("message", dataOrEvent);
524
+ },
525
+ event(name, data, id) {
526
+ return writeEvent(name, data, id);
527
+ },
528
+ comment(text = "ping") {
529
+ if (closed || res.writableEnded) return false;
530
+ res.write(`:${String(text).replace(/\r?\n/g, " ")}\n\n`);
531
+ return true;
532
+ },
533
+ onClose(fn) {
534
+ if (typeof fn === "function") closeCallbacks.add(fn);
535
+ },
536
+ close() {
537
+ cleanup();
538
+ if (!res.writableEnded) {
539
+ res.end();
540
+ }
541
+ },
542
+ };
543
+ };
544
+
545
+ res.setHeader("X-Powered-By", "Blue Bird");
546
+ next();
547
+ });
548
+
549
+ this.app.get("/api/health", (req, res) =>
550
+ res.json({
551
+ status: "ok",
552
+ timestamp: new Date().toISOString(),
553
+ uptime: Math.floor(process.uptime()),
554
+ environment: this.debug ? "development" : "production",
555
+ desktop: this.desktop,
556
+ memory: {
557
+ rss: `${Math.round(process.memoryUsage().rss / 1024 / 1024)}MB`,
558
+ heapUsed: `${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`,
559
+ },
560
+ })
561
+ );
562
+
563
+ const staticPath = this.static?.path || "public";
564
+ const staticOptions = this.static?.options || {};
565
+ const isDebug = this.debug;
566
+ const resolvedStaticDir = path.isAbsolute(staticPath)
567
+ ? staticPath
568
+ : path.resolve(Config.appDir(), staticPath);
569
+
570
+ this.app.use(
571
+ express.static(resolvedStaticDir, {
572
+ ...staticOptions,
573
+ setHeaders: (res) => {
574
+ res.setHeader("X-Powered-By", "Blue Bird");
575
+ res.setHeader(
576
+ "Cache-Control",
577
+ isDebug ? "no-cache" : "public, max-age=2592000, immutable"
578
+ );
579
+ },
580
+ })
581
+ );
582
+
583
+ if (this.desktop) {
584
+ const uploadsDir = path.join(Config.userDataDir(), "uploads");
585
+ if (!fs.existsSync(uploadsDir)) {
586
+ try {
587
+ fs.mkdirSync(uploadsDir, { recursive: true });
588
+ } catch {}
589
+ }
590
+ this.app.use("/uploads", express.static(uploadsDir));
591
+ }
592
+
593
+ this.middlewares.forEach((middleware) => {
594
+ this.app.use(middleware);
595
+ });
596
+
597
+ if (this.logger || props.debug) this._middlewareLogger(this.logger);
598
+
599
+ if (props.debug) {
600
+ Debug.middlewareMetrics(this.app);
601
+ }
602
+ }
603
+
604
+ /**
605
+ * Finalizes application routes, 404, and error handling.
606
+ * Called automatically before listening.
607
+ * @private
608
+ */
609
+ async _finalize() {
610
+ if (this._finalized) return;
611
+ this._finalized = true;
612
+
613
+ if (this.swagger) {
614
+ const { default: Swagger } = await import("./swagger.js");
615
+ const defaultSwaggerOptions = {
616
+ info: { title: "Blue Bird API", version: "1.0.0", description: "Blue Bird Framework API Documentation" },
617
+ url: this.appUrl ? this.appUrl : `${this.host}:${this.port}`,
618
+ route: "/docs",
619
+ };
620
+ Swagger.init(this.app, {
621
+ ...defaultSwaggerOptions,
622
+ ...(typeof this.swagger === "object" ? this.swagger : {}),
623
+ });
624
+ }
625
+
626
+ await this._dispatchRoutes();
627
+
628
+ if (this.notFound) this._notFoundDefault();
629
+
630
+ this._errorHandler();
631
+ }
632
+
633
+ /**
634
+ * Middleware that logs incoming HTTP requests.
635
+ * @private
636
+ * @param {boolean} [logger=false]
637
+ */
638
+ _middlewareLogger(logger = false) {
639
+ this.app.use((req, res, next) => {
640
+ const method = req.method;
641
+ const url = req.url.replace(/(password|token|authorization)=([^&]+)/gi, "$1=***");
642
+ if (url.includes("chrome")) return next();
643
+ const params = Object.keys(req.params).length > 0 ? ` ${JSON.stringify(req.params)}` : "";
644
+ const ip = req.ip || req.socket?.remoteAddress;
645
+ const now = new Date().toISOString();
646
+ const time = `${now.split("T")[0]} ${now.split("T")[1].split(".")[0]}`;
647
+ let message = ` ${time} -${ip} -[${method}] ${url} ${params}`;
648
+
649
+ if (logger) this.loggerInstance.info(message);
650
+
651
+ if (props.debug) {
652
+ message = `${colors.bold.green(time)} - ${colors.bold.cyan(ip)} -[${colors.bold.red(method)}] ${colors.bold.blue(url)} ${colors.bold.yellow(params)}`;
653
+ console.log(message);
654
+ }
655
+ next();
656
+ });
657
+ }
658
+
659
+ /**
660
+ * Global error handler for the application.
661
+ * @private
662
+ */
663
+ _errorHandler() {
664
+ this.app.use((err, req, res, next) => {
665
+ const statusCode = err.statusCode || err.status || 500;
666
+ const message = err.message || "Internal Server Error";
667
+ const errors = err.errors || [];
668
+
669
+ if (this.logger) {
670
+ this.loggerInstance.error(`[${statusCode}] ${message} - ${err.stack}`);
671
+ }
672
+
673
+ const payload = {
674
+ status: "error",
675
+ message: statusCode === 500 && !props.debug ? "Internal Server Error" : message,
676
+ errors,
677
+ };
678
+
679
+ if (props.debug && err.stack) payload.stack = err.stack;
680
+
681
+ return res.status(statusCode).json(payload);
682
+ });
683
+ }
684
+
685
+ /**
686
+ * When started by `npx bluebird-js dev`, exits as soon as the runner's IPC channel closes, so a killed
687
+ * runner (closed terminal, task kill on Windows) never leaves an orphan server holding the port.
688
+ * @private
689
+ */
690
+ _exitWithDevRunner() {
691
+ if (this._devRunnerHooked || process.env.BLUEBIRD_DEV_RUNNER !== "1" || typeof process.send !== "function") return;
692
+ this._devRunnerHooked = true;
693
+ process.on("disconnect", () => {
694
+ this.close().finally(() => process.exit(0));
695
+ setTimeout(() => process.exit(0), 1500).unref();
696
+ });
697
+ }
698
+
699
+ /**
700
+ * Attaches Vite middleware/manifest, SEO routes, and all registered routers.
701
+ * @private
702
+ */
703
+ async _dispatchRoutes() {
704
+ if (props.debug) {
705
+ const debug = new Debug();
706
+ const debugRouter = debug.getRouter();
707
+ this.app.use(debugRouter.path, debugRouter.router);
708
+ }
709
+
710
+ const hasSpaRouter = this.routes.some((r) => r._hasSpa);
711
+ const rootDir = Config.appDir();
712
+ if (this.vite !== false && (hasSpaRouter || ViteBridge.needed(rootDir))) {
713
+ const viteOpts = typeof this.vite === "object" ? this.vite : {};
714
+ this.viteBridge = new ViteBridge({
715
+ root: rootDir,
716
+ dev: this.debug,
717
+ ...viteOpts,
718
+ });
719
+ await this.viteBridge.init(this.app, this.server);
720
+ this.app.locals._viteBridge = this.viteBridge;
721
+ }
722
+
723
+ const hasSeoRouter = this.routes.some((r) => r._seo) || Seo.getRoutes().length > 0;
724
+ if (hasSeoRouter) {
725
+ this.app.get("/sitemap.xml", (req, res) => {
726
+ res.setHeader("Content-Type", "application/xml; charset=utf-8");
727
+ res.send(Seo.generateSitemap(this.appUrl));
728
+ });
729
+ this.app.get("/robots.txt", (req, res) => {
730
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
731
+ res.send(Seo.generateRobots(this.appUrl));
732
+ });
733
+ }
734
+
735
+ this.routes.forEach((route) => {
736
+ this.app.use(route.path, route.router);
737
+ });
738
+ }
739
+
740
+ /**
741
+ * Default 404 handler for unmatched routes.
742
+ * @private
743
+ */
744
+ _notFoundDefault() {
745
+ this.app.use(async (req, res, next) => {
746
+ const isApi = req.path === "/api" || req.path.startsWith("/api/");
747
+ const expectsHtml = !isApi && (req.method === "GET" || req.method === "HEAD") && req.accepts(["html", "json"]) === "html";
748
+ if (!expectsHtml) return res.status(404).json({ message: "Not Found" });
749
+ try {
750
+ const { default: ViewLoader } = await import("./view-loader.js");
751
+ if (await ViewLoader.load("notFound")) {
752
+ const { default: Render } = await import("./render.js");
753
+ res.status(404);
754
+ return await Render.html(res, "notFound", { title: "Page not found", path: req.path }, { layout: "main" });
755
+ }
756
+ } catch (err) {
757
+ return next(err);
758
+ }
759
+ res.status(404).type("html").send(NOT_FOUND_HTML.replace("%LANG%", req.lang || "en"));
760
+ });
761
+ }
762
+
763
+ /**
764
+ * Starts the HTTP server and listens for incoming connections.
765
+ * @returns {Promise<import('http').Server>}
766
+ */
767
+ async run() {
768
+ this._exitWithDevRunner();
769
+ await this._finalize();
770
+
771
+ return new Promise((resolve, reject) => {
772
+ const onListening = () => {
773
+ const activePort = this.getPort();
774
+ this.port = activePort;
775
+ if (this.desktop) {
776
+ this.appUrl = `http://127.0.0.1:${activePort}`;
777
+ }
778
+ let banner =
779
+ colors.bold.blue("Blue Bird Server Online\n") +
780
+ colors.bold.cyan("App URL: ") +
781
+ colors.green(`${this.appUrl}`) +
782
+ "\n" +
783
+ colors.bold.cyan("Internal: ") +
784
+ colors.green(`${this.host}:${activePort}`) +
785
+ "\n";
786
+
787
+ if (this.desktop && this.allowLan) {
788
+ const lanIp = getLanIp();
789
+ banner +=
790
+ colors.bold.cyan("LAN / QR: ") +
791
+ colors.yellow(`http://${lanIp}:${activePort}`) +
792
+ "\n";
793
+ }
794
+
795
+ banner += colors.gray("────────────────────────────────");
796
+ console.log(banner);
797
+ if (!this.desktop) {
798
+ loopbackReachesServer(this.server, activePort).then((mine) => {
799
+ if (mine) return;
800
+ console.warn(
801
+ colors.yellow(
802
+ `[WARN] Another process is listening on 127.0.0.1:${activePort}, so http://localhost:${activePort} may open it instead of this app. ` +
803
+ `Stop it (e.g. VS Code Live Preview) or set PORT to a free port.`
804
+ )
805
+ );
806
+ });
807
+ }
808
+ resolve(this.server);
809
+ };
810
+
811
+ this.server.on("error", reject);
812
+
813
+ if (this.desktop) {
814
+ const bindAddress = this.allowLan ? "0.0.0.0" : "127.0.0.1";
815
+ this.server.listen(this.port, bindAddress, onListening);
816
+ } else {
817
+ this.server.listen(this.port, onListening);
818
+ }
819
+ });
820
+ }
821
+
822
+ /**
823
+ * Starts the server in Electron / Desktop mode, binding to 127.0.0.1 (or 0.0.0.0 when `allowLan` is true),
824
+ * using a dynamic port when port is 0, and returning the local URL ready for `mainWindow.loadURL(url)`.
825
+ * @param {Object} [options={}]
826
+ * @param {string} [options.appPath] - Path from Electron `app.getAppPath()`.
827
+ * @param {string} [options.userDataPath] - Path from Electron `app.getPath("userData")`.
828
+ * @param {boolean} [options.allowLan=false] - Allow local network / mobile access (binds 0.0.0.0).
829
+ * @param {string} [options.host] - Custom host override.
830
+ * @param {number} [options.port] - Custom port override.
831
+ * @returns {Promise<{server: import('http').Server, port: number, url: string, lanUrl?: string, lanIp?: string}>}
832
+ */
833
+ async runDesktop(options = {}) {
834
+ if (options.appPath) {
835
+ Config.setAppDir(options.appPath);
836
+ }
837
+ if (options.userDataPath) {
838
+ Config.setUserDataDir(options.userDataPath);
839
+ }
840
+ if (options.port !== undefined) {
841
+ this.port = options.port;
842
+ }
843
+ if (options.allowLan !== undefined) {
844
+ this.allowLan = Boolean(options.allowLan);
845
+ }
846
+ this.desktop = true;
847
+ this.host = options.host || (this.allowLan ? "http://0.0.0.0" : "http://127.0.0.1");
848
+ await this.run();
849
+ const port = this.getPort();
850
+ const url = `http://127.0.0.1:${port}`;
851
+ const result = { server: this.server, port, url };
852
+ if (this.allowLan) {
853
+ const lanIp = getLanIp();
854
+ result.lanIp = lanIp;
855
+ result.lanUrl = `http://${lanIp}:${port}`;
856
+ }
857
+ return result;
858
+ }
859
+
860
+ /**
861
+ * Closes the running HTTP server, Vite dev server, and cleans up database connections.
862
+ * @returns {Promise<void>}
863
+ */
864
+ async close() {
865
+ try {
866
+ if (this.viteBridge) await this.viteBridge.close();
867
+ } catch {}
868
+ try {
869
+ const { Database } = await import("./database.js");
870
+ await Database.closeAll();
871
+ } catch {}
872
+ try {
873
+ const { default: Model } = await import("./model.js");
874
+ await Model.close();
875
+ } catch {}
876
+
877
+ return new Promise((resolve, reject) => {
878
+ if (this.server) {
879
+ this.server.close((err) => (err ? reject(err) : resolve()));
880
+ } else {
881
+ resolve();
882
+ }
883
+ });
884
+ }
885
+
886
+ /**
887
+ * Initializes and returns the WebSocket manager attached to the HTTP server.
888
+ * @param {Function|Object} [options]
889
+ * @returns {WebSocketManager}
890
+ */
891
+ websocket(options = {}) {
892
+ const handler = typeof options === "function" ? options : null;
893
+ const wsOptions = typeof options === "object" && options !== null ? options : {};
894
+
895
+ if (!this.wsManager) {
896
+ this.wsManager = new WebSocketManager(this.server, wsOptions);
897
+ }
898
+ if (handler) {
899
+ this.wsManager.onConnection(handler);
900
+ }
901
+ return this.wsManager;
902
+ }
903
+
904
+ /**
905
+ * Returns a pre-configured Helmet middleware function synchronously.
906
+ * @param {Object} [options={}]
907
+ * @returns {Function} Express middleware.
908
+ */
909
+ static helmet(options = {}) {
910
+ let helmetMiddleware = null;
911
+ let loadPromise = null;
912
+
913
+ return (req, res, next) => {
914
+ if (helmetMiddleware) return helmetMiddleware(req, res, next);
915
+
916
+ if (!loadPromise) {
917
+ loadPromise = import("helmet")
918
+ .then((mod) => {
919
+ const helmetFn = mod.default || mod;
920
+ helmetMiddleware = helmetFn({
921
+ contentSecurityPolicy: props.debug ? false : undefined,
922
+ hidePoweredBy: false,
923
+ ...options,
924
+ });
925
+ })
926
+ .catch(() => {
927
+ console.error("[APP WARN] 'helmet' is not installed. Run: npx bluebird-js add helmet");
928
+ });
929
+ }
930
+
931
+ loadPromise.then(() => {
932
+ if (helmetMiddleware) helmetMiddleware(req, res, next);
933
+ else next();
934
+ });
935
+ };
936
+ }
937
+
938
+ /**
939
+ * Returns the built-in security headers middleware.
940
+ * @param {Object} [options={}]
941
+ * @returns {Function} Express middleware.
942
+ */
943
+ static securityHeaders(options = {}) {
944
+ return securityHeaders(options);
945
+ }
946
+
947
+ /**
948
+ * Returns a new or default unified AI instance.
949
+ * @param {Object} [options={}]
950
+ * @returns {AI}
951
+ */
952
+ static ai(options = {}) {
953
+ return Object.keys(options).length > 0 ? new AI(options) : ai;
954
+ }
955
+
956
+ /**
957
+ * Returns the native rate-limiting middleware for protecting specific routes or routers.
958
+ * @param {Object} [options={}]
959
+ * @returns {Function} Express middleware.
960
+ */
961
+ static rateLimit(options = {}) {
962
+ return RateLimit.middleware(options);
963
+ }
964
+ }
965
+
966
+ /**
967
+ * Operational application error class for standardizing custom API errors.
968
+ */
969
+ export class AppError extends Error {
970
+ /**
971
+ * Creates an AppError instance.
972
+ * @param {string} message
973
+ * @param {number} [statusCode=500]
974
+ * @param {Array|Object} [errors=[]]
975
+ */
976
+ constructor(message, statusCode = 500, errors = []) {
977
+ super(message);
978
+ this.name = "AppError";
979
+ this.statusCode = statusCode;
980
+ this.errors = errors;
981
+ this.isOperational = true;
982
+ Error.captureStackTrace(this, this.constructor);
983
+ }
984
+ }
985
+
986
+ export { App, AI, ai };
987
+ export default App;