@seip/bluebird-js 0.1.2 → 0.1.5

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 (43) hide show
  1. package/.vscode/extensions.json +7 -0
  2. package/.vscode/settings.json +10 -0
  3. package/AGENTS.md +495 -454
  4. package/README.md +528 -353
  5. package/app/routes/web.js +47 -55
  6. package/app/views/about.jsx +98 -0
  7. package/app/views/components/Header.jsx +42 -0
  8. package/app/views/components/LiveCounter.jsx +66 -0
  9. package/app/views/dashboard.jsx +300 -0
  10. package/app/views/index.jsx +123 -0
  11. package/app/views/layouts/main/view.jsx +201 -0
  12. package/app/views/legal/terms.html +29 -19
  13. package/app/views/login.jsx +141 -0
  14. package/core/actions.d.ts +4 -0
  15. package/core/actions.js +329 -0
  16. package/core/app.js +38 -6
  17. package/core/cli/doctor.js +3 -4
  18. package/core/cli/init.js +20 -6
  19. package/core/cli/migrate.js +418 -145
  20. package/core/cli/view.js +76 -11
  21. package/core/database.js +6 -10
  22. package/core/debug.js +1 -1
  23. package/core/html.d.ts +54 -42
  24. package/core/html.js +473 -217
  25. package/core/index.d.ts +1385 -1190
  26. package/core/jsx.d.ts +38 -0
  27. package/core/jsx.js +1432 -0
  28. package/core/model.js +271 -61
  29. package/core/render-cache.js +212 -212
  30. package/core/render.d.ts +20 -2
  31. package/core/render.js +459 -51
  32. package/core/validate.js +1 -1
  33. package/core/view-loader.js +360 -24
  34. package/package.json +9 -3
  35. package/public/js/bluebird-client.js +3160 -1780
  36. package/public/js/tailwind.js +8 -0
  37. package/app/views/about.js +0 -63
  38. package/app/views/dashboard.js +0 -147
  39. package/app/views/index.js +0 -80
  40. package/app/views/layouts/main/view.js +0 -81
  41. package/app/views/login.js +0 -80
  42. package/public/css/bluebird.min.css +0 -2
  43. package/public/js/bluebird.min.js +0 -1073
package/AGENTS.md CHANGED
@@ -1,454 +1,495 @@
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
- await User.delete(userId);
123
- await User.delete(userId, { force: true });
124
- await User.delete(userId, { cascade: [Post] });
125
- await User.restore(userId);
126
- ```
127
-
128
- ## 6. CSRF Protection (Csrf)
129
-
130
- Bluebird provides native, zero-dependency HMAC-signed CSRF protection (`core/csrf.js`):
131
-
132
- ```javascript
133
- import Csrf from "@seip/bluebird-js/core/csrf.js";
134
-
135
- routerWeb.use(Csrf.middleware());
136
- ```
137
-
138
- ## 7. Authentication & Password Hashing (Auth & Hash)
139
-
140
- ### Password Hashing (Hash)
141
-
142
- Native password hashing using `node:crypto.scrypt` with random salt and timing-safe comparison (zero external npm dependencies required).
143
-
144
- ```javascript
145
- import Hash from "@seip/bluebird-js/core/hash.js";
146
-
147
- const hash = await Hash.make("mySecretPassword");
148
- const isValid = await Hash.verify("mySecretPassword", hash);
149
- ```
150
-
151
- ### JWT Handling (Auth)
152
-
153
- Native JWT handling with AES-256-GCM encryption and HMAC-SHA256 signature verification using `node:crypto`.
154
-
155
- ```javascript
156
- import Auth from "@seip/bluebird-js/core/auth.js";
157
-
158
- router.get("/profile", Auth.protect(), (req, res) => {
159
- res.json({ user: req.user });
160
- });
161
-
162
- router.post("/login", async (req, res) => {
163
- const user = { id: 1, name: "John" };
164
- await Auth.login(res, user);
165
- res.ok(user, "Logged in");
166
- });
167
-
168
- router.post("/logout", async (req, res) => {
169
- await Auth.logout(res);
170
- res.ok(null, "Logged out");
171
- });
172
- ```
173
-
174
- ## 8. HTTP Response Helpers & Health Check
175
-
176
- Bluebird decorates the Express `res` object with standardized helper methods:
177
-
178
- ```javascript
179
- res.ok(data, "Success message");
180
- res.created(data, "Created successfully");
181
- res.paginate(items, pagination, "Fetched");
182
-
183
- res.badRequest("Invalid input", errors);
184
- res.unauthorized("Authentication required");
185
- res.forbidden("Access denied");
186
- res.notFound("Resource not found");
187
- res.serverError("Internal failure", err);
188
- ```
189
-
190
- Every Bluebird application provides a native `/api/health` endpoint returning uptime, timestamp, environment, and memory consumption.
191
-
192
- ## 9. Performance Caching (Cache & Redis)
193
-
194
- 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.
195
-
196
- ```javascript
197
- import Cache from "@seip/bluebird-js/core/cache.js";
198
-
199
- router.get("/stats", Cache.middleware(60), (req, res) => {
200
- res.ok({ usersCount: 150 });
201
- });
202
-
203
- await Cache.set("custom_key", { data: "value" }, 120, { driver: "memory" });
204
- const cachedData = await Cache.get("custom_key", { driver: "memory" });
205
-
206
- const stats = await Cache.deduplicate("stats-key", async () => {
207
- return await calculateHeavyStats();
208
- });
209
-
210
- await Cache.delete("custom_key");
211
- await Cache.clear();
212
- ```
213
-
214
- ## 10. Database Module (database.js)
215
-
216
- 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`)**:
217
-
218
- - **Native SQLite by Default:** No native C++ compilation or build tools required.
219
- - **SQLite Concurrency & WAL:** Automatically configures WAL mode, busy timeout, and memory-mapped I/O.
220
- - **Prepared Statement Caching:** SQLite caches prepared statement ASTs automatically.
221
- - **Query Caching:** Supports `{ cache: 60 }` across memory, file, and redis backends.
222
-
223
- ```javascript
224
- import { Database, DB_TYPE } from "@seip/bluebird-js/core/database.js";
225
-
226
- const connection = new Database(20);
227
-
228
- const user = await connection.query("SELECT * FROM users WHERE id = ?", [1], "return_row");
229
- const stats = await connection.query("SELECT COUNT(*) as cnt FROM logs", [], { cache: 60 });
230
-
231
- await connection.transaction(async (tx) => {
232
- const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
233
- await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
234
- });
235
- ```
236
-
237
- ## 11. On-Demand Modules & CLI Add
238
-
239
- To keep dependencies lightweight and minimal, optional modules load dynamically on-demand:
240
-
241
- ```bash
242
- npx bluebird-js add upload # Installs multer for file uploads
243
- npx bluebird-js add ws # Installs ws for WebSockets
244
- npx bluebird-js add redis # Installs redis for distributed caching
245
- npx bluebird-js add sqlite # Installs better-sqlite3 (fallback for older environments)
246
- npx bluebird-js add mysql # Installs mysql2
247
- npx bluebird-js add postgres # Installs pg
248
- npx bluebird-js add bcrypt # Installs bcrypt
249
- npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
250
- npx bluebird-js add helmet # Installs helmet
251
- npx bluebird-js add ejs # Installs ejs
252
- npx bluebird-js add react-islands # Installs react, react-dom, vite & scaffolds island runtime
253
- ```
254
-
255
- ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
256
-
257
- 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`).
258
-
259
- ### Native Rate Limiting (`core/ratelimit.js`)
260
-
261
- Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers):
262
-
263
- ```javascript
264
- import App from "@seip/bluebird-js/core/app.js";
265
-
266
- const app = new App({
267
- routes: [routerWeb, routerApi],
268
- rateLimit: { max: 120, windowMs: 60000 },
269
- });
270
-
271
- routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req, res) => {
272
- res.ok({ authenticated: true });
273
- });
274
- ```
275
-
276
- ### Automatic SEO Sitemap & Robots (`core/seo.js`)
277
-
278
- 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`.
279
-
280
- ### Helmet Integration
281
-
282
- Helmet can be applied per router when installed (`npx bluebird-js add helmet`):
283
-
284
- ```javascript
285
- import App from "@seip/bluebird-js/core/app.js";
286
-
287
- const apiRouter = new Router("/api");
288
- apiRouter.use(App.helmet());
289
- ```
290
-
291
- ## 13. Production Deployment & Electron Desktop Mode
292
-
293
- ### PM2 & Nginx Reverse Proxy
294
-
295
- Production deployments run directly via `npm start` or PM2 cluster mode:
296
-
297
- ```bash
298
- npx bluebird-js make:ecosystem # Generates ecosystem.config.cjs
299
- npx bluebird-js make:ecosystem --start # Generates and starts immediately in PM2
300
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx config with upstream keepalive & static try_files
301
- ```
302
-
303
- For complete deployment details including Nginx reverse proxy configuration and optional standalone Docker snippet, consult [production.md](production.md).
304
-
305
- ### Electron & Desktop Mode (`desktop: true`)
306
-
307
- Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
308
-
309
- - **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()`).
310
- - **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.
311
- - **Dynamic Port & LAN / QR Access**:
312
- - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
313
- - 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.
314
- - **Uploads & Static Serving**:
315
- - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
316
- - **Clean Shutdown & WAL Checkpoint**:
317
- - 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.
318
- - **Packaging with electron-builder**:
319
- - Recommended `electron-builder` configuration in `package.json`:
320
- ```json
321
- "build": {
322
- "asar": true,
323
- "asarUnpack": ["app/views/**/*", "database/**/*"]
324
- }
325
- ```
326
-
327
- ```javascript
328
- import App from "@seip/bluebird-js/core/app.js";
329
- import { app as electronApp, BrowserWindow } from "electron";
330
- import routerApi from "./app/routes/api.js";
331
- import routerWeb from "./app/routes/web.js";
332
-
333
- const app = new App({
334
- desktop: true,
335
- appPath: electronApp.getAppPath(),
336
- userDataPath: electronApp.getPath("userData"),
337
- routes: [routerWeb, routerApi],
338
- });
339
-
340
- electronApp.whenReady().then(async () => {
341
- const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
342
- const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
343
- mainWindow.loadURL(url);
344
-
345
- electronApp.on("before-quit", async () => {
346
- await app.close();
347
- });
348
- });
349
- ```
350
-
351
- ## 14. Developer Tooling CLI
352
-
353
- ```bash
354
- npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
355
- npx bluebird-js make:model <Name> # BaseModel scaffolding
356
- npx bluebird-js make:route <name> # REST route scaffolding
357
- npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
358
- npx bluebird-js make:view <name> # HTML or EJS template scaffolding
359
- npx bluebird-js make:migration <name> # Blank SQL migration
360
- npx bluebird-js make:migration --model <Model> # Auto DDL migration from Model schema
361
- npx bluebird-js make:migration --all # Batch generate migrations for all models
362
- npx bluebird-js migrate # Applies pending migrations
363
- npx bluebird-js migrate:status # Displays applied batches
364
- npx bluebird-js migrate:rollback # Reverts latest batch
365
- npx bluebird-js make:seed <name> # Database seed file creation
366
- npx bluebird-js seed # Executes database seeds
367
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
368
- npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
369
- ```
370
-
371
- ## 15. Background Jobs & Queue (Queue)
372
-
373
- Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
374
-
375
- ```javascript
376
- import Queue from "@seip/bluebird-js/core/queue.js";
377
-
378
- Queue.process("sendWelcomeEmail", async (payload) => {
379
- console.log(`Sending email to ${payload.email}...`);
380
- });
381
-
382
- await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
383
- await Queue.work();
384
- ```
385
-
386
- ## 16. Pure JavaScript Views, Layouts, Vanilla Scripts & View Transitions
387
-
388
- Bluebird provides a modern, zero-build view architecture uniting database-driven server-rendered HTML with pure ESM JavaScript views, shared layouts, simple inline vanilla scripts, and instant View Transitions SPA navigation:
389
-
390
- - **Zero-Build JavaScript Views (`html\`...\``)**: Located as flat files in `app/views/<name>.js` (e.g. `app/views/about.js`, `app/views/dashboard.js`, `app/views/login.js`). Views export a default rendering function using `html` tagged templates from `@seip/bluebird-js/core/html.js`. All interpolated variables `${val}` are strictly HTML-escaped automatically to prevent XSS. Explicit trusted markup uses `html.raw(markup)`.
391
- - **Shared Layouts (`app/views/layouts/main/view.js` or `app/views/layouts/main.js`)**:
392
- - Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, head, ctx, data }`.
393
- - When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
394
- - 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.
395
- - **Vanilla Inline Scripts (`<script>`)**:
396
- - Zero heavy frontend dependencies. Write plain native JavaScript directly in `<script>` tags inside `html\`...\`` (or using the optional `script` tagged template helper from `@seip/bluebird-js/core/html.js` for safe serialization).
397
- - Scripts inside `[data-bb-outlet]` re-execute automatically upon View Transitions navigation.
398
- - **Dev Live Reload**:
399
- - During development (`debug: true` or `node --watch`), Bluebird automatically reloads connected browser tabs via native Server-Sent Events (`/_bb/dev-reload`) on server restart. Zero browser plugins required.
400
- - **Raw Static HTML (`Render.html`)**:
401
- - For unparsed static files (terms of service, legal disclaimers, offline pages): `Render.html(res, "legal/terms.html", { ttl: 86400 })`. Bypasses template execution completely with zero server overhead.
402
- - **Fragment & Route Caching (`cached` & `Render.cache`)**:
403
- - Cache heavy fragments inside dynamic pages with `await cached("stats:summary", 60, async () => StatsCard(await Stats.summary()))`.
404
- - **Client Router (`public/js/bluebird-client.js`)**:
405
- - Native `document.startViewTransition()` page navigation.
406
- - Outlet-aware swaps via `[data-bb-outlet]` without layout flickering.
407
- - Preserved elements via `data-persist="true"`.
408
-
409
- ```javascript
410
- // app/views/dashboard.js
411
- import { html } from "@seip/bluebird-js/core/html.js";
412
-
413
- export const layout = "main";
414
- export const head = (data) => ({ title: `Dashboard — ${data.user.name}` });
415
-
416
- export default function DashboardView({ user, metrics }) {
417
- const initial = metrics?.unread || 0;
418
-
419
- return html`
420
- <section class="dashboard-grid">
421
- <h1>Welcome back, ${user.name}</h1>
422
-
423
- <div class="card">
424
- <button id="btnDec" class="btn-sm">-</button>
425
- <span id="counter" class="font-bold">${initial}</span>
426
- <button id="btnInc" class="btn-sm">+</button>
427
- </div>
428
- </section>
429
-
430
- <!-- Native vanilla inline script: simple, readable, fast -->
431
- <script>
432
- (() => {
433
- let count = ${initial};
434
- const el = document.getElementById("counter");
435
- document.getElementById("btnInc")?.addEventListener("click", () => {
436
- count++;
437
- if (el) el.textContent = count;
438
- });
439
- document.getElementById("btnDec")?.addEventListener("click", () => {
440
- if (count > 0) count--;
441
- if (el) el.textContent = count;
442
- });
443
- })();
444
- </script>
445
- `;
446
- }
447
- ```
448
-
449
- ## 17. AI Development Guidelines
450
-
451
- 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()`.
452
- 2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
453
- 3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
454
- 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+). 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
+
251
+ ## 11. On-Demand Modules & CLI Add
252
+
253
+ To keep dependencies lightweight and minimal, optional modules load dynamically on-demand:
254
+
255
+ ```bash
256
+ npx bluebird-js add upload # Installs multer for file uploads
257
+ npx bluebird-js add ws # Installs ws for WebSockets
258
+ npx bluebird-js add redis # Installs redis for distributed caching
259
+ npx bluebird-js add sqlite # Installs better-sqlite3 (fallback for older environments)
260
+ npx bluebird-js add mysql # Installs mysql2
261
+ npx bluebird-js add postgres # Installs pg
262
+ npx bluebird-js add bcrypt # Installs bcrypt
263
+ npx bluebird-js add swagger # Installs swagger-ui-express & swagger-jsdoc
264
+ npx bluebird-js add helmet # Installs helmet
265
+ npx bluebird-js add ejs # Installs ejs
266
+ npx bluebird-js add react-islands # Installs react, react-dom, vite & scaffolds island runtime
267
+ ```
268
+
269
+ ## 12. Security, Rate Limiting & SEO (Security Headers, Helmet, RateLimit, Seo)
270
+
271
+ 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`).
272
+
273
+ ### Native Rate Limiting (`core/ratelimit.js`)
274
+
275
+ Configure rate limiting globally via `new App({ rateLimit })` or per-route via `App.rateLimit()` (supports `"memory"` and `"redis"` drivers):
276
+
277
+ ```javascript
278
+ import App from "@seip/bluebird-js/core/app.js";
279
+
280
+ const app = new App({
281
+ routes: [routerWeb, routerApi],
282
+ rateLimit: { max: 120, windowMs: 60000 },
283
+ });
284
+
285
+ routerApi.post("/login", App.rateLimit({ max: 5, windowMs: 60000 }), async (req, res) => {
286
+ res.ok({ authenticated: true });
287
+ });
288
+ ```
289
+
290
+ ### Automatic SEO Sitemap & Robots (`core/seo.js`)
291
+
292
+ 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`.
293
+
294
+ ### Helmet Integration
295
+
296
+ Helmet can be applied per router when installed (`npx bluebird-js add helmet`):
297
+
298
+ ```javascript
299
+ import App from "@seip/bluebird-js/core/app.js";
300
+
301
+ const apiRouter = new Router("/api");
302
+ apiRouter.use(App.helmet());
303
+ ```
304
+
305
+ ## 13. Production Deployment & Electron Desktop Mode
306
+
307
+ ### PM2 & Nginx Reverse Proxy
308
+
309
+ Production deployments run directly via `npm start` or PM2 cluster mode:
310
+
311
+ ```bash
312
+ npx bluebird-js make:ecosystem # Generates ecosystem.config.cjs
313
+ npx bluebird-js make:ecosystem --start # Generates and starts immediately in PM2
314
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx config with upstream keepalive & static try_files
315
+ ```
316
+
317
+ For complete deployment details including Nginx reverse proxy configuration and optional standalone Docker snippet, consult [production.md](production.md).
318
+
319
+ ### Electron & Desktop Mode (`desktop: true`)
320
+
321
+ Bluebird supports running embedded inside Electron or Tauri desktop applications where the application bundle (`.asar`) is read-only:
322
+
323
+ - **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()`).
324
+ - **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.
325
+ - **Dynamic Port & LAN / QR Access**:
326
+ - By default, binds to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
327
+ - 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.
328
+ - **Uploads & Static Serving**:
329
+ - In desktop mode, `Upload.storage()` writes to `userDataDir/uploads` and `App` automatically mounts `/uploads` to serve uploaded files statically without read-only filesystem errors.
330
+ - **Clean Shutdown & WAL Checkpoint**:
331
+ - 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.
332
+ - **Packaging with electron-builder**:
333
+ - Recommended `electron-builder` configuration in `package.json`:
334
+ ```json
335
+ "build": {
336
+ "asar": true,
337
+ "asarUnpack": ["app/views/**/*", "database/**/*"]
338
+ }
339
+ ```
340
+
341
+ ```javascript
342
+ import App from "@seip/bluebird-js/core/app.js";
343
+ import { app as electronApp, BrowserWindow } from "electron";
344
+ import routerApi from "./app/routes/api.js";
345
+ import routerWeb from "./app/routes/web.js";
346
+
347
+ const app = new App({
348
+ desktop: true,
349
+ appPath: electronApp.getAppPath(),
350
+ userDataPath: electronApp.getPath("userData"),
351
+ routes: [routerWeb, routerApi],
352
+ });
353
+
354
+ electronApp.whenReady().then(async () => {
355
+ const { url, port, lanUrl, lanIp } = await app.runDesktop({ allowLan: true });
356
+ const mainWindow = new BrowserWindow({ width: 1200, height: 800 });
357
+ mainWindow.loadURL(url);
358
+
359
+ electronApp.on("before-quit", async () => {
360
+ await app.close();
361
+ });
362
+ });
363
+ ```
364
+
365
+ ## 14. Developer Tooling CLI
366
+
367
+ ```bash
368
+ npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
369
+ npx bluebird-js make:model <Name> # BaseModel scaffolding
370
+ npx bluebird-js make:route <name> # REST route scaffolding
371
+ npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
372
+ npx bluebird-js make:view <name> # HTML or EJS template scaffolding
373
+ npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
374
+ npx bluebird-js make:migration --model <Model> # Auto DDL migration for specific Model schema
375
+ npx bluebird-js migrate [--yes] # Executes pending migrations with auto-detection
376
+ npx bluebird-js migrate:status # Displays applied batches
377
+ npx bluebird-js migrate:rollback # Reverts latest batch
378
+ npx bluebird-js make:seed <name> # Database seed file creation
379
+ npx bluebird-js seed # Executes database seeds
380
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
381
+ npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
382
+ ```
383
+
384
+ ## 15. Background Jobs & Queue (Queue)
385
+
386
+ Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
387
+
388
+ ```javascript
389
+ import Queue from "@seip/bluebird-js/core/queue.js";
390
+
391
+ Queue.process("sendWelcomeEmail", async (payload) => {
392
+ console.log(`Sending email to ${payload.email}...`);
393
+ });
394
+
395
+ await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
396
+ await Queue.work();
397
+ ```
398
+
399
+ ## 16. React JSX SSR, Auto-Routes, Client Islands & View Transitions
400
+
401
+ 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:
402
+
403
+ - **Built-In Tailwind CSS v4 & Inter Font**:
404
+ - `public/js/tailwind.js` and Google Fonts `Inter` are loaded by default in the main layout (`app/views/layouts/main/view.jsx`).
405
+ - Zero build steps, zero transpilation, pure modern utilities out of the box with dark mode synchronization.
406
+ - **Native Zero-Build React JSX & TSX SSR (`app/views/*.jsx`, `*.tsx`):**
407
+ - 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.
408
+ - Automatically strips TypeScript type annotations from `.tsx` and `.ts` components while preserving line mappings.
409
+ - Supports `async` Server Components, Fragments (`<>...</>`), spread props, `style` objects, automatic XSS escaping, and mixed `html\`...\`` templates.
410
+ - **`<ErrorBoundary>` Component**:
411
+ - 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>`.
412
+ - **Dynamic Head Manager & Tag Hoisting (`<Head>`, `<Title>`, `<Meta>`):**
413
+ - Hoist `<title>` and `<meta>` tags from nested components directly into the document `<head>`: `<Head><Title>Dashboard</Title><Meta name="robots" content="noindex" /></Head>`.
414
+ - **Streaming SSR with `<Suspense>` & Smart Caching (`Render.stream()`):**
415
+ - Emits chunked transfer encoding responses with immediate shell and `<Suspense fallback={<Skeleton />}>` placeholders.
416
+ - Out-of-order chunks stream as async data resolves, with tiny inline scripts swapping templates seamlessly.
417
+ - 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.
418
+ - **Declarative Auto-Routes from Views (`ViewLoader.discoverRoutes()` / `Render.autoRoutes()`)**:
419
+ - Automatically scans `app/views/` (ignoring `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) and mounts GET routes when `App` starts.
420
+ - Export route settings directly from any view file:
421
+ - `export const route = "/login"` (or inferred automatically from filename; `false` disables auto-routing)
422
+ - `export const cache = 300` (applies `Render.cache(300)` automatically)
423
+ - `export const layout = "main"` (uses `app/views/layouts/main/view.jsx`)
424
+ - `export const middlewares = [Auth.protect({ redirect: "/login" })]`
425
+ - `export const seo = true` (registers route in `/sitemap.xml` and `/robots.txt`)
426
+ - Disable auto-discovery if desired via `new App({ noAutoDiscoverRoutes: true })`.
427
+ - **Client Components & Anti-Accordion Skeletons (`<Client>` / `<Island>`)**:
428
+ - Everything renders as pure SSR by default (0 KB client JS).
429
+ - For client-side interactivity (`useEffect`, `useState`, or native DOM logic), use `<Client>` or `<Island>` from `@seip/bluebird-js/core/jsx.js`.
430
+ - 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.
431
+ - 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`).
432
+ - **Native Server Actions (`core/actions.js` & `export const actions = { ... }`)**:
433
+ - 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.
434
+ - 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.
435
+ - **Shared Layouts (`app/views/layouts/main/view.jsx`)**:
436
+ - Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, children, head, ctx, data }`.
437
+ - When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
438
+ - 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.
439
+ - **Comprehensive Built-In Client UI Kit (`public/js/bluebird-client.js`)**:
440
+ - `toast({ title, description, type, position, duration })`
441
+ - `snackbar({ message, type, duration })`
442
+ - `bluebird('drawer', { id, action: 'open'|'close'|'toggle' })`
443
+ - `new ResponsiveDataTable(containerId, options)`
444
+ - `bluebird('command')` palette (`Ctrl+K`), `bluebird('tab')`, `bluebird('popover')`, `bluebird('carousel')`
445
+ - Declarative forms via `form[data-bb-form="true"]`: submits via `fetch`, auto-injects CSRF tokens, and follows `X-Bluebird-Redirect`.
446
+ - Native `document.startViewTransition()` page navigation with preserved elements via `data-persist="true"`.
447
+
448
+ ```jsx
449
+ // app/views/dashboard.jsx
450
+ import Auth from "@seip/bluebird-js/core/auth.js";
451
+ import Actions from "@seip/bluebird-js/core/actions.js";
452
+ import { Client } from "@seip/bluebird-js/core/jsx.js";
453
+ import Header from "./components/Header.jsx";
454
+ import LiveCounter from "./components/LiveCounter.js";
455
+
456
+ export const route = "/dashboard";
457
+ export const layout = "main";
458
+ export const middlewares = [Auth.protect({ redirect: "/login" })];
459
+ export const seo = false;
460
+ export const head = (data) => ({ title: `Dashboard — ${data.user?.name}` });
461
+
462
+ export const actions = {
463
+ syncCount: Actions.define(
464
+ {
465
+ maxBytes: "16kb",
466
+ schema: { count: { required: true, number: true } },
467
+ },
468
+ async ({ body, user }) => {
469
+ return { syncedCount: Number(body.count), updatedBy: user?.email };
470
+ }
471
+ ),
472
+ };
473
+
474
+ export default async function DashboardView({ user, syncedCount = 7 }) {
475
+ return (
476
+ <>
477
+ <Header title="Dashboard" user={user} count={syncedCount} />
478
+ <Client
479
+ component={LiveCounter}
480
+ props={{ initial: syncedCount }}
481
+ persistent={true}
482
+ minHeight={56}
483
+ skeleton={<div className="h-14 animate-pulse bg-slate-900 rounded-xl" />}
484
+ />
485
+ </>
486
+ );
487
+ }
488
+ ```
489
+
490
+ ## 17. AI Development Guidelines
491
+
492
+ 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()`.
493
+ 2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
494
+ 3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
495
+ 4. **All documentation in English**.