@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/AGENTS.md CHANGED
@@ -1,620 +1,726 @@
1
- # Bluebird.js Framework - AI Agent Guide
2
-
3
- This document serves as the primary manual for any AI Agent interacting with the codebase. It details the architecture of Bluebird.js (`@seip/bluebird-js`), its internal modules, and how features should be written or modified.
4
-
5
- ## 1. Core Architecture
6
-
7
- Bluebird.js is a performance-first web and API framework built on **Express** (Node.js 22.18+). It provides pure modern JavaScript ESM execution, JWT auth, HTML rendering with multi-level caching, BaseModel, schema validation, database access, and queue processing out of the box.
8
-
9
- - **Entrypoint (`index.js`)**: Located at the project root. Initializes the server using `App` from `core/app.js` and registers the routes.
10
- - **Application (`app/`)**: Application code — `app/routes/` (API + web), `app/models/` (BaseModels), `app/views/` (HTML templates), `app/jobs/` (background workers).
11
- - **Public assets (`public/`)**: Static files only (CSS, JS, images, fonts). Served directly by Nginx or Express fallback.
12
- - **Core (`core/`)**: The framework core. Contains `Router`, `Render`, `Validator`, `Auth`, `Cache`, `Redis`, `Database`, `Model`, `Csrf`, `Hash`, etc. **DO NOT MODIFY** the core unless explicitly requested.
13
-
14
- ## 2. Modern JavaScript Standard (ESM)
15
-
16
- Bluebird.js standardizes on pure modern JavaScript (Node.js 22.18+ ESM) with zero build steps or transpilation pipelines required:
17
-
18
- - **Root Entrypoint (`index.js`)**: Run in development with `node --watch --env-file=.env index.js`.
19
- - **Production Entrypoint (`index.js`)**: Run with `node --env-file=.env index.js` or via PM2 cluster.
20
- - **Initialization**: `npx bluebird-js` scaffolds a new project directly with `index.js` at the root.
21
- - **IDE Intellisense**: Powered by `core/index.d.ts` and `jsconfig.json`.
22
-
23
- ```javascript
24
- import App from "@seip/bluebird-js/core/app.js";
25
- import routerApi from "./app/routes/api.js";
26
- import routerWeb from "./app/routes/web.js";
27
-
28
- const app = new App({
29
- routes: [routerWeb, routerApi],
30
- port: process.env.PORT || 3000,
31
- });
32
-
33
- app.run();
34
- ```
35
-
36
- ## 3. Routing (Router)
37
-
38
- Do not use Express' native router directly. Always use Bluebird's `Router` wrapper.
39
-
40
- ```javascript
41
- import Router from "@seip/bluebird-js/core/router.js";
42
-
43
- const routerApi = new Router("/api");
44
-
45
- routerApi.get("/users", (req, res) => {
46
- res.json({ users: [] });
47
- });
48
-
49
- export default routerApi;
50
- ```
51
-
52
- When created with `{ seo: true }`, all GET routes registered on that router are tracked for search engine indexing.
53
-
54
- ## 4. Request Validation (Validator)
55
-
56
- Incoming request data is validated using `core/validate.js`, which automatically returns HTTP 400 JSON responses on error. The validator inspects request payloads without destructively mutating raw data.
57
-
58
- ```javascript
59
- import Validator from "@seip/bluebird-js/core/validate.js";
60
-
61
- const userSchema = {
62
- email: { required: true, email: true },
63
- password: { required: true, min: 8 },
64
- bio: { required: false },
65
- };
66
-
67
- const validateUser = new Validator(userSchema, "en");
68
-
69
- routerApi.post("/users", validateUser.middleware(), (req, res) => {
70
- res.json({ success: true });
71
- });
72
- ```
73
-
74
- ## 5. Lightweight BaseModel (Model)
75
-
76
- > **Important Architecture Note:**
77
- > Bluebird's `BaseModel` (`core/model.js`) is designed as a lightweight, zero-dependency static facade for high performance, simple queries, soft deletes, and migrations.
78
- > **For complex multi-tier enterprise ORM mapping, Prisma is recommended.**
79
-
80
- ### Defining a Model
81
-
82
- Create models inside `app/models/`:
83
-
84
- ```javascript
85
- import Model from "@seip/bluebird-js/core/model.js";
86
-
87
- export default class User extends Model {
88
- static table = "users";
89
- static primaryKey = "id";
90
- static timestamps = true;
91
- static softDelete = true;
92
-
93
- static schema = {
94
- id: { type: "int", primary: true, auto: true },
95
- name: { type: "string", length: 150, required: true },
96
- email: { type: "string", length: 150, unique: true, required: true, email: true },
97
- password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
98
- role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
99
- };
100
- }
101
- ```
102
-
103
- ### CRUD Shortcuts & Query Facades
104
-
105
- Every Model exposes direct shortcuts to database queries, transactions, and mutations:
106
-
107
- ```javascript
108
- const total = await User.query("SELECT COUNT(*) as count FROM users", [], "return_row");
109
- await User.transaction(async (tx) => {
110
- await tx.query("UPDATE users SET role = ? WHERE id = ?", ["admin", 1]);
111
- });
112
-
113
- const userId = await User.create({ name: "Alice", email: "alice@example.com", password: "secretPassword" });
114
-
115
- const user = await User.find(1, { cache: 60 });
116
- const userWithPosts = await User.find(1, { oneMany: Post });
117
- const postWithAuthor = await Post.find(10, { belongsTo: User });
118
-
119
- const page = await User.paginate({ where: { role: "user" }, page: 1, limit: 10 });
120
- await User.update(userId, { name: "Alice Smith" });
121
-
122
- const totalUsers = await User.count({ role: "user" });
123
- const exists = await User.exists({ email: "alice@example.com" });
124
-
125
- const matching = await User.all({
126
- where: {
127
- id: [1, 2, 3],
128
- role: { $ne: "banned" },
129
- views: { $gt: 100 },
130
- },
131
- });
132
-
133
- const userRecord = await User.firstOrCreate({ email: "john@example.com" }, { name: "John Doe" });
134
- const updatedRecord = await User.updateOrCreate({ email: "john@example.com" }, { name: "Johnathan" });
135
-
136
- await User.delete(userId);
137
- await User.delete(userId, { force: true });
138
- await User.delete(userId, { cascade: [Post] });
139
- await User.restore(userId);
140
- ```
141
-
142
- ## 6. CSRF Protection (Csrf)
143
-
144
- Bluebird provides native, zero-dependency HMAC-signed CSRF protection (`core/csrf.js`):
145
-
146
- ```javascript
147
- import Csrf from "@seip/bluebird-js/core/csrf.js";
148
-
149
- routerWeb.use(Csrf.middleware());
150
- ```
151
-
152
- ## 7. Authentication & Password Hashing (Auth & Hash)
153
-
154
- ### Password Hashing (Hash)
155
-
156
- Native password hashing using `node:crypto.scrypt` with random salt and timing-safe comparison (zero external npm dependencies required).
157
-
158
- ```javascript
159
- import Hash from "@seip/bluebird-js/core/hash.js";
160
-
161
- const hash = await Hash.make("mySecretPassword");
162
- const isValid = await Hash.verify("mySecretPassword", hash);
163
- ```
164
-
165
- ### JWT Handling (Auth)
166
-
167
- Native JWT handling with AES-256-GCM encryption and HMAC-SHA256 signature verification using `node:crypto`.
168
-
169
- ```javascript
170
- import Auth from "@seip/bluebird-js/core/auth.js";
171
-
172
- router.get("/profile", Auth.protect(), (req, res) => {
173
- res.json({ user: req.user });
174
- });
175
-
176
- router.post("/login", async (req, res) => {
177
- const user = { id: 1, name: "John" };
178
- await Auth.login(res, user);
179
- res.ok(user, "Logged in");
180
- });
181
-
182
- router.post("/logout", async (req, res) => {
183
- await Auth.logout(res);
184
- res.ok(null, "Logged out");
185
- });
186
- ```
187
-
188
- ## 8. HTTP Response Helpers & Health Check
189
-
190
- Bluebird decorates the Express `res` object with standardized helper methods:
191
-
192
- ```javascript
193
- res.ok(data, "Success message");
194
- res.created(data, "Created successfully");
195
- res.paginate(items, pagination, "Fetched");
196
-
197
- res.badRequest("Invalid input", errors);
198
- res.unauthorized("Authentication required");
199
- res.forbidden("Access denied");
200
- res.notFound("Resource not found");
201
- res.serverError("Internal failure", err);
202
- ```
203
-
204
- Every Bluebird application provides a native `/api/health` endpoint returning uptime, timestamp, environment, and memory consumption.
205
-
206
- ## 9. Performance Caching (Cache & Redis)
207
-
208
- Caching defaults to fast in-memory LRU storage, ideal for desktop applications and single or dual PM2 instances. Filesystem caching (`driver: "file"`) is available as persistent local fallback, and Redis (`driver: "redis"`) is isolated in `core/redis.js` on-demand for high-traffic environments.
209
-
210
- ```javascript
211
- import Cache from "@seip/bluebird-js/core/cache.js";
212
-
213
- router.get("/stats", Cache.middleware(60), (req, res) => {
214
- res.ok({ usersCount: 150 });
215
- });
216
-
217
- await Cache.set("custom_key", { data: "value" }, 120, { driver: "memory" });
218
- const cachedData = await Cache.get("custom_key", { driver: "memory" });
219
-
220
- const stats = await Cache.deduplicate("stats-key", async () => {
221
- return await calculateHeavyStats();
222
- });
223
-
224
- await Cache.delete("custom_key");
225
- await Cache.clear();
226
- ```
227
-
228
- ## 10. Database Module (database.js)
229
-
230
- Bluebird provides a unified wrapper class (`core/database.js`) supporting **SQLite (native `node:sqlite` in Node 22.18+ with `better-sqlite3` fallback)**, **MySQL (`mysql2/promise`)**, and **PostgreSQL (`pg`)**:
231
-
232
- - **Native SQLite by Default:** No native C++ compilation or build tools required.
233
- - **SQLite Concurrency & WAL:** Automatically configures WAL mode, busy timeout, and memory-mapped I/O.
234
- - **Prepared Statement Caching:** SQLite caches prepared statement ASTs automatically.
235
- - **Query Caching:** Supports `{ cache: 60 }` across memory, file, and redis backends.
236
-
237
- ```javascript
238
- import { Database, DB_TYPE } from "@seip/bluebird-js/core/database.js";
239
-
240
- const connection = new Database(20);
241
-
242
- const user = await connection.query("SELECT * FROM users WHERE id = ?", [1], "return_row");
243
- const stats = await connection.query("SELECT COUNT(*) as cnt FROM logs", [], { cache: 60 });
244
-
245
- await connection.transaction(async (tx) => {
246
- const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
247
- await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
248
- });
249
-
250
- // Atomic, WAL-safe compressed database backup with retention rotation
251
- const backup = await Database.backup({ out: "database/backups", keep: 10, compress: true });
252
-
253
- // Integrity-verified restore with pre-restore safety snapshot
254
- await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.gz", {
255
- safetyBackup: true,
256
- verify: true,
257
- });
258
- ```
259
-
260
- ## 11. On-Demand Modules & CLI Add
261
- const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
262
- await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
263
- });
264
- ```
265
-
266
- ## 11. On-Demand Modules & CLI Add
267
-
268
- To keep dependencies lightweight and minimal, optional modules load dynamically on-demand:
269
-
270
- ```bash
271
- npx bluebird-js add upload # Installs multer for file uploads
272
- npx bluebird-js add ws # Installs ws for WebSockets
273
- npx bluebird-js add redis # Installs redis for distributed caching
274
- npx bluebird-js add sqlite # Installs better-sqlite3 (fallback for older environments)
275
- npx bluebird-js add mysql # Installs mysql2
276
- npx bluebird-js add postgres # Installs pg
277
- npx bluebird-js add bcrypt # Installs bcrypt
278
- npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
279
- npx bluebird-js add helmet # Installs helmet
280
- npx bluebird-js add ejs # Installs ejs
281
- npx bluebird-js add react-islands # Installs react, react-dom, vite & scaffolds island runtime
282
- ```
283
-
284
- ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
285
-
286
- Bluebird includes native zero-dependency security headers enabled by default (`X-Content-Type-Options: nosniff`, `X-XSS-Protection: 0`, `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy`).
287
-
288
- ### Native Rate Limiting (`core/ratelimit.js`)
289
-
290
- Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers):
291
-
292
- ```javascript
293
- import App from "@seip/bluebird-js/core/app.js";
294
-
295
- const app = new App({
296
- routes: [routerWeb, routerApi],
297
- rateLimit: { max: 120, windowMs: 60000 },
298
- });
299
-
300
- routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req, res) => {
301
- res.ok({ authenticated: true });
302
- });
303
- ```
304
-
305
- ### Automatic SEO Sitemap & Robots (`core/seo.js`)
306
-
307
- When a `Router` is created with `{ seo: true }`, all static `GET` routes are automatically registered and exposed at `/sitemap.xml` and `/robots.txt` by `App`.
308
-
309
- ### Helmet Integration
310
-
311
- Helmet can be applied per router when installed (`npx bluebird-js add helmet`):
312
-
313
- ```javascript
314
- import App from "@seip/bluebird-js/core/app.js";
315
-
316
- const apiRouter = new Router("/api");
317
- apiRouter.use(App.helmet());
318
- ```
319
-
320
- ## 13. Production Deployment & Electron Desktop Mode
321
-
322
- ### PM2 & Nginx Reverse Proxy
323
-
324
- Production deployments run directly via `npm start` or PM2 cluster mode:
325
-
326
- ```bash
327
- npx bluebird-js make:ecosystem # Generates ecosystem.config.cjs
328
- npx bluebird-js make:ecosystem --start # Generates and starts immediately in PM2
329
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx config with upstream keepalive & static try_files
330
- ```
331
-
332
- For complete deployment details including Nginx reverse proxy configuration and optional standalone Docker snippet, consult [production.md](production.md).
333
-
334
- ### Electron & Desktop Mode (`desktop: true`)
335
-
336
- Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
337
-
338
- - **Base Directory Resolution (`appPath`)**: Accepts `appPath: electronApp.getAppPath()` (or `Config.setAppDir()`) to ensure views (`app/views/`) and static assets (`public/`) resolve accurately regardless of shortcut launch locations (`process.cwd()`).
339
- - **Writable User Data (`userDataPath`)**: Automatically routes SQLite database files, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`electronApp.getPath("userData")`), copying bundled initial SQLite template databases from `appPath`, `process.resourcesPath`, or `.asar.unpacked` on first launch.
340
- - **Dynamic Port & LAN / QR Access**:
341
- - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
342
- - When `{ allowLan: true }` is enabled, binds to `0.0.0.0` and returns `{ server, port, url, lanUrl, lanIp }` ready for mobile QR code access on local WiFi.
343
- - **Uploads & Static Serving**:
344
- - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
345
- - **Clean Shutdown & WAL Checkpoint**:
346
- - Invoking `await app.close()` (e.g. in Electron `app.on("before-quit")`) automatically checkpoints SQLite WAL (`PRAGMA wal_checkpoint(TRUNCATE)`), closes open database handles via `Database.closeAll()`, and frees Windows file locks cleanly.
347
- - **Packaging with electron-builder**:
348
- - Recommended `electron-builder` configuration in `package.json`:
349
- ```json
350
- "build": {
351
- "asar": true,
352
- "asarUnpack": ["app/views/**/*", "database/**/*"]
353
- }
354
- ```
355
-
356
- ```javascript
357
- import App from "@seip/bluebird-js/core/app.js";
358
- import { app as electronApp, BrowserWindow } from "electron";
359
- import routerApi from "./app/routes/api.js";
360
- import routerWeb from "./app/routes/web.js";
361
-
362
- const app = new App({
363
- desktop: true,
364
- appPath: electronApp.getAppPath(),
365
- userDataPath: electronApp.getPath("userData"),
366
- routes: [routerWeb, routerApi],
367
- });
368
-
369
- electronApp.whenReady().then(async () => {
370
- const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
371
- const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
372
- mainWindow.loadURL(url);
373
-
374
- electronApp.on("before-quit", async () => {
375
- await app.close();
376
- });
377
- });
378
- ```
379
-
380
- ## 14. Developer Tooling CLI
381
-
382
- ```bash
383
- npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
384
- npx bluebird-js make:model <Name> # BaseModel scaffolding
385
- npx bluebird-js make:route <name> # REST route scaffolding
386
- npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
387
- npx bluebird-js make:view <name> # HTML or EJS template scaffolding
388
- npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
389
- npx bluebird-js make:migration --model <Model> # Auto DDL migration for specific Model schema
390
- npx bluebird-js migrate [--yes] # Executes pending migrations with auto-detection
391
- npx bluebird-js migrate:status # Displays applied batches
392
- npx bluebird-js migrate:rollback # Reverts latest batch
393
- npx bluebird-js make:seed <name> # Database seed file creation
394
- npx bluebird-js seed # Executes database seeds
395
- npx bluebird-js db:backup [--keep 10] [--out dir] # Compressed WAL-safe database backup with retention rotation
396
- npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
397
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
398
- npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
399
- ```
400
-
401
- ## 15. Background Jobs & Queue (Queue)
402
-
403
- Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
404
-
405
- ```javascript
406
- import Queue from "@seip/bluebird-js/core/queue.js";
407
-
408
- Queue.process("sendWelcomeEmail", async (payload) => {
409
- console.log(`Sending email to ${payload.email}...`);
410
- });
411
-
412
- await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
413
- await Queue.work();
414
- ```
415
-
416
- ## 16. React JSX SSR, Auto-Routes, Client Islands & View Transitions
417
-
418
- Bluebird provides a modern, zero-build view architecture uniting database-driven server-rendered HTML with native React JSX (`.jsx`) and JavaScript (`.js`) views, declarative file-based Auto-Routes, shared layouts, Tailwind CSS v4, `<Client>` / `<Island>` components with anti-CLS skeletons, and instant View Transitions SPA navigation:
419
-
420
- - **Built-In Tailwind CSS v4 & Inter Font**:
421
- - `public/js/tailwind.js` and Google Fonts `Inter` are loaded by default in the main layout (`app/views/layouts/main/view.jsx`).
422
- - Zero build steps, zero transpilation, pure modern utilities out of the box with dark mode synchronization.
423
- - **Native Zero-Build React JSX & TSX SSR (`app/views/*.jsx`, `*.tsx`):**
424
- - Powered by `core/jsx.js` and Node 22.18+ native `module.registerHooks()`. Compiles `.jsx` and TypeScript `.tsx` modules in memory with **zero temporary files on disk** and **zero external npm dependencies** required.
425
- - Automatically strips TypeScript type annotations from `.tsx` and `.ts` components while preserving line mappings.
426
- - Supports `async` Server Components, Fragments (`<>...</>`), spread props, `style` objects, automatic XSS escaping, and mixed `html\`...\`` templates.
427
- - **`<ErrorBoundary>` Component**:
428
- - Catches subtree runtime exceptions during SSR and renders a fallback UI without failing the entire page request: `<ErrorBoundary fallback={(err) => <ErrorBox message={err.message} />}>...</ErrorBoundary>`.
429
- - **Dynamic Head Manager & Tag Hoisting (`<Head>`, `<Title>`, `<Meta>`):**
430
- - Hoist `<title>` and `<meta>` tags from nested components directly into the document `<head>`: `<Head><Title>Dashboard</Title><Meta name="robots" content="noindex" /></Head>`.
431
- - **Streaming SSR with `<Suspense>` & Smart Caching (`Render.stream()`):**
432
- - Emits chunked transfer encoding responses with immediate shell and `<Suspense fallback={<Skeleton />}>` placeholders.
433
- - Out-of-order chunks stream as async data resolves, with tiny inline scripts swapping templates seamlessly.
434
- - Respects cache TTL (`Render.cache(300)` / `export const cache = 300`): subsequent requests are served as **instant Cache HITs** without streaming overhead, while streaming cache misses automatically caches the assembled final HTML.
435
- - **Declarative Auto-Routes from Views (`ViewLoader.discoverRoutes()` / `Render.autoRoutes()`)**:
436
- - Automatically scans `app/views/pages/` (with fallback to `app/views/` if `pages/` does not exist for backwards compatibility) and mounts GET routes when `App` starts.
437
- - Keeping pages inside `app/views/pages/` allows placing `actions/`, `client/`, `components/`, `hooks/`, `partials/`, or `layouts/` inside `app/views/` without risk of them being mounted as HTTP routes.
438
- - Export route settings directly from any view file:
439
- - `export const route = "/login"` (or inferred automatically from filename; `false` disables auto-routing)
440
- - `export const cache = 300` (applies `Render.cache(300)` automatically)
441
- - `export const layout = "main"` (uses `app/views/layouts/main/view.jsx`)
442
- - `export const middlewares = [Auth.protect({ redirect: "/login" })]`
443
- - `export const seo = true` (registers route in `/sitemap.xml` and `/robots.txt`)
444
- - Disable auto-discovery if desired via `new App({ noAutoDiscoverRoutes: true })`.
445
- - **Client Components & Anti-Accordion Skeletons (`<Client>` / `<Island>`)**:
446
- - Everything renders as pure SSR by default (0 KB client JS).
447
- - For client-side interactivity (`useEffect`, `useState`, or native DOM logic), use `<Client>` or `<Island>` from `@seip/bluebird-js/core/jsx.js`.
448
- - Pass `skeleton={...}`, `minHeight`, and `minWidth` to lock container dimensions before hydration and prevent layout shift ("accordion" effect), plus `persistent={true}` to preserve state across View Transitions.
449
- - Supports zero-build declarative client components with standard hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `useRef`, `html` tagged templates) via `component={LiveCounter}` (`LiveCounter.jsx`), inline functions via `client={(el, props) => { ... }}`, and full React Islands (`npx bluebird-js add react-islands`).
450
- - **Native Server Actions (`core/actions.js` & `export const actions = { ... }`)**:
451
- - Next.js-style Server Actions executed on the server with automatic CSRF verification (`_csrf` cookie + `X-CSRF-Token` header), payload byte limit guards (`maxBytes`, default 64KB), prototype-pollution & depth/key sanitization (`sanitizeActionPayload`), and optional `Validator` schema checks.
452
- - Supports direct async functions in `export const actions = { async syncCount({ body, user }) { ... } }`, standalone exports via `action()` (`export const syncCount = action(async ({ count }, ctx) => ...)`) in views or `app/views/actions/`, and passing either action name string or function reference to `useAction(syncCount)` and `Bluebird.action(syncCount, payload)`.
453
- - Triggered from the client via `await Bluebird.action("syncCount", { count: 10 })`, `useAction(syncCount)` in client components, or declarative `data-action="syncCount"` attributes on buttons/forms with automatic `disabled`, `aria-busy="true"`, and `is-pending` states.
454
- - **Native JSX `<Script>` Component (`core/jsx.js` & `core/render.js`)**:
455
- - Ergonomic client DOM scripting in views without string concatenation or escaping: `<Script data={{ userId: user.id }} onPageLoad>{({ userId }) => { ... }}</Script>`.
456
- - Runs safely on initial load and across SPA View Transitions, executing optional cleanup functions upon navigation.
457
- - **Shared Layouts (`app/views/layouts/main/view.jsx`)**:
458
- - Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, children, head, ctx, data }`.
459
- - When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
460
- - Elements with `data-bb-outlet="true"` enable layout outlet swapping so navigation between pages sharing the same layout preserves header, menus, and media playback uninterrupted.
461
- - **Comprehensive Built-In Client UI Kit (`public/js/bluebird-client.js`)**:
462
- - `toast({ title, description, type, position, duration })`
463
- - `snackbar({ message, type, duration })`
464
- - `bluebird('drawer', { id, action: 'open'|'close'|'toggle' })`
465
- - `new ResponsiveDataTable(containerId, options)`
466
- - `bluebird('command')` palette (`Ctrl+K`), `bluebird('tab')`, `bluebird('popover')`, `bluebird('carousel')`
467
- - Declarative forms via `form[data-bb-form="true"]`: submits via `fetch`, auto-injects CSRF tokens, and follows `X-Bluebird-Redirect`.
468
- - Native `document.startViewTransition()` page navigation with preserved elements via `data-persist="true"`.
469
-
470
- ```jsx
471
- // app/views/pages/dashboard.jsx
472
- import Auth from "@seip/bluebird-js/core/auth.js";
473
- import { action } from "@seip/bluebird-js/core/actions.js";
474
- import { Script } from "@seip/bluebird-js/core/jsx.js";
475
- import Header from "../components/Header.jsx";
476
- import LiveCounter from "../components/LiveCounter.jsx";
477
-
478
- export const route = "/dashboard";
479
- export const layout = "main";
480
- export const middlewares = [Auth.protect({ redirect: "/login" })];
481
- export const seo = false;
482
- export const head = (data) => ({ title: `Dashboard — ${data.user?.name}` });
483
-
484
- export const actions = {
485
- // Direct plain async function with automatic CSRF, 64KB maxBytes & prototype sanitization
486
- async syncCount({ body, user }) {
487
- return { syncedCount: Number(body.count), updatedBy: user?.email };
488
- },
489
- };
490
-
491
- export default async function DashboardView({ user, syncedCount = 7 }) {
492
- return (
493
- <>
494
- <Header title="Dashboard" user={user} count={syncedCount} />
495
- {/* Direct JSX invocation with automatic anti-CLS skeleton */}
496
- <LiveCounter initial={syncedCount} />
497
-
498
- {/* Native JSX Script component */}
499
- <Script data={{ initialCount: syncedCount }} onPageLoad>
500
- {({ initialCount }) => {
501
- console.log("Mounted dashboard with count:", initialCount);
502
- return () => console.log("Cleanup on page transition");
503
- }}
504
- </Script>
505
- </>
506
- );
507
- }
508
- ```
509
-
510
- ```jsx
511
- // app/views/components/LiveCounter.jsx
512
- import { useState, useAction, client } from "@seip/bluebird-js/core/jsx.js";
513
-
514
- export function LiveCounter({ initial = 7, label = "Client Counter" }) {
515
- const [count, setCount] = useState(Number(initial) || 0);
516
- const [sync, isPending] = useAction("syncCount", {
517
- onSuccess(res) {
518
- window.toast?.({ title: "Synced", description: res.data?.message || "OK" });
519
- },
520
- });
521
-
522
- return (
523
- <div className="h-14 rounded-xl border border-slate-800 bg-slate-950/90 px-4 flex items-center justify-between">
524
- <span className="text-xs text-slate-300">
525
- {label}: <strong className="text-sky-400 font-mono">{count}</strong>
526
- </span>
527
- <div className="flex items-center gap-2">
528
- <button
529
- type="button"
530
- onClick={() => setCount(count + 1)}
531
- className="px-2.5 py-1 bg-sky-500 rounded text-xs font-bold text-slate-950"
532
- >
533
- +1
534
- </button>
535
- <button
536
- type="button"
537
- onClick={() => sync({ count })}
538
- disabled={isPending}
539
- className="px-2.5 py-1 bg-emerald-500/15 border border-emerald-500/30 rounded text-xs text-emerald-300"
540
- >
541
- {isPending ? "Syncing..." : "Sync Server Action"}
542
- </button>
543
- </div>
544
- </div>
545
- );
546
- }
547
-
548
- export default client(LiveCounter, { minHeight: 56 });
549
- ```
550
-
551
- ## 17. Unified AI Client (AI & core/ai.js)
552
-
553
- Bluebird includes a native, zero-dependency unified AI client (`core/ai.js`) supporting **DeepSeek (default)**, **Google Gemini**, and **OpenAI** out of the box with zero external SDKs required. It features automated PII data masking, 0ms prompt caching, sliding window rate limiting ("Anti-Quiebra"), and structured JSON extraction with schema validation:
554
-
555
- - **DeepSeek by Default**:
556
- - Base URL `https://api.deepseek.com`, model `deepseek-flash` (served by DeepSeek-V4.1-Flash-1017; legacy names `deepseek-v4-flash`, `deepseek-chat` supported).
557
- - OpenAI-compatible format with optional thinking/reasoning mode (`thinking: { type: "enabled" }`, `reasoningEffort: "high"`).
558
- - **Google Gemini**:
559
- - REST API with `gemini-3.5-flash` (default), `gemini-3.8-flash`, `gemini-2.5-flash`, etc.
560
- - **OpenAI & Custom Endpoints**:
561
- - Compatible with `gpt-4o-mini`, `gpt-4o`, Ollama, OpenRouter, and custom endpoints via `baseURL`.
562
- - **Accurate Real Client IP Detection (`getClientIp`)**:
563
- - Extracts real visitor IP behind Cloudflare (`cf-connecting-ip`, `true-client-ip`), Nginx (`x-real-ip`), proxy chains (`x-forwarded-for` first IP), and normalizes IPv6 mappings (`::ffff:`).
564
- - **Reversible Sensitive Data Masking (PII)**:
565
- - Personal values (`sensitiveKeys`) in context data and prompt text are replaced with anonymous deterministic tokens (`[name_01]`, `[email_01]`, `[dni_01]`) before leaving the server.
566
- - Responses (`result.text`) are returned fully restored with original user values.
567
- - **0ms Prompt Cache Synergy**:
568
- - Cache hashes are computed against the *anonymized* prompt. Two different users asking the same query template trigger an immediate 0ms, $0 latency/cost Cache Hit with their unique personal values restored cleanly.
569
- - **Sliding Window Rate Limiting ("Anti-Quiebra")**:
570
- - Protects API budgets with minute/day limits (e.g. `{ minute: 6, day: 30 }` or `{ max: 15, windowMs: 60000 }`), returning HTTP 429 clean responses before depleting credits.
571
- - Express route protection middleware available via `ai.protect()`.
572
- - **Response Streaming & SSE (`ai.pipe` & `askStream`)**:
573
- - Stream tokens in real time directly to Express responses via `await ai.pipe(res, prompt, { sse: true })` with automatic Nginx anti-buffering (`X-Accel-Buffering: no`), or iterate manually via `for await (const chunk of ai.askStream(prompt))`.
574
-
575
- ```javascript
576
- import AI, { ai } from "@seip/bluebird-js/core/ai.js";
577
-
578
- const supportAi = new AI({
579
- provider: "deepseek", // "deepseek" (default) | "gemini" | "openai" | "custom"
580
- model: "deepseek-flash", // default model
581
- rateLimit: { minute: 6, day: 30 }, // Sliding window protection
582
- cacheTtl: 3600, // Cache responses for 1 hour
583
- });
584
-
585
- routerApi.post("/support/reply", supportAi.protect(), async (req, res) => {
586
- const userData = {
587
- name: "Maria Garcia",
588
- email: "maria@example.com",
589
- dni: "45123987",
590
- issue: "Need help updating billing details",
591
- };
592
-
593
- const result = await supportAi.ask("Draft a courteous support reply for this user:", {
594
- data: userData,
595
- sensitiveKeys: ["name", "email", "dni"], // Masked to [name_01], [email_01], [dni_01] before sending!
596
- request: req, // Automatic IP rate limiting
597
- json: true,
598
- });
599
-
600
- // result.text is returned fully restored with 'Maria Garcia' and 'maria@example.com'!
601
- res.ok(result);
602
- });
603
-
604
- // Stream real-time Server-Sent Events (SSE) directly to Express client response
605
- routerApi.post("/support/stream", async (req, res) => {
606
- await supportAi.pipe(res, req.body.message, { sse: true, request: req });
607
- });
608
-
609
- // Or iterate chunks manually via async generator
610
- for await (const chunk of supportAi.askStream("Explain quantum computing in simple terms")) {
611
- process.stdout.write(chunk.text);
612
- }
613
- ```
614
-
615
- ## 18. AI Development Guidelines
616
-
617
- 1. **Assets & Views**: Static assets in `public/`. HTML views, layouts (`app/views/layouts/`), and partials (`app/views/partials/`) in `app/views/` served via `Render.view()`, `Render.send()`, or `Render.partial()`.
618
- 2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
619
- 3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
620
- 4. **All documentation in English**.
1
+ # Bluebird.js Framework - AI Agent Guide
2
+
3
+ This document serves as the primary manual for any AI Agent interacting with the codebase. It details the architecture of Bluebird.js (`@seip/bluebird-js`), its internal modules, and how features should be written or modified.
4
+
5
+ ## 1. Core Architecture
6
+
7
+ Bluebird.js is a performance-first web and API framework built on **Express** (Node.js 22.18+). Public landing pages and SEO routes are server-rendered with **HTML `{{ }}` templates** (`app/resources/html/`), while interactive dashboards and applications run as client-rendered **React 19 + React Router** SPAs (`app/resources/`) mounted with **`router.spa()`**, bundled with **Vite 7**, and styled with **Tailwind CSS v4** (light and dark modes). It also provides JWT auth with role enforcement, multi-level caching, BaseModel, schema validation, database access, and queue processing out of the box.
8
+
9
+ - **Entrypoint (`index.js`)**: Located at the project root. Initializes the server using `App` from `core/app.js` and registers the routes.
10
+ - **Application (`app/`)**: Application code — `app/resources/` holds everything client-side: the React SPA (`index.html` shell, `spa.js` config, `main.jsx`, `routes.jsx`, `layouts/`, `pages/`), `styles.css` (Tailwind v4 entry), and `html/` (HTML `{{ }}` SSR views, `html/layouts/`, `html/partials/`). Server code lives in `app/routes/` (API, Auth, Web routes), `app/models/` (BaseModels), and `app/jobs/` (background workers).
11
+ - **Public assets (`public/`)**: Static files (`images/`, `js/bluebird.js` vanilla UI helpers). `public/build/` is generated by `npx bluebird-js build` (hashed client bundle and CSS manifest). Served directly by Nginx or Express fallback.
12
+ - **React & Vite runtime (`core/vite.js`, `core/vite-plugin.js`, `core/spa.js`, `core/react/client/`)**: `ViteBridge` manages Vite middleware in dev and `public/build/.vite/manifest.json` in production; `core/spa.js` powers `router.spa()` with per-URL SEO metadata, JSON-LD, and full-width `#root` skeletons; `core/react/client/` exports React UI components, `api`, `AuthProvider`, `RequireAuth`, `GuestOnly`, and `useTheme` as `@seip/bluebird-js/react`.
13
+ - **Core (`core/`)**: The framework core. Contains `Router`, `Render`, `Validator`, `Auth`, `Cache`, `Redis`, `Database`, `Model`, `Csrf`, `Hash`, `ViteBridge`, etc. **DO NOT MODIFY** the core unless explicitly requested.
14
+
15
+ ## 2. Modern JavaScript Standard (ESM)
16
+
17
+ Bluebird.js standardizes on modern JavaScript (Node.js 22.18+ ESM) with JSDoc types. Server code (routes, models) runs directly in Node; React SPA modules and Tailwind CSS are compiled by Vite:
18
+
19
+ - **Development (`npm run dev` → `bluebird-js dev`)**: Express + Vite middleware on the same port (HMR / React Fast Refresh, on-the-fly Tailwind CSS v4, also injected into HTML `{{ }}` pages). The server restarts when any server file under `app/` changes (routes, models, jobs, `app/lib/`, `app/database.js`...), plus `index.js`, `.env`, and `app/resources/spa.js` (add more with `--watch dir`); client files in `app/resources/` are hot-reloaded by Vite instead; writes to `logs/`, `node_modules/`, or build output never restart it. Do not use `node --watch-path`: on some platforms it reports changes outside the watched paths (Vite's `node_modules/.vite-temp`, `logs/`) and restarts endlessly.
20
+ - **Build (`npx bluebird-js build`)**: Client SPA & CSS bundle in `public/build/` with `.vite/manifest.json`.
21
+ - **Static export (`npx bluebird-js export`)**: The React SPA as 100% static HTML/JS/CSS (`dist/client/`) for Electron, Capacitor, or static hosting.
22
+ - **Production Entrypoint (`index.js`)**: Run with `node --env-file=.env index.js` (`npm start`) or via PM2 cluster.
23
+ - **Initialization**: `npx bluebird-js` scaffolds a new project directly with `index.js` at the root, from a template: `--blank` (default: HTML page on `/` + one-page React SPA on `/app/*`), `--auth` (login, register, forgot/reset password, dashboard, profile), `--blog` (HTML blog with RSS and sitemap + React admin), `--api` (headless REST API with JWT and a CRUD example), or `--demo` (framework showcase). Templates live in `templates/` (`_base` and `_auth` are shared layers) and never overwrite existing files. Non-interactive: `npx bluebird-js --auth --yes --title "My App"`.
24
+ - **IDE Intellisense**: Powered by `core/index.d.ts` and `jsconfig.json`.
25
+
26
+ ```javascript
27
+ import App from "@seip/bluebird-js/core/app.js";
28
+ import routerApi from "./app/routes/api.js";
29
+ import routerAuth from "./app/routes/auth.js";
30
+ import routerWeb from "./app/routes/web.js";
31
+
32
+ const app = new App({
33
+ routes: [routerWeb, routerAuth, routerApi],
34
+ port: process.env.PORT || 3000,
35
+ });
36
+
37
+ app.run();
38
+ ```
39
+
40
+ ## 3. Routing (Router & `router.spa()`)
41
+
42
+ Do not use Express' native router directly. Always use Bluebird's `Router` wrapper.
43
+
44
+ ```javascript
45
+ import Router from "@seip/bluebird-js/core/router.js";
46
+
47
+ const routerApi = new Router("/api");
48
+
49
+ routerApi.get("/users", (req, res) => {
50
+ res.json({ users: [] });
51
+ });
52
+
53
+ export default routerApi;
54
+ ```
55
+
56
+ When created with `{ seo: true }`, static GET routes and static indexable `router.spa()` entries are tracked for `/sitemap.xml` and `/robots.txt`.
57
+
58
+ Mount a React Router SPA under any prefix with `router.spa(path, options)`:
59
+
60
+ ```javascript
61
+ routerWeb.spa("/app", {
62
+ lang: "en",
63
+ titleTemplate: "%s — My App",
64
+ skeleton: "app",
65
+ meta: {
66
+ "*": { title: "Workspace", robots: "noindex, nofollow", skeleton: "app" },
67
+ "login": { title: "Sign In", description: "Access your account", robots: "index, follow", skeleton: "auth" },
68
+ "/app/register": { title: "Create Account", robots: "index, follow", skeleton: "auth" },
69
+ },
70
+ });
71
+ ```
72
+
73
+ ## 4. Request Validation (Validator)
74
+
75
+ Incoming request data is validated using `core/validate.js`, which automatically returns HTTP 400 JSON responses on error. The validator inspects request payloads without destructively mutating raw data.
76
+
77
+ ```javascript
78
+ import Validator from "@seip/bluebird-js/core/validate.js";
79
+
80
+ const userSchema = {
81
+ email: { required: true, email: true },
82
+ password: { required: true, min: 8 },
83
+ bio: { required: false },
84
+ };
85
+
86
+ const validateUser = new Validator(userSchema, "en");
87
+
88
+ routerApi.post("/users", validateUser.middleware(), (req, res) => {
89
+ res.json({ success: true });
90
+ });
91
+ ```
92
+
93
+ ## 5. Lightweight BaseModel (Model)
94
+
95
+ > **Important Architecture Note:**
96
+ > Bluebird's `BaseModel` (`core/model.js`) is designed as a lightweight, built-in static facade for high performance, simple queries, soft deletes, and migrations.
97
+ > **For complex multi-tier enterprise ORM mapping, Prisma is recommended.**
98
+
99
+ ### Defining a Model
100
+
101
+ Create models inside `app/models/`:
102
+
103
+ ```javascript
104
+ import Model from "@seip/bluebird-js/core/model.js";
105
+
106
+ export default class User extends Model {
107
+ static table = "users";
108
+ static primaryKey = "id";
109
+ static timestamps = true;
110
+ static softDelete = true;
111
+
112
+ static schema = {
113
+ id: { type: "int", primary: true, auto: true },
114
+ name: { type: "string", length: 150, required: true },
115
+ email: { type: "string", length: 150, unique: true, required: true, email: true },
116
+ password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
117
+ role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
118
+ };
119
+ }
120
+ ```
121
+
122
+ ### CRUD Shortcuts & Query Facades
123
+
124
+ Every Model exposes direct shortcuts to database queries, transactions, and mutations:
125
+
126
+ ```javascript
127
+ const total = await User.query("SELECT COUNT(*) as count FROM users", [], "return_row");
128
+ await User.transaction(async (tx) => {
129
+ await tx.query("UPDATE users SET role = ? WHERE id = ?", ["admin", 1]);
130
+ });
131
+
132
+ const userId = await User.create({ name: "Alice", email: "alice@example.com", password: "secretPassword" });
133
+
134
+ const user = await User.find(1, { cache: 60 });
135
+ const userWithPosts = await User.find(1, { oneMany: Post });
136
+ const postWithAuthor = await Post.find(10, { belongsTo: User });
137
+
138
+ const page = await User.paginate({ where: { role: "user" }, page: 1, limit: 10 });
139
+ await User.update(userId, { name: "Alice Smith" });
140
+
141
+ const totalUsers = await User.count({ role: "user" });
142
+ const exists = await User.exists({ email: "alice@example.com" });
143
+
144
+ const matching = await User.all({
145
+ where: {
146
+ id: [1, 2, 3],
147
+ role: { $ne: "banned" },
148
+ views: { $gt: 100 },
149
+ },
150
+ });
151
+
152
+ const userRecord = await User.firstOrCreate({ email: "john@example.com" }, { name: "John Doe" });
153
+ const updatedRecord = await User.updateOrCreate({ email: "john@example.com" }, { name: "Johnathan" });
154
+
155
+ await User.delete(userId);
156
+ await User.delete(userId, { force: true });
157
+ await User.delete(userId, { cascade: [Post] });
158
+ await User.restore(userId);
159
+ ```
160
+
161
+ ## 6. CSRF Protection (Csrf)
162
+
163
+ Bluebird provides built-in HMAC-signed double-submit CSRF protection (`core/csrf.js`):
164
+
165
+ ```javascript
166
+ import Csrf from "@seip/bluebird-js/core/csrf.js";
167
+
168
+ routerWeb.use(Csrf.middleware());
169
+
170
+ const token = Csrf.ensure(req, res); // Valid token for this request (issues the `_csrf` cookie when missing)
171
+ Csrf.verifyRequest(req); // Timing-safe cookie ↔ header/body check
172
+ Csrf.rotate(res); // Fresh token (done automatically by Auth.login / Auth.logout)
173
+ ```
174
+
175
+ - Tokens are accepted from the `X-CSRF-Token` header or the `_csrf` body field. **Query-string tokens are rejected.**
176
+ - The signing secret is `CSRF_SECRET` or `JWT_SECRET`. Without either, a random per-process secret is used (tokens do not survive restarts or validate across PM2 workers) and a warning is printed in production.
177
+ - Cached pages never leak tokens between visitors: the token is replaced by a placeholder before caching and restored per request.
178
+
179
+ ## 7. Authentication & Password Hashing (Auth & Hash)
180
+
181
+ ### Password Hashing (Hash)
182
+
183
+ Native password hashing using `node:crypto.scrypt` with random salt and timing-safe comparison (zero external npm dependencies required).
184
+
185
+ ```javascript
186
+ import Hash from "@seip/bluebird-js/core/hash.js";
187
+
188
+ const hash = await Hash.make("mySecretPassword");
189
+ const isValid = await Hash.verify("mySecretPassword", hash);
190
+ ```
191
+
192
+ ### JWT Handling (Auth)
193
+
194
+ Native JWT handling with AES-256-GCM encryption and HMAC-SHA256 signature verification using `node:crypto`, plus optional role enforcement and guest-friendly session inspection:
195
+
196
+ ```javascript
197
+ import Auth from "@seip/bluebird-js/core/auth.js";
198
+
199
+ router.get("/profile", Auth.protect(), (req, res) => {
200
+ res.json({ user: req.user });
201
+ });
202
+
203
+ router.get("/admin/metrics", Auth.protect({ roles: ["admin", "editor"] }), (req, res) => {
204
+ res.ok({ metrics: true });
205
+ });
206
+
207
+ router.get("/session", Auth.optional(), (req, res) => {
208
+ res.ok({ user: req.user || null });
209
+ });
210
+
211
+ router.post("/login", async (req, res) => {
212
+ const user = { id: 1, name: "John", role: "user" };
213
+ await Auth.login(res, user);
214
+ res.ok(user, "Logged in");
215
+ });
216
+
217
+ router.post("/logout", async (req, res) => {
218
+ await Auth.logout(res);
219
+ res.ok(null, "Logged out");
220
+ });
221
+ ```
222
+
223
+ Project auth routes in `app/routes/auth.js` expose `/api/auth/me`, `/api/auth/login`, `/api/auth/logout`, and optional `/api/auth/register` via `createAuthRouter({ register: true })` (defaults to `register: false`). The auth and API routers apply `Csrf.middleware()`; bearer clients (`X-Auth-Mode: token`) receive `{ user, token }` instead of a cookie.
224
+
225
+ `Auth.configure({ resolveUser: async (payload, req) => user | null })` reloads the user on every `Auth.protect()` / `Auth.optional()` request after the token signature is checked: return the current user (fresh role) or `null` to reject the session; errors reject it too. The `auth`, `api`, and `blog` templates use it with a `session_version` column stored in the token as `sv`: password change/reset and `POST /api/auth/logout-all` increment it to revoke every existing session, `PUT /api/auth/password` returns a fresh session for the current device, and `PUT /api/auth/profile` requires `current_password` to change the email. Never trust roles from the token alone for sensitive actions.
226
+
227
+ ## 8. HTTP Response Helpers & Health Check
228
+
229
+ Bluebird decorates the Express `res` object with standardized helper methods:
230
+
231
+ ```javascript
232
+ res.ok(data, "Success message");
233
+ res.created(data, "Created successfully");
234
+ res.paginate(items, pagination, "Fetched");
235
+
236
+ res.badRequest("Invalid input", errors);
237
+ res.unauthorized("Authentication required");
238
+ res.forbidden("Access denied");
239
+ res.notFound("Resource not found");
240
+ res.serverError("Internal failure", err);
241
+ ```
242
+
243
+ Every Bluebird application provides a native `/api/health` endpoint returning uptime, timestamp, environment, and memory consumption.
244
+
245
+ Unknown routes get a 404: JSON (`{ message: "Not Found" }`) under `/api` or for JSON clients, and for browser requests the `app/resources/html/notFound.html` view (receives `{{ path }}`) rendered inside the `main` layout, falling back to a built-in page when the view does not exist. Unknown routes inside a `router.spa()` mount are handled by the React `NotFound` page (`{ path: "*" }` in `routes.jsx`). Disable it with `new App({ notFound: false })`.
246
+
247
+ ## 9. Performance Caching (Cache & Redis)
248
+
249
+ Caching defaults to fast in-memory LRU storage, ideal for desktop applications and single or dual PM2 instances. Filesystem caching (`driver: "file"`) is available as persistent local fallback, and Redis (`driver: "redis"`) is isolated in `core/redis.js` on-demand for high-traffic environments.
250
+
251
+ ```javascript
252
+ import Cache from "@seip/bluebird-js/core/cache.js";
253
+
254
+ router.get("/stats", Cache.middleware(60), (req, res) => {
255
+ res.ok({ usersCount: 150 });
256
+ });
257
+
258
+ await Cache.set("custom_key", { data: "value" }, 120, { driver: "memory" });
259
+ const cachedData = await Cache.get("custom_key", { driver: "memory" });
260
+
261
+ const stats = await Cache.deduplicate("stats-key", async () => {
262
+ return await calculateHeavyStats();
263
+ });
264
+
265
+ await Cache.delete("custom_key");
266
+ await Cache.clear();
267
+ ```
268
+
269
+ ### Render Cache & Query Parameters
270
+
271
+ HTML caches (`Render.cache(ttl)`, `Render.html(..., { cache: 300, cacheQuery: [...] })`, and `router.spa(..., { cache: 300 })`) key entries by **path only**. Requests carrying query parameters bypass the cache unless the parameter is allowlisted, preventing cache flooding with `?random=...` variants:
272
+
273
+ ```javascript
274
+ routerWeb.get("/posts", (req, res) =>
275
+ Render.html(res, "posts", { posts }, { layout: "main", cache: 300, cacheQuery: ["page", "sort"] })
276
+ );
277
+
278
+ router.get("/posts", Render.cache(300, { query: ["page"] }), handler);
279
+ ```
280
+
281
+ Authenticated requests are never shared-cached. Cache keys include the full path (`baseUrl` + `path`) and the request language (`#lang=es` when not `en`). `req.lang` comes from `?lang=`, the body, or the `lang` cookie and only accepts BCP 47 style tags (`es`, `pt-BR`), falling back to `en`. Invalidate with `await Render.invalidate("/posts")`.
282
+
283
+ ## 10. Database Module (database.js)
284
+
285
+ Bluebird provides a unified wrapper class (`core/database.js`) supporting **SQLite (native `node:sqlite` in Node 22.18+ with `better-sqlite3` fallback)**, **MySQL (`mysql2/promise`)**, and **PostgreSQL (`pg`)**:
286
+
287
+ - **Native SQLite by Default:** No native C++ compilation or build tools required.
288
+ - **SQLite Concurrency & WAL:** Automatically configures WAL mode, busy timeout, and memory-mapped I/O.
289
+ - **Prepared Statement Caching:** SQLite caches prepared statement ASTs automatically.
290
+ - **Query Caching:** Supports `{ cache: 60 }` across memory, file, and redis backends.
291
+
292
+ ```javascript
293
+ import { Database, DB_TYPE } from "@seip/bluebird-js/core/database.js";
294
+
295
+ const connection = new Database(20);
296
+
297
+ const user = await connection.query("SELECT * FROM users WHERE id = ?", [1], "return_row");
298
+ const stats = await connection.query("SELECT COUNT(*) as cnt FROM logs", [], { cache: 60 });
299
+
300
+ await connection.transaction(async (tx) => {
301
+ const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
302
+ await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
303
+ });
304
+
305
+ // Atomic, WAL-safe compressed database backup with retention rotation
306
+ const backup = await Database.backup({ out: "database/backups", keep: 10, compress: true });
307
+
308
+ // Integrity-verified restore with pre-restore safety snapshot
309
+ await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.gz", {
310
+ safetyBackup: true,
311
+ verify: true,
312
+ });
313
+ ```
314
+
315
+ Backup rotation orders files by the timestamp in their name (equal `mtime` values on Windows/NTFS never drop the newest backup), never deletes the backup just created, and suffixes `-1`, `-2` on same-millisecond collisions.
316
+
317
+ ## 11. On-Demand Modules & CLI Add
318
+
319
+ To keep dependencies lightweight and minimal, optional modules load dynamically on-demand:
320
+
321
+ ```bash
322
+ npx bluebird-js add upload # Installs multer for file uploads
323
+ npx bluebird-js add ws # Installs ws for WebSockets
324
+ npx bluebird-js add redis # Installs redis for distributed caching
325
+ npx bluebird-js add sqlite # Installs better-sqlite3 (fallback for older environments)
326
+ npx bluebird-js add mysql # Installs mysql2
327
+ npx bluebird-js add postgres # Installs pg
328
+ npx bluebird-js add bcrypt # Installs bcrypt
329
+ npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
330
+ npx bluebird-js add helmet # Installs helmet
331
+ npx bluebird-js add ejs # Installs ejs
332
+ ```
333
+
334
+ ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
335
+
336
+ Bluebird includes built-in security headers enabled by default (`X-Content-Type-Options: nosniff`, `X-XSS-Protection: 0`, `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy: strict-origin-when-cross-origin`, `Permissions-Policy`).
337
+
338
+ ### Content-Security-Policy with Nonces
339
+
340
+ Use `{nonce}` in the policy to get a random per-request nonce. It is exposed as `res.locals.cspNonce` and added automatically to every inline `<script>` and `<style>` tag of the documents Bluebird renders (HTML `{{ }}` views, `router.spa()` skeleton styles/scripts, and cached pages).
341
+
342
+ ```javascript
343
+ const app = new App({
344
+ routes: [routerWeb, routerApi],
345
+ security: { csp: "default-src 'self'; script-src 'self' 'nonce-{nonce}'" },
346
+ });
347
+ ```
348
+
349
+ ### CORS
350
+
351
+ CORS is secure by default: `origin: "*"` never reflects the request origin and never sends `Access-Control-Allow-Credentials`. Credentialed cross-origin requests require an explicit allowlist:
352
+
353
+ ```javascript
354
+ new App({ cors: { origin: ["https://app.example.com"], credentials: true } });
355
+ new App({ cors: { origin: (origin) => origin.endsWith(".example.com"), credentials: true } });
356
+ new App({ cors: false }); // disable CORS headers entirely
357
+ ```
358
+
359
+ ### Trusted Proxies & Client IP
360
+
361
+ `req.ip` (used by rate limits and logs) honors Express `trust proxy`. The default `trustProxy: "loopback, linklocal, uniquelocal"` trusts only a reverse proxy on the same host or a private network (Nginx from `npx bluebird-js nginx:conf`, Docker), so clients cannot spoof `X-Forwarded-For`. Behind a CDN pass its hop count or address list (`new App({ trustProxy: 2 })`); `true` trusts every hop and is unsafe when the app is reachable directly.
362
+
363
+ ### JWT Secret
364
+
365
+ Set `JWT_SECRET` (32+ characters, generated by the scaffold). In production a missing or weak secret is never replaced by a known value: Bluebird uses a random per-process secret and logs an error, so sessions end on restart until you set it.
366
+
367
+ ### Native Rate Limiting (`core/ratelimit.js`)
368
+
369
+ Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers). Every limiter keeps its own buckets (`prefix`), so a global and a per-route limiter never double count:
370
+
371
+ ```javascript
372
+ import App from "@seip/bluebird-js/core/app.js";
373
+
374
+ const app = new App({
375
+ routes: [routerWeb, routerApi],
376
+ rateLimit: { max: 120, windowMs: 60000 },
377
+ });
378
+
379
+ routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req, res) => {
380
+ res.ok({ authenticated: true });
381
+ });
382
+ ```
383
+
384
+ ### Automatic SEO Sitemap & Robots (`core/seo.js`)
385
+
386
+ When a `Router` is created with `{ seo: true }`, all static `GET` routes are automatically registered and exposed at `/sitemap.xml` and `/robots.txt` by `App`. Dynamic pages (e.g. blog posts) are added with `Seo.registerRoute("/", "/blog/my-post")` and removed with `Seo.unregisterRoute("/blog/my-post")`.
387
+
388
+ ### Helmet Integration
389
+
390
+ Helmet can be applied per router when installed (`npx bluebird-js add helmet`):
391
+
392
+ ```javascript
393
+ import App from "@seip/bluebird-js/core/app.js";
394
+
395
+ const apiRouter = new Router("/api");
396
+ apiRouter.use(App.helmet());
397
+ ```
398
+
399
+ ## 13. Production Deployment & Electron Desktop Mode
400
+
401
+ ### PM2 & Nginx Reverse Proxy
402
+
403
+ Production deployments run directly via `npm start` or PM2 cluster mode:
404
+
405
+ ```bash
406
+ npx bluebird-js make:ecosystem # Generates ecosystem.config.cjs
407
+ npx bluebird-js make:ecosystem --start # Generates and starts immediately in PM2
408
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx config with upstream keepalive & static try_files
409
+ ```
410
+
411
+ For complete deployment details including Nginx reverse proxy configuration and optional standalone Docker snippet, consult [production.md](production.md).
412
+
413
+ ### Electron & Desktop Mode (`desktop: true`)
414
+
415
+ Two ways to ship desktop/mobile apps from the same React code in `app/resources/`:
416
+
417
+ 1. **Embedded server** (below): Electron runs the full Bluebird server locally (`app.runDesktop()`), including SQLite, HTML views, and the SPA.
418
+ 2. **Static client** (`npx bluebird-js export`, section 16): Electron `loadFile()` or Capacitor loads a static HTML/JS/CSS build that calls a remote Bluebird `/api/` with bearer tokens.
419
+
420
+ Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
421
+
422
+ - **Base Directory Resolution (`appPath`)**: Accepts `appPath: electronApp.getAppPath()` (or `Config.setAppDir()`) to ensure views (`app/resources/html/`) and static assets (`public/`) resolve accurately regardless of shortcut launch locations (`process.cwd()`).
423
+ - **Writable User Data (`userDataPath`)**: Automatically routes SQLite database files, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`electronApp.getPath("userData")`), copying bundled initial SQLite template databases from `appPath`, `process.resourcesPath`, or `.asar.unpacked` on first launch.
424
+ - **Dynamic Port & LAN / QR Access**:
425
+ - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
426
+ - When `{ allowLan: true }` is enabled, binds to `0.0.0.0` and returns `{ server, port, url, lanUrl, lanIp }` ready for mobile QR code access on local WiFi.
427
+ - **Uploads & Static Serving**:
428
+ - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
429
+ - **Clean Shutdown & WAL Checkpoint**:
430
+ - Invoking `await app.close()` (e.g. in Electron `app.on("before-quit")`) automatically checkpoints SQLite WAL (`PRAGMA wal_checkpoint(TRUNCATE)`), closes open database handles via `Database.closeAll()`, and frees Windows file locks cleanly.
431
+ - **Packaging with electron-builder**:
432
+ - Recommended `electron-builder` configuration in `package.json`:
433
+ ```json
434
+ "build": {
435
+ "asar": true,
436
+ "asarUnpack": ["app/resources/**/*", "database/**/*"]
437
+ }
438
+ ```
439
+ - Run `npx bluebird-js build` before packaging: desktop mode serves the compiled SPA bundle and Tailwind CSS from `public/build/` (the generated `desktop:*` scripts already do it).
440
+
441
+ ```javascript
442
+ import App from "@seip/bluebird-js/core/app.js";
443
+ import { app as electronApp, BrowserWindow } from "electron";
444
+ import routerApi from "./app/routes/api.js";
445
+ import routerAuth from "./app/routes/auth.js";
446
+ import routerWeb from "./app/routes/web.js";
447
+
448
+ const app = new App({
449
+ desktop: true,
450
+ appPath: electronApp.getAppPath(),
451
+ userDataPath: electronApp.getPath("userData"),
452
+ routes: [routerWeb, routerAuth, routerApi],
453
+ });
454
+
455
+ electronApp.whenReady().then(async () => {
456
+ const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
457
+ const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
458
+ mainWindow.loadURL(url);
459
+
460
+ electronApp.on("before-quit", async () => {
461
+ await app.close();
462
+ });
463
+ });
464
+ ```
465
+
466
+ ## 14. Developer Tooling CLI
467
+
468
+ ```bash
469
+ npx bluebird-js [--blank|--auth|--blog|--api|--demo] # Scaffolds a project from a template (default: blank)
470
+ npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
471
+ npx bluebird-js make:model <Name> # BaseModel scaffolding
472
+ npx bluebird-js make:route <name> # REST route scaffolding
473
+ npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
474
+ npx bluebird-js build # Vite build: client SPA + Tailwind CSS in public/build/
475
+ npx bluebird-js export [--api url] [--out dir] # Static React export (Electron, Capacitor, static hosts)
476
+ npx bluebird-js make:view <name> [--partial|--layout] # HTML {{ }} template scaffolding in app/resources/html/
477
+ npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
478
+ npx bluebird-js make:migration --model <Model> # Auto DDL migration for specific Model schema
479
+ npx bluebird-js migrate [--yes] # Executes pending migrations with auto-detection
480
+ npx bluebird-js migrate:status # Displays applied batches
481
+ npx bluebird-js migrate:rollback # Reverts latest batch
482
+ npx bluebird-js make:seed <name> # Database seed file creation
483
+ npx bluebird-js seed # Executes database seeds
484
+ npx bluebird-js db:backup [--keep 10] [--out dir] # Compressed WAL-safe database backup with retention rotation
485
+ npx bluebird-js dev [entry] [--watch dir] # Dev server (Vite HMR) restarting only on server file changes
486
+ npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
487
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
488
+ npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
489
+ ```
490
+
491
+ ## 15. Background Jobs & Queue (Queue)
492
+
493
+ Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
494
+
495
+ ```javascript
496
+ import Queue from "@seip/bluebird-js/core/queue.js";
497
+
498
+ Queue.process("sendWelcomeEmail", async (payload) => {
499
+ console.log(`Sending email to ${payload.email}...`);
500
+ });
501
+
502
+ await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
503
+ await Queue.work();
504
+ ```
505
+
506
+ ## 16. HTML `{{ }}` SSR Rendering & React Router SPA (`router.spa()`)
507
+
508
+ Bluebird cleanly separates **SEO server-rendered HTML** from **client-side React applications**:
509
+
510
+ 1. **HTML `{{ }}` SSR (`app/resources/html/`)**: Express routes call `Render.html(res, "view", data, { layout, cache })`. Ideal for landing pages, storefronts, marketing pages, and emails.
511
+ 2. **React Router SPA (`router.spa()`)**: Serves the React shell `app/resources/index.html` (built-in default when missing) with per-URL SEO tags (`title`, `description`, `keywords`, `canonical`, Open Graph, `robots`, `jsonld`), custom scripts/styles, and a full-width inline skeleton inside `<div id="root">`. React mounts on the client with zero server state embedded, so the same code is exported unchanged with `npx bluebird-js export`.
512
+
513
+ Everything client-side lives in `app/resources/`. The two HTML entry points are intentionally separate files:
514
+
515
+ - `app/resources/index.html`: React SPA shell (`router.spa()` and `npx bluebird-js export`).
516
+ - `app/resources/html/layouts/main.html`: HTML `{{ }}` SSR layout (`Render.html(..., { layout: "main" })`).
517
+
518
+ ```
519
+ app/
520
+ ├── resources/
521
+ │ ├── index.html (React SPA shell: {{{ head }}}, {{{ skeleton }}}, {{{ scripts }}})
522
+ │ ├── spa.js (SPA config: mount, title, meta tree; used by router.spa() and export)
523
+ │ ├── styles.css (Tailwind v4 entry shared by HTML views and React)
524
+ │ ├── main.jsx (createRoot + AuthProvider + RouterProvider, imports ./styles.css)
525
+ │ ├── routes.jsx (createRouter + lazy routes)
526
+ │ ├── layouts/AppLayout.jsx (React layouts)
527
+ │ ├── pages/ (Home.jsx, Login.jsx, Register.jsx, Dashboard.jsx, NotFound.jsx)
528
+ │ └── html/
529
+ │ ├── layouts/main.html (HTML SSR layout with {{{ body }}})
530
+ │ ├── partials/ ({{> partialName }})
531
+ │ ├── home.html (HTML {{ }} SSR page)
532
+ │ ├── terms.html
533
+ │ └── notFound.html (404 page for unknown non-/api routes)
534
+ ├── routes/ (web.js, auth.js, api.js)
535
+ └── models/ (user.js)
536
+ ```
537
+
538
+ ### HTML Template Syntax (`core/render.js`)
539
+
540
+ | Syntax | Behavior |
541
+ |---|---|
542
+ | `{{ var }}` / `{{ user.name }}` | Escaped HTML interpolation (`SafeHtml` from `html\`...\`` inserts unescaped) |
543
+ | `{{{ rawHtml }}}` | Raw unescaped interpolation |
544
+ | `{{#if cond}} … {{else}} … {{/if}}` | Conditionals (also `{{if cond}}`, `!cond`, `===`, `!==`) |
545
+ | `{{#each items}} … {{else}} … {{/each}}` | Loops (supports `this`, `@index`, `@number`, `@first`, `@last`, `../parent`) |
546
+ | `{{> header }}` | Includes `app/resources/html/partials/header.html` |
547
+ | `{{ vite "app/resources/styles.css" }}` | Emits Vite dev link or hashed production manifest tags |
548
+ | `{{ lang }}`, `{{ csrf }}`, `{{{ csrfField }}}` | Automatically injected request context |
549
+ | `\{{ literal }}` | Backslash escape: prints `{{ literal }}` as text |
550
+
551
+ ```javascript
552
+ routerWeb.get("/", (req, res) =>
553
+ Render.html(
554
+ res,
555
+ "home",
556
+ {
557
+ title: "Storefront",
558
+ clientsHtml: clients.map((c) => `<span>${escapeHtml(c.name)}</span>`).join(""),
559
+ },
560
+ { layout: "main", cache: 300, cacheQuery: ["page"] }
561
+ )
562
+ );
563
+ ```
564
+
565
+ ### `router.spa()` SEO Meta Tree & Skeleton
566
+
567
+ The SPA configuration lives in `app/resources/spa.js` so the web server and the static export share it:
568
+
569
+ ```javascript
570
+ // app/resources/spa.js
571
+ export default {
572
+ mount: "/app",
573
+ lang: "en",
574
+ titleTemplate: "%s — My App",
575
+ head: [{ tag: "link", rel: "icon", href: "/images/favicon.ico" }],
576
+ skeleton: "app",
577
+ meta: {
578
+ "*": { title: "Workspace", robots: "noindex, nofollow", skeleton: "app" },
579
+ "/": { title: "Home", description: "App workspace", robots: "index, follow", skeleton: "page" },
580
+ "login": { title: "Sign In", keywords: "login, auth", skeleton: "auth", jsonld: { "@type": "WebPage" } },
581
+ "/app/register": { title: "Register", skeleton: "auth" },
582
+ "users/:id": (req, params) => ({ title: `User ${params.id}` }),
583
+ },
584
+ };
585
+
586
+ // app/routes/web.js
587
+ import spa from "../resources/spa.js";
588
+ routerWeb.spa(spa.mount, spa);
589
+ ```
590
+
591
+ - Keys inside `meta` accept both **relative** (`"login"`) and **absolute** (`"/app/login"`) forms, plus `"*"` wildcard and dynamic functions.
592
+ - `entry` defaults to `app/resources/main.jsx` (which imports `./styles.css`), `template` defaults to `app/resources/index.html` (`false` = built-in shell), and `styles` adds extra stylesheets.
593
+ - Built-in inline skeleton variants (`"app"`, `"auth"`, `"page"`, `false`, or custom HTML) fill `<div id="root" class="w-full min-h-screen">` so layout width stays locked before React mounts.
594
+ - Static non-`noindex` entries automatically register in `/sitemap.xml` when `seo: true`.
595
+
596
+ ### React Router (`createRouter`)
597
+
598
+ ```javascript
599
+ import { createRouter } from "@seip/bluebird-js/react";
600
+
601
+ export const router = createRouter(routes, { basename: "/app" });
602
+ ```
603
+
604
+ Uses `createBrowserRouter` with `basename` when served by `router.spa()`, and `createHashRouter` in static exports or under `file://` (Electron `loadFile`). Force a mode with `{ mode: "browser" | "hash" | "memory" }`.
605
+
606
+ ### Static Export (`npx bluebird-js export`) for Electron, Capacitor & Static Hosts
607
+
608
+ Builds the same React code, `index.html` shell, and `spa.js` metadata into a 100% static HTML/JS/CSS folder (no Node server inside the app):
609
+
610
+ ```bash
611
+ npx bluebird-js export --api https://api.example.com # dist/client/index.html (hash router, ./ assets)
612
+ npx bluebird-js export --out mobile/www --api https://api.example.com
613
+ npx bluebird-js export --router browser --base / --out dist/web # static host with history fallback
614
+ ```
615
+
616
+ | Option | Default | Purpose |
617
+ |---|---|---|
618
+ | `--out <dir>` | `dist/client` | Output folder (refuses `app/`, `core/`, `public/`, or the project root) |
619
+ | `--api <url>` | `EXPORT_API_URL` or `APP_URL` | Base URL prepended by `api()` to `/api/*` |
620
+ | `--router <mode>` | `hash` | `hash` (works with `file://`), `browser`, or `memory` |
621
+ | `--base <path>` | `./` (`/` for browser) | Asset base URL; root-absolute `src`/`href` in the shell are rebased |
622
+ | `--auth <mode>` | `token` | `token` = `Authorization: Bearer` stored in `localStorage`; `cookie` = same-site cookies |
623
+ | `--config <file>` | `app/resources/spa.js` | SPA config module |
624
+ | `--no-public` | | Skip copying `public/` into the output |
625
+
626
+ - **Electron (static)**: `mainWindow.loadFile("dist/client/index.html")`. **Electron (embedded server)** keeps working with `desktop: true` and `app.runDesktop()` (section 13).
627
+ - **Capacitor**: `"webDir": "dist/client"` in `capacitor.config.json`, then `npx cap sync`.
628
+ - **Auth from exports**: `AuthProvider` sends `X-Auth-Mode: token`; `/api/auth/login` and `/register` return `{ user, token }` without cookies, and `Csrf.middleware()` exempts bearer requests that carry no auth cookie. Default CORS (`origin: "*"`, no credentials) already allows these requests.
629
+ - `isExported()` / `getExportConfig()` let components hide web-only UI (e.g. links to HTML pages).
630
+
631
+ ### React Client API (`@seip/bluebird-js/react`)
632
+
633
+ | Export | Purpose |
634
+ |---|---|
635
+ | `api` (`get`, `post`, `put`, `patch`, `delete`), `ApiError`, `setApiBaseUrl`, `configureApi({ baseUrl, auth })` | Fetch helper with `X-CSRF-Token` (cookie mode) or bearer token (token mode), and `Validator` error normalization |
636
+ | `createRouter`, `isExported`, `getExportConfig`, `getAuthToken`, `setAuthToken`, `getAuthMode` | Router factory and static export helpers |
637
+ | `AuthProvider`, `useAuth`, `RequireAuth`, `GuestOnly` | Session sync with `/api/auth/me` and optional role guards (`roles={["admin"]}`) |
638
+ | `Link`, `Button`, `buttonVariants`, `Form`, `SubmitButton`, `Input`, `Textarea`, `Select`, `Card`, `Badge`, `Carousel`, `Modal`, `Drawer`, `Skeleton`, `PageSkeleton`, `ProgressBar`, `Spinner`, `Toaster`, `toast`, `ThemeToggle`, `useTheme`, `cn` | React UI kit built on the design system below (light + dark) |
639
+ | `useLocale`, `t`, `setLocale`, `getLocale`, `addMessages`, `MESSAGES` | Component UI strings in the page language (`<html lang>`): `en`, `es`, `pt`, `fr`, `de`, `it`, with base-language and English fallback |
640
+
641
+ ### Vanilla Browser Helpers (`public/js/bluebird.js`)
642
+
643
+ Includes event-delegated `[data-carousel]`, `[data-toast]`, `[data-modal]` / `[data-modal-open]`, `[data-dropdown]`, `[data-tabs]`, `[data-theme-toggle]`, `[data-copy]`, `[data-confirm]`, `[data-password-toggle]`, and `form[data-form]` (CSRF-aware fetch with inline field errors). Exposed globally as `window.Bluebird` (including `Bluebird.i18n.t / addMessages / setLocale`). Including the script twice is harmless: the second copy is ignored.
644
+
645
+ Built-in component strings (toast badges such as `Correcto` / `Cuidado` in Spanish, close buttons, carousel controls, error fallbacks) follow `<html lang>` in both the React kit and `public/js/bluebird.js`. Never hardcode those labels in components; add new keys to `core/react/client/i18n.js` and the identical `MESSAGES` object in `public/js/bluebird.js` (the regression suite checks they match).
646
+
647
+ ### Development & Production
648
+
649
+ ```bash
650
+ npm run dev # bluebird-js dev: Express + Vite on one port (HMR + Tailwind v4), restarts on server file changes
651
+ npx bluebird-js build # Builds client SPA & CSS bundle to public/build/
652
+ npm start # Production server reading public/build/.vite/manifest.json
653
+ npx bluebird-js export # Static React build (dist/client) for Electron, Capacitor, or static hosting
654
+ ```
655
+
656
+ ## 17. Unified AI Client (AI & core/ai.js)
657
+
658
+ Bluebird includes a built-in unified AI client (`core/ai.js`) supporting **DeepSeek (default)**, **Google Gemini**, and **OpenAI** out of the box with no provider SDKs required. It features automated PII data masking, 0ms prompt caching, sliding window rate limiting ("Anti-Quiebra"), and structured JSON extraction with schema validation:
659
+
660
+ - **DeepSeek by Default**:
661
+ - Base URL `https://api.deepseek.com`, model `deepseek-flash` (served by DeepSeek-V4.1-Flash-1017; legacy names `deepseek-v4-flash`, `deepseek-chat` supported).
662
+ - OpenAI-compatible format with optional thinking/reasoning mode (`thinking: { type: "enabled" }`, `reasoningEffort: "high"`).
663
+ - **Google Gemini**:
664
+ - REST API with `gemini-3.5-flash` (default), `gemini-3.8-flash`, `gemini-2.5-flash`, etc.
665
+ - **OpenAI & Custom Endpoints**:
666
+ - Compatible with `gpt-4o-mini`, `gpt-4o`, Ollama, OpenRouter, and custom endpoints via `baseURL`.
667
+ - **Accurate Real Client IP Detection (`getClientIp`)**:
668
+ - Extracts real visitor IP behind Cloudflare (`cf-connecting-ip`, `true-client-ip`), Nginx (`x-real-ip`), and proxy chains (`x-forwarded-for`), and normalizes IPv6 mappings (`::ffff:`). Proxy headers are only trusted when the request comes from a local/private reverse proxy, so direct clients cannot spoof them to bypass rate limits.
669
+ - **Reversible Sensitive Data Masking (PII)**:
670
+ - Personal values (`sensitiveKeys`) in context data and prompt text are replaced with anonymous deterministic tokens (`[name_01]`, `[email_01]`, `[dni_01]`) before leaving the server.
671
+ - Responses (`result.text`) are returned fully restored with original user values.
672
+ - **0ms Prompt Cache Synergy**:
673
+ - Cache hashes are computed against the *anonymized* prompt. Two different users asking the same query template trigger an immediate 0ms, $0 latency/cost Cache Hit with their unique personal values restored cleanly.
674
+ - **Sliding Window Rate Limiting ("Anti-Quiebra")**:
675
+ - Protects API budgets with minute/day limits (e.g. `{ minute: 6, day: 30 }` or `{ max: 15, windowMs: 60000 }`), returning HTTP 429 clean responses before depleting credits.
676
+ - Express route protection middleware available via `ai.protect()`.
677
+ - **Response Streaming & SSE (`ai.pipe` & `askStream`)**:
678
+ - Stream tokens in real time directly to Express responses via `await ai.pipe(res, prompt, { sse: true })` with automatic Nginx anti-buffering (`X-Accel-Buffering: no`), or iterate manually via `for await (const chunk of ai.askStream(prompt))`.
679
+
680
+ ```javascript
681
+ import AI, { ai } from "@seip/bluebird-js/core/ai.js";
682
+
683
+ const supportAi = new AI({
684
+ provider: "deepseek", // "deepseek" (default) | "gemini" | "openai" | "custom"
685
+ model: "deepseek-flash", // default model
686
+ rateLimit: { minute: 6, day: 30 }, // Sliding window protection
687
+ cacheTtl: 3600, // Cache responses for 1 hour
688
+ });
689
+
690
+ routerApi.post("/support/reply", supportAi.protect(), async (req, res) => {
691
+ const userData = {
692
+ name: "Maria Garcia",
693
+ email: "maria@example.com",
694
+ dni: "45123987",
695
+ issue: "Need help updating billing details",
696
+ };
697
+
698
+ const result = await supportAi.ask("Draft a courteous support reply for this user:", {
699
+ data: userData,
700
+ sensitiveKeys: ["name", "email", "dni"], // Masked to [name_01], [email_01], [dni_01] before sending!
701
+ request: req, // Automatic IP rate limiting
702
+ json: true,
703
+ });
704
+
705
+ // result.text is returned fully restored with 'Maria Garcia' and 'maria@example.com'!
706
+ res.ok(result);
707
+ });
708
+
709
+ // Stream real-time Server-Sent Events (SSE) directly to Express client response
710
+ routerApi.post("/support/stream", async (req, res) => {
711
+ await supportAi.pipe(res, req.body.message, { sse: true, request: req });
712
+ });
713
+
714
+ // Or iterate chunks manually via async generator
715
+ for await (const chunk of supportAi.askStream("Explain quantum computing in simple terms")) {
716
+ process.stdout.write(chunk.text);
717
+ }
718
+ ```
719
+
720
+ ## 18. AI Development Guidelines
721
+
722
+ 1. **Views & Client SPA**: HTML `{{ }}` SSR views live in `app/resources/html/` (served via `Render.html()`, `Render.send()`, `Render.partial()`, or `Render.view()`), while React Router client code lives in `app/resources/` (shell `index.html`, config `spa.js`, mounted with `router.spa()` and exported with `npx bluebird-js export`). Static assets live in `public/`. Keep React code free of server-injected state so it stays exportable.
723
+ 2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
724
+ 3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
725
+ 4. **All documentation in English**.
726
+ 5. **Styling**: Tailwind CSS v4 with the Bluebird design system (`core/react/client/theme.css`, injected by the Vite plugin after `@import "tailwindcss"`). Use semantic tokens (`bg-background`, `bg-card`, `text-foreground`, `text-muted-foreground`, `border-border`, `bg-primary`, `text-destructive`) instead of raw palette colors such as `slate-*` or `sky-*`, so light and dark modes work without `dark:` variants. In HTML views use the component classes (`btn btn-primary|secondary|outline|ghost|danger|link`, `btn-sm|lg|icon`, `card`, `card-title`, `card-description`, `field`, `field-label`, `badge` + `badge-dot`, `nav-link`, `glass`, `bg-app`, `brand`); in React use `Button`, `Card`, `Input`, `Badge`, and `buttonVariants()` for links styled as buttons. Keep color minimal: one `primary` action per view, `secondary`/`outline`/`ghost` for the rest, `danger` for destructive actions, `brand` only for the logo, and tones as a small dot (badges, toasts). Projects customize the theme by overriding the CSS variables (`:root { --primary: ... }`, `.dark { ... }`), or disable it with `bluebird({ theme: false })`. Reuse the components from `@seip/bluebird-js/react` and `public/js/bluebird.js` before writing new ones.