@seip/bluebird-js 0.1.6 → 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 (152) hide show
  1. package/.vscode/extensions.json +7 -7
  2. package/.vscode/settings.json +10 -10
  3. package/AGENTS.md +266 -116
  4. package/README.md +258 -245
  5. package/app/models/user.js +19 -0
  6. package/app/resources/html/home.html +137 -0
  7. package/app/resources/html/layouts/main.html +54 -0
  8. package/app/resources/html/notFound.html +14 -0
  9. package/app/resources/html/terms.html +46 -0
  10. package/app/resources/index.html +27 -0
  11. package/app/resources/layouts/AppLayout.jsx +89 -0
  12. package/app/resources/main.jsx +18 -0
  13. package/app/resources/pages/Dashboard.jsx +98 -0
  14. package/app/resources/pages/Home.jsx +140 -0
  15. package/app/resources/pages/Login.jsx +35 -0
  16. package/app/resources/pages/NotFound.jsx +16 -0
  17. package/app/resources/pages/Register.jsx +55 -0
  18. package/app/resources/routes.jsx +54 -0
  19. package/app/resources/spa.js +67 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +85 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +49 -37
  24. package/core/ai.d.ts +151 -151
  25. package/core/ai.js +1071 -1051
  26. package/core/app.d.ts +2 -18
  27. package/core/app.js +978 -792
  28. package/core/auth.d.ts +2 -13
  29. package/core/auth.js +444 -326
  30. package/core/cli/backup.js +167 -167
  31. package/core/cli/build.js +37 -0
  32. package/core/cli/dev.js +155 -0
  33. package/core/cli/doctor.js +37 -2
  34. package/core/cli/export.js +191 -0
  35. package/core/cli/init.js +101 -332
  36. package/core/cli/nginx.js +1 -1
  37. package/core/cli/templates.js +139 -0
  38. package/core/cli/view.js +73 -136
  39. package/core/config.js +44 -2
  40. package/core/csrf.js +156 -24
  41. package/core/database.js +737 -684
  42. package/core/debug.js +1 -1
  43. package/core/html.js +8 -1
  44. package/core/index.d.ts +1286 -1431
  45. package/core/paths.js +55 -0
  46. package/core/ratelimit.js +10 -1
  47. package/core/react/client/api.js +237 -0
  48. package/core/react/client/auth.js +236 -0
  49. package/core/react/client/components.js +1321 -0
  50. package/core/react/client/i18n.js +338 -0
  51. package/core/react/client/index.d.ts +249 -0
  52. package/core/react/client/index.js +49 -0
  53. package/core/react/client/router.js +26 -0
  54. package/core/react/client/theme.css +512 -0
  55. package/core/render-cache.js +250 -212
  56. package/core/render.d.ts +25 -21
  57. package/core/render.js +613 -603
  58. package/core/router.d.ts +2 -3
  59. package/core/router.js +171 -171
  60. package/core/seo.js +10 -0
  61. package/core/spa.js +599 -0
  62. package/core/view-loader.js +81 -455
  63. package/core/vite-plugin.d.ts +18 -0
  64. package/core/vite-plugin.js +162 -0
  65. package/core/vite.js +250 -145
  66. package/index.js +22 -18
  67. package/jsconfig.json +5 -3
  68. package/package.json +114 -92
  69. package/production.md +8 -3
  70. package/public/js/bluebird.js +1160 -0
  71. package/templates/_auth/app/database.js +19 -0
  72. package/templates/_auth/app/models/user.js +22 -0
  73. package/templates/_auth/app/routes/auth-router.js +304 -0
  74. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  75. package/templates/_base/app/resources/html/notFound.html +14 -0
  76. package/templates/_base/app/resources/index.html +27 -0
  77. package/templates/_base/app/resources/styles.css +9 -0
  78. package/templates/api/app/models/note.js +18 -0
  79. package/templates/api/app/routes/api.js +82 -0
  80. package/templates/api/app/routes/auth.js +11 -0
  81. package/templates/api/index.js +19 -0
  82. package/templates/api/template.json +13 -0
  83. package/templates/auth/app/mail.js +11 -0
  84. package/templates/auth/app/models/password_reset.js +18 -0
  85. package/templates/auth/app/resources/html/home.html +21 -0
  86. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  87. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  88. package/templates/auth/app/resources/main.jsx +18 -0
  89. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  90. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  91. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  92. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  93. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  94. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  95. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  96. package/templates/auth/app/resources/routes.jsx +54 -0
  97. package/templates/auth/app/resources/spa.js +29 -0
  98. package/templates/auth/app/routes/api.js +17 -0
  99. package/templates/auth/app/routes/auth.js +13 -0
  100. package/templates/auth/app/routes/web.js +21 -0
  101. package/templates/auth/index.js +19 -0
  102. package/templates/auth/template.json +15 -0
  103. package/templates/blank/app/models/.gitkeep +0 -0
  104. package/templates/blank/app/resources/html/home.html +27 -0
  105. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  106. package/templates/blank/app/resources/main.jsx +16 -0
  107. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  108. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  109. package/templates/blank/app/resources/routes.jsx +15 -0
  110. package/templates/blank/app/resources/spa.js +24 -0
  111. package/templates/blank/app/routes/api.js +11 -0
  112. package/templates/blank/app/routes/web.js +21 -0
  113. package/templates/blank/index.js +13 -0
  114. package/templates/blank/template.json +12 -0
  115. package/templates/blog/app/lib/blog.js +149 -0
  116. package/templates/blog/app/models/post.js +22 -0
  117. package/templates/blog/app/resources/html/home.html +28 -0
  118. package/templates/blog/app/resources/html/not-found.html +5 -0
  119. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  120. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  121. package/templates/blog/app/resources/html/post.html +8 -0
  122. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  123. package/templates/blog/app/resources/main.jsx +18 -0
  124. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  125. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  126. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  127. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  128. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  129. package/templates/blog/app/resources/routes.jsx +51 -0
  130. package/templates/blog/app/resources/spa.js +25 -0
  131. package/templates/blog/app/resources/styles.css +40 -0
  132. package/templates/blog/app/routes/api.js +77 -0
  133. package/templates/blog/app/routes/auth.js +10 -0
  134. package/templates/blog/app/routes/web.js +114 -0
  135. package/templates/blog/index.js +21 -0
  136. package/templates/blog/template.json +14 -0
  137. package/vite.config.js +11 -0
  138. package/app/views/about.jsx +0 -98
  139. package/app/views/components/Header.jsx +0 -42
  140. package/app/views/components/LiveCounter.jsx +0 -66
  141. package/app/views/dashboard.jsx +0 -300
  142. package/app/views/index.jsx +0 -123
  143. package/app/views/layouts/main/view.jsx +0 -201
  144. package/app/views/legal/terms.html +0 -29
  145. package/app/views/login.jsx +0 -141
  146. package/core/actions.d.ts +0 -4
  147. package/core/actions.js +0 -329
  148. package/core/jsx.d.ts +0 -38
  149. package/core/jsx.js +0 -1432
  150. package/core/vite.d.ts +0 -3
  151. package/public/js/bluebird-client.js +0 -3161
  152. package/public/js/tailwind.js +0 -8
package/AGENTS.md CHANGED
@@ -4,36 +4,40 @@ This document serves as the primary manual for any AI Agent interacting with the
4
4
 
5
5
  ## 1. Core Architecture
6
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.
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
8
 
9
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.
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.
13
14
 
14
15
  ## 2. Modern JavaScript Standard (ESM)
15
16
 
16
- Bluebird.js standardizes on pure modern JavaScript (Node.js 22.18+ ESM) with zero build steps or transpilation pipelines required:
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:
17
18
 
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.
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"`.
21
24
  - **IDE Intellisense**: Powered by `core/index.d.ts` and `jsconfig.json`.
22
25
 
23
26
  ```javascript
24
27
  import App from "@seip/bluebird-js/core/app.js";
25
28
  import routerApi from "./app/routes/api.js";
29
+ import routerAuth from "./app/routes/auth.js";
26
30
  import routerWeb from "./app/routes/web.js";
27
31
 
28
32
  const app = new App({
29
- routes: [routerWeb, routerApi],
33
+ routes: [routerWeb, routerAuth, routerApi],
30
34
  port: process.env.PORT || 3000,
31
35
  });
32
36
 
33
37
  app.run();
34
38
  ```
35
39
 
36
- ## 3. Routing (Router)
40
+ ## 3. Routing (Router & `router.spa()`)
37
41
 
38
42
  Do not use Express' native router directly. Always use Bluebird's `Router` wrapper.
39
43
 
@@ -49,7 +53,22 @@ routerApi.get("/users", (req, res) => {
49
53
  export default routerApi;
50
54
  ```
51
55
 
52
- When created with `{ seo: true }`, all GET routes registered on that router are tracked for search engine indexing.
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
+ ```
53
72
 
54
73
  ## 4. Request Validation (Validator)
55
74
 
@@ -74,7 +93,7 @@ routerApi.post("/users", validateUser.middleware(), (req, res) => {
74
93
  ## 5. Lightweight BaseModel (Model)
75
94
 
76
95
  > **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.
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.
78
97
  > **For complex multi-tier enterprise ORM mapping, Prisma is recommended.**
79
98
 
80
99
  ### Defining a Model
@@ -141,14 +160,22 @@ await User.restore(userId);
141
160
 
142
161
  ## 6. CSRF Protection (Csrf)
143
162
 
144
- Bluebird provides native, zero-dependency HMAC-signed CSRF protection (`core/csrf.js`):
163
+ Bluebird provides built-in HMAC-signed double-submit CSRF protection (`core/csrf.js`):
145
164
 
146
165
  ```javascript
147
166
  import Csrf from "@seip/bluebird-js/core/csrf.js";
148
167
 
149
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)
150
173
  ```
151
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
+
152
179
  ## 7. Authentication & Password Hashing (Auth & Hash)
153
180
 
154
181
  ### Password Hashing (Hash)
@@ -164,7 +191,7 @@ const isValid = await Hash.verify("mySecretPassword", hash);
164
191
 
165
192
  ### JWT Handling (Auth)
166
193
 
167
- Native JWT handling with AES-256-GCM encryption and HMAC-SHA256 signature verification using `node:crypto`.
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:
168
195
 
169
196
  ```javascript
170
197
  import Auth from "@seip/bluebird-js/core/auth.js";
@@ -173,8 +200,16 @@ router.get("/profile", Auth.protect(), (req, res) => {
173
200
  res.json({ user: req.user });
174
201
  });
175
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
+
176
211
  router.post("/login", async (req, res) => {
177
- const user = { id: 1, name: "John" };
212
+ const user = { id: 1, name: "John", role: "user" };
178
213
  await Auth.login(res, user);
179
214
  res.ok(user, "Logged in");
180
215
  });
@@ -185,6 +220,10 @@ router.post("/logout", async (req, res) => {
185
220
  });
186
221
  ```
187
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
+
188
227
  ## 8. HTTP Response Helpers & Health Check
189
228
 
190
229
  Bluebird decorates the Express `res` object with standardized helper methods:
@@ -203,6 +242,8 @@ res.serverError("Internal failure", err);
203
242
 
204
243
  Every Bluebird application provides a native `/api/health` endpoint returning uptime, timestamp, environment, and memory consumption.
205
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
+
206
247
  ## 9. Performance Caching (Cache & Redis)
207
248
 
208
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.
@@ -225,6 +266,20 @@ await Cache.delete("custom_key");
225
266
  await Cache.clear();
226
267
  ```
227
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
+
228
283
  ## 10. Database Module (database.js)
229
284
 
230
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`)**:
@@ -257,11 +312,7 @@ await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.
257
312
  });
258
313
  ```
259
314
 
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
- ```
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.
265
316
 
266
317
  ## 11. On-Demand Modules & CLI Add
267
318
 
@@ -278,16 +329,44 @@ npx bluebird-js add bcrypt # Installs bcrypt
278
329
  npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
279
330
  npx bluebird-js add helmet # Installs helmet
280
331
  npx bluebird-js add ejs # Installs ejs
281
- npx bluebird-js add react-islands # Installs react, react-dom, vite & scaffolds island runtime
282
332
  ```
283
333
 
284
334
  ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
285
335
 
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`).
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.
287
366
 
288
367
  ### Native Rate Limiting (`core/ratelimit.js`)
289
368
 
290
- Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers):
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:
291
370
 
292
371
  ```javascript
293
372
  import App from "@seip/bluebird-js/core/app.js";
@@ -304,7 +383,7 @@ routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req,
304
383
 
305
384
  ### Automatic SEO Sitemap & Robots (`core/seo.js`)
306
385
 
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`.
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")`.
308
387
 
309
388
  ### Helmet Integration
310
389
 
@@ -333,9 +412,14 @@ For complete deployment details including Nginx reverse proxy configuration and
333
412
 
334
413
  ### Electron & Desktop Mode (`desktop: true`)
335
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
+
336
420
  Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
337
421
 
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()`).
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()`).
339
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.
340
424
  - **Dynamic Port & LAN / QR Access**:
341
425
  - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
@@ -349,21 +433,23 @@ Bluebird supports running embedded inside Electron or Tauri desktop applications
349
433
  ```json
350
434
  "build": {
351
435
  "asar": true,
352
- "asarUnpack": ["app/views/**/*", "database/**/*"]
436
+ "asarUnpack": ["app/resources/**/*", "database/**/*"]
353
437
  }
354
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).
355
440
 
356
441
  ```javascript
357
442
  import App from "@seip/bluebird-js/core/app.js";
358
443
  import { app as electronApp, BrowserWindow } from "electron";
359
444
  import routerApi from "./app/routes/api.js";
445
+ import routerAuth from "./app/routes/auth.js";
360
446
  import routerWeb from "./app/routes/web.js";
361
447
 
362
448
  const app = new App({
363
449
  desktop: true,
364
450
  appPath: electronApp.getAppPath(),
365
451
  userDataPath: electronApp.getPath("userData"),
366
- routes: [routerWeb, routerApi],
452
+ routes: [routerWeb, routerAuth, routerApi],
367
453
  });
368
454
 
369
455
  electronApp.whenReady().then(async () => {
@@ -380,11 +466,14 @@ electronApp.whenReady().then(async () => {
380
466
  ## 14. Developer Tooling CLI
381
467
 
382
468
  ```bash
469
+ npx bluebird-js [--blank|--auth|--blog|--api|--demo] # Scaffolds a project from a template (default: blank)
383
470
  npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
384
471
  npx bluebird-js make:model <Name> # BaseModel scaffolding
385
472
  npx bluebird-js make:route <name> # REST route scaffolding
386
473
  npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
387
- npx bluebird-js make:view <name> # HTML or EJS template 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/
388
477
  npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
389
478
  npx bluebird-js make:migration --model <Model> # Auto DDL migration for specific Model schema
390
479
  npx bluebird-js migrate [--yes] # Executes pending migrations with auto-detection
@@ -393,6 +482,7 @@ npx bluebird-js migrate:rollback # Reverts latest batch
393
482
  npx bluebird-js make:seed <name> # Database seed file creation
394
483
  npx bluebird-js seed # Executes database seeds
395
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
396
486
  npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
397
487
  npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
398
488
  npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
@@ -413,100 +503,159 @@ await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
413
503
  await Queue.work();
414
504
  ```
415
505
 
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/` (ignoring `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) and mounts GET routes when `App` starts.
437
- - Export route settings directly from any view file:
438
- - `export const route = "/login"` (or inferred automatically from filename; `false` disables auto-routing)
439
- - `export const cache = 300` (applies `Render.cache(300)` automatically)
440
- - `export const layout = "main"` (uses `app/views/layouts/main/view.jsx`)
441
- - `export const middlewares = [Auth.protect({ redirect: "/login" })]`
442
- - `export const seo = true` (registers route in `/sitemap.xml` and `/robots.txt`)
443
- - Disable auto-discovery if desired via `new App({ noAutoDiscoverRoutes: true })`.
444
- - **Client Components & Anti-Accordion Skeletons (`<Client>` / `<Island>`)**:
445
- - Everything renders as pure SSR by default (0 KB client JS).
446
- - For client-side interactivity (`useEffect`, `useState`, or native DOM logic), use `<Client>` or `<Island>` from `@seip/bluebird-js/core/jsx.js`.
447
- - 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.
448
- - 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`).
449
- - **Native Server Actions (`core/actions.js` & `export const actions = { ... }`)**:
450
- - 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.
451
- - 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.
452
- - **Shared Layouts (`app/views/layouts/main/view.jsx`)**:
453
- - Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, children, head, ctx, data }`.
454
- - When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
455
- - 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.
456
- - **Comprehensive Built-In Client UI Kit (`public/js/bluebird-client.js`)**:
457
- - `toast({ title, description, type, position, duration })`
458
- - `snackbar({ message, type, duration })`
459
- - `bluebird('drawer', { id, action: 'open'|'close'|'toggle' })`
460
- - `new ResponsiveDataTable(containerId, options)`
461
- - `bluebird('command')` palette (`Ctrl+K`), `bluebird('tab')`, `bluebird('popover')`, `bluebird('carousel')`
462
- - Declarative forms via `form[data-bb-form="true"]`: submits via `fetch`, auto-injects CSRF tokens, and follows `X-Bluebird-Redirect`.
463
- - Native `document.startViewTransition()` page navigation with preserved elements via `data-persist="true"`.
464
-
465
- ```jsx
466
- // app/views/dashboard.jsx
467
- import Auth from "@seip/bluebird-js/core/auth.js";
468
- import Actions from "@seip/bluebird-js/core/actions.js";
469
- import { Client } from "@seip/bluebird-js/core/jsx.js";
470
- import Header from "./components/Header.jsx";
471
- import LiveCounter from "./components/LiveCounter.js";
472
-
473
- export const route = "/dashboard";
474
- export const layout = "main";
475
- export const middlewares = [Auth.protect({ redirect: "/login" })];
476
- export const seo = false;
477
- export const head = (data) => ({ title: `Dashboard — ${data.user?.name}` });
478
-
479
- export const actions = {
480
- syncCount: Actions.define(
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",
481
556
  {
482
- maxBytes: "16kb",
483
- schema: { count: { required: true, number: true } },
557
+ title: "Storefront",
558
+ clientsHtml: clients.map((c) => `<span>${escapeHtml(c.name)}</span>`).join(""),
484
559
  },
485
- async ({ body, user }) => {
486
- return { syncedCount: Number(body.count), updatedBy: user?.email };
487
- }
488
- ),
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
+ },
489
584
  };
490
585
 
491
- export default async function DashboardView({ user, syncedCount = 7 }) {
492
- return (
493
- <>
494
- <Header title="Dashboard" user={user} count={syncedCount} />
495
- <Client
496
- component={LiveCounter}
497
- props={{ initial: syncedCount }}
498
- persistent={true}
499
- minHeight={56}
500
- skeleton={<div className="h-14 animate-pulse bg-slate-900 rounded-xl" />}
501
- />
502
- </>
503
- );
504
- }
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
505
654
  ```
506
655
 
507
656
  ## 17. Unified AI Client (AI & core/ai.js)
508
657
 
509
- 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:
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:
510
659
 
511
660
  - **DeepSeek by Default**:
512
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).
@@ -516,7 +665,7 @@ Bluebird includes a native, zero-dependency unified AI client (`core/ai.js`) sup
516
665
  - **OpenAI & Custom Endpoints**:
517
666
  - Compatible with `gpt-4o-mini`, `gpt-4o`, Ollama, OpenRouter, and custom endpoints via `baseURL`.
518
667
  - **Accurate Real Client IP Detection (`getClientIp`)**:
519
- - 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:`).
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.
520
669
  - **Reversible Sensitive Data Masking (PII)**:
521
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.
522
671
  - Responses (`result.text`) are returned fully restored with original user values.
@@ -570,7 +719,8 @@ for await (const chunk of supportAi.askStream("Explain quantum computing in simp
570
719
 
571
720
  ## 18. AI Development Guidelines
572
721
 
573
- 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()`.
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.
574
723
  2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
575
724
  3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
576
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.