@seip/bluebird-js 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env_example +53 -53
- package/AGENTS.md +426 -403
- package/LICENSE +1 -1
- package/README.md +292 -285
- package/app/routes/api.js +50 -50
- package/app/routes/web.js +55 -53
- package/app/views/about.js +63 -0
- package/app/views/dashboard.js +147 -0
- package/app/views/index.js +80 -0
- package/app/views/layouts/main/view.js +81 -0
- package/app/views/legal/terms.html +19 -0
- package/app/views/login.js +80 -0
- package/core/app.d.ts +18 -18
- package/core/app.js +684 -644
- package/core/auth.d.ts +13 -13
- package/core/auth.js +326 -326
- package/core/cache.d.ts +17 -17
- package/core/cache.js +475 -475
- package/core/cli/doctor.js +287 -287
- package/core/cli/ecosystem.js +162 -162
- package/core/cli/init.js +779 -779
- package/core/cli/migrate.js +541 -541
- package/core/cli/model.js +66 -66
- package/core/cli/nginx.js +199 -199
- package/core/cli/route.js +120 -120
- package/core/cli/view.js +55 -36
- package/core/config.d.ts +3 -3
- package/core/config.js +111 -111
- package/core/csrf.d.ts +3 -3
- package/core/csrf.js +114 -114
- package/core/database.d.ts +15 -15
- package/core/database.js +636 -636
- package/core/debug.d.ts +3 -3
- package/core/debug.js +249 -249
- package/core/hash.d.ts +3 -3
- package/core/hash.js +194 -194
- package/core/html.d.ts +42 -0
- package/core/html.js +217 -0
- package/core/index.d.ts +1176 -1071
- package/core/logger.d.ts +3 -3
- package/core/logger.js +127 -124
- package/core/middleware.d.ts +3 -3
- package/core/middleware.js +28 -28
- package/core/model.d.ts +19 -19
- package/core/model.js +600 -600
- package/core/queue.d.ts +13 -13
- package/core/queue.js +172 -172
- package/core/ratelimit.d.ts +3 -3
- package/core/ratelimit.js +145 -145
- package/core/redis.d.ts +21 -21
- package/core/redis.js +230 -230
- package/core/render-cache.js +212 -0
- package/core/render.d.ts +3 -3
- package/core/render.js +199 -555
- package/core/router.d.ts +3 -3
- package/core/router.js +171 -171
- package/core/seo.d.ts +3 -3
- package/core/seo.js +106 -106
- package/core/swagger.d.ts +3 -3
- package/core/swagger.js +60 -60
- package/core/upload.d.ts +13 -13
- package/core/upload.js +102 -102
- package/core/util/colors.js +82 -82
- package/core/validate.d.ts +15 -15
- package/core/validate.js +364 -364
- package/core/view-loader.js +162 -0
- package/core/vite.d.ts +3 -3
- package/core/vite.js +145 -145
- package/core/ws.d.ts +13 -13
- package/core/ws.js +245 -245
- package/index.js +18 -18
- package/jsconfig.json +15 -15
- package/package.json +85 -86
- package/production.md +273 -273
- package/public/css/bluebird.min.css +1 -1
- package/public/js/bluebird-client.js +1780 -1662
- package/public/js/bluebird.min.js +1072 -1072
- package/app/views/about.html +0 -161
- package/app/views/dashboard.html +0 -140
- package/app/views/index.html +0 -150
- package/app/views/login.html +0 -144
package/AGENTS.md
CHANGED
|
@@ -1,403 +1,426 @@
|
|
|
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
|
-
- Automatically routes SQLite database files, `logs/`, and `app/cache/` to a writable OS user data directory (`Config.userDataDir()`), copying initial bundled SQLite databases on first run.
|
|
310
|
-
- Binds strictly to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
|
|
311
|
-
|
|
312
|
-
```javascript
|
|
313
|
-
const app = new App({
|
|
314
|
-
desktop: true,
|
|
315
|
-
userDataPath: electronApp.getPath("userData"),
|
|
316
|
-
routes: [routerWeb, routerApi],
|
|
317
|
-
});
|
|
318
|
-
|
|
319
|
-
const { url, port } = await app.runDesktop();
|
|
320
|
-
mainWindow.loadURL(url);
|
|
321
|
-
```
|
|
322
|
-
|
|
323
|
-
## 14. Developer Tooling CLI
|
|
324
|
-
|
|
325
|
-
```bash
|
|
326
|
-
npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
|
|
327
|
-
npx bluebird-js make:model <Name> # BaseModel scaffolding
|
|
328
|
-
npx bluebird-js make:route <name> # REST route scaffolding
|
|
329
|
-
npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
|
|
330
|
-
npx bluebird-js make:view <name> # HTML or EJS template scaffolding
|
|
331
|
-
npx bluebird-js make:migration <name> # Blank SQL migration
|
|
332
|
-
npx bluebird-js make:migration --model <Model> # Auto DDL migration from Model schema
|
|
333
|
-
npx bluebird-js make:migration --all # Batch generate migrations for all models
|
|
334
|
-
npx bluebird-js migrate # Applies pending migrations
|
|
335
|
-
npx bluebird-js migrate:status # Displays applied batches
|
|
336
|
-
npx bluebird-js migrate:rollback # Reverts latest batch
|
|
337
|
-
npx bluebird-js make:seed <name> # Database seed file creation
|
|
338
|
-
npx bluebird-js seed # Executes database seeds
|
|
339
|
-
npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
|
|
340
|
-
npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
|
|
341
|
-
```
|
|
342
|
-
|
|
343
|
-
## 15. Background Jobs & Queue (Queue)
|
|
344
|
-
|
|
345
|
-
Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
|
|
346
|
-
|
|
347
|
-
```javascript
|
|
348
|
-
import Queue from "@seip/bluebird-js/core/queue.js";
|
|
349
|
-
|
|
350
|
-
Queue.process("sendWelcomeEmail", async (payload) => {
|
|
351
|
-
console.log(`Sending email to ${payload.email}...`);
|
|
352
|
-
});
|
|
353
|
-
|
|
354
|
-
await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
|
|
355
|
-
await Queue.work();
|
|
356
|
-
```
|
|
357
|
-
|
|
358
|
-
## 16.
|
|
359
|
-
|
|
360
|
-
Bluebird provides a
|
|
361
|
-
|
|
362
|
-
- **
|
|
363
|
-
- **
|
|
364
|
-
-
|
|
365
|
-
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
-
|
|
369
|
-
-
|
|
370
|
-
|
|
371
|
-
-
|
|
372
|
-
- **
|
|
373
|
-
-
|
|
374
|
-
|
|
375
|
-
-
|
|
376
|
-
|
|
377
|
-
-
|
|
378
|
-
-
|
|
379
|
-
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
{
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
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
|
+
- Automatically routes SQLite database files, `logs/`, and `app/cache/` to a writable OS user data directory (`Config.userDataDir()`), copying initial bundled SQLite databases on first run.
|
|
310
|
+
- Binds strictly to `127.0.0.1` with dynamic port allocation (`port: 0`) via `await app.runDesktop()`.
|
|
311
|
+
|
|
312
|
+
```javascript
|
|
313
|
+
const app = new App({
|
|
314
|
+
desktop: true,
|
|
315
|
+
userDataPath: electronApp.getPath("userData"),
|
|
316
|
+
routes: [routerWeb, routerApi],
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
const { url, port } = await app.runDesktop();
|
|
320
|
+
mainWindow.loadURL(url);
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
## 14. Developer Tooling CLI
|
|
324
|
+
|
|
325
|
+
```bash
|
|
326
|
+
npx bluebird-js doctor # Project diagnostics and HTTP smoke tests
|
|
327
|
+
npx bluebird-js make:model <Name> # BaseModel scaffolding
|
|
328
|
+
npx bluebird-js make:route <name> # REST route scaffolding
|
|
329
|
+
npx bluebird-js make:route <name> --auth # Authenticated REST route scaffolding
|
|
330
|
+
npx bluebird-js make:view <name> # HTML or EJS template scaffolding
|
|
331
|
+
npx bluebird-js make:migration <name> # Blank SQL migration
|
|
332
|
+
npx bluebird-js make:migration --model <Model> # Auto DDL migration from Model schema
|
|
333
|
+
npx bluebird-js make:migration --all # Batch generate migrations for all models
|
|
334
|
+
npx bluebird-js migrate # Applies pending migrations
|
|
335
|
+
npx bluebird-js migrate:status # Displays applied batches
|
|
336
|
+
npx bluebird-js migrate:rollback # Reverts latest batch
|
|
337
|
+
npx bluebird-js make:seed <name> # Database seed file creation
|
|
338
|
+
npx bluebird-js seed # Executes database seeds
|
|
339
|
+
npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
|
|
340
|
+
npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
## 15. Background Jobs & Queue (Queue)
|
|
344
|
+
|
|
345
|
+
Lightweight background worker (`core/queue.js`) backed by Redis with automatic in-memory fallback.
|
|
346
|
+
|
|
347
|
+
```javascript
|
|
348
|
+
import Queue from "@seip/bluebird-js/core/queue.js";
|
|
349
|
+
|
|
350
|
+
Queue.process("sendWelcomeEmail", async (payload) => {
|
|
351
|
+
console.log(`Sending email to ${payload.email}...`);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
await Queue.dispatch("sendWelcomeEmail", { email: "user@example.com" });
|
|
355
|
+
await Queue.work();
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
## 16. Pure JavaScript Views, Layouts, Vanilla Scripts & View Transitions
|
|
359
|
+
|
|
360
|
+
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:
|
|
361
|
+
|
|
362
|
+
- **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)`.
|
|
363
|
+
- **Shared Layouts (`app/views/layouts/main/view.js` or `app/views/layouts/main.js`)**:
|
|
364
|
+
- Exported via `export const layout = "main"` on any view (defaults to `"main"`). Layout receives `{ body, head, ctx, data }`.
|
|
365
|
+
- When requested with `X-Bluebird-Partial: 1`, layouts are automatically bypassed for fast partial swaps.
|
|
366
|
+
- 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.
|
|
367
|
+
- **Vanilla Inline Scripts (`<script>`)**:
|
|
368
|
+
- 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).
|
|
369
|
+
- Scripts inside `[data-bb-outlet]` re-execute automatically upon View Transitions navigation.
|
|
370
|
+
- **Dev Live Reload**:
|
|
371
|
+
- 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.
|
|
372
|
+
- **Raw Static HTML (`Render.html`)**:
|
|
373
|
+
- 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.
|
|
374
|
+
- **Fragment & Route Caching (`cached` & `Render.cache`)**:
|
|
375
|
+
- Cache heavy fragments inside dynamic pages with `await cached("stats:summary", 60, async () => StatsCard(await Stats.summary()))`.
|
|
376
|
+
- **Client Router (`public/js/bluebird-client.js`)**:
|
|
377
|
+
- Native `document.startViewTransition()` page navigation.
|
|
378
|
+
- Outlet-aware swaps via `[data-bb-outlet]` without layout flickering.
|
|
379
|
+
- Preserved elements via `data-persist="true"`.
|
|
380
|
+
|
|
381
|
+
```javascript
|
|
382
|
+
// app/views/dashboard.js
|
|
383
|
+
import { html } from "@seip/bluebird-js/core/html.js";
|
|
384
|
+
|
|
385
|
+
export const layout = "main";
|
|
386
|
+
export const head = (data) => ({ title: `Dashboard — ${data.user.name}` });
|
|
387
|
+
|
|
388
|
+
export default function DashboardView({ user, metrics }) {
|
|
389
|
+
const initial = metrics?.unread || 0;
|
|
390
|
+
|
|
391
|
+
return html`
|
|
392
|
+
<section class="dashboard-grid">
|
|
393
|
+
<h1>Welcome back, ${user.name}</h1>
|
|
394
|
+
|
|
395
|
+
<div class="card">
|
|
396
|
+
<button id="btnDec" class="btn-sm">-</button>
|
|
397
|
+
<span id="counter" class="font-bold">${initial}</span>
|
|
398
|
+
<button id="btnInc" class="btn-sm">+</button>
|
|
399
|
+
</div>
|
|
400
|
+
</section>
|
|
401
|
+
|
|
402
|
+
<!-- Native vanilla inline script: simple, readable, fast -->
|
|
403
|
+
<script>
|
|
404
|
+
(() => {
|
|
405
|
+
let count = ${initial};
|
|
406
|
+
const el = document.getElementById("counter");
|
|
407
|
+
document.getElementById("btnInc")?.addEventListener("click", () => {
|
|
408
|
+
count++;
|
|
409
|
+
if (el) el.textContent = count;
|
|
410
|
+
});
|
|
411
|
+
document.getElementById("btnDec")?.addEventListener("click", () => {
|
|
412
|
+
if (count > 0) count--;
|
|
413
|
+
if (el) el.textContent = count;
|
|
414
|
+
});
|
|
415
|
+
})();
|
|
416
|
+
</script>
|
|
417
|
+
`;
|
|
418
|
+
}
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
## 17. AI Development Guidelines
|
|
422
|
+
|
|
423
|
+
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()`.
|
|
424
|
+
2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
|
|
425
|
+
3. **No inline comments**: Preserve code cleanliness. Use **ONLY JSDoc comments** (`/** ... */`).
|
|
426
|
+
4. **All documentation in English**.
|