@seip/bluebird-js 0.1.5 → 0.1.7

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/README.md CHANGED
@@ -1,528 +1,607 @@
1
- # Bluebird.js Framework
2
-
3
- **Performance-first Node.js API and web framework with native JavaScript ESM, built-in Tailwind CSS, Inter fonts, declarative UI components, JWT auth, BaseModel, smart migrations, and multi-level caching.**
4
-
5
- [![npm version](https://img.shields.io/npm/v/@seip/bluebird-js.svg)](https://www.npmjs.com/package/@seip/bluebird-js)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
- [![Node.js Version](https://img.shields.io/badge/node-%3E%3D22.18.0-brightgreen.svg)](https://nodejs.org)
8
-
9
- ---
10
-
11
- ## Introduction
12
-
13
- Bluebird.js (`@seip/bluebird-js`) is a high-performance web and API framework built on Express (Node.js 22.18+). It provides native modern JavaScript ESM execution, built-in Tailwind CSS v4 runtime and Google Fonts (`Inter`), zero-build SSR with React/Next.js-style component tags, multi-driver caching (in-memory LRU by default with filesystem and Redis support), AES-256-GCM encrypted JWT authentication, BaseModel schema definitions with smart migrations, CSRF protection, background queues, and PM2 production clustering into a cohesive developer experience.
14
-
15
- ### Key Highlights
16
-
17
- - **Native Zero-Build React JSX & TSX SSR (`app/views/*.jsx`, `*.tsx`):** Compiles `.jsx` and TypeScript `.tsx` modules in memory via Node 22.18+ `module.registerHooks()` with zero temporary disk files, automatic TypeScript type stripping, and zero build steps.
18
- - **`<ErrorBoundary>` & Dynamic `<Head>` Hoisting:** Native JSX error boundary (`<ErrorBoundary fallback={...}>`) protects against subtree SSR errors, while `<Head>`, `<Title>`, and `<Meta>` automatically hoist metadata into the page head.
19
- - **Streaming SSR with `<Suspense>` & Instant Caching:** Chunked progressive rendering (`Render.stream()`) with fallback skeletons and seamless deferred template swapping, automatically caching assembled output for instant cache HITs.
20
- - **Client Components with `useAction` & `useActionState`:** Micro-reactive client runtime with standard hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `html` tagged templates), plus anti-CLS layout locking (`minHeight`, `minWidth`) and automatic button/form pending states.
21
- - **Declarative Auto-Routes from Views:** Export `const route`, `const cache`, `const middlewares`, `const layout`, and `const seo` directly from `app/views/*.jsx` or `*.tsx` to mount cached, protected web routes automatically (`noAutoDiscoverRoutes: true` in `new App()` to disable).
22
- - **Built-In Tailwind CSS & Inter Font:** Includes the official standalone Tailwind CSS runtime (`/js/tailwind.js`) and Google Fonts `Inter` by default with zero configuration or compilers.
23
- - **Smart Automatic Migrations:** CLI detects schema changes across `app/models/`, resolves foreign key dependencies topologically, generates consolidated `CREATE TABLE` / `ALTER TABLE ADD COLUMN` SQL files, and executes them with interactive terminal prompts.
24
- - **Lightweight BaseModel:** Static facade providing readable schemas, CRUD shortcuts, query operators (`IN`, `$gt`, `$like`), `count()`, `exists()`, `firstOrCreate()`, `updateOrCreate()`, smart relations without N+1 queries, soft deletes, and automatic query cache invalidation.
25
- - **Native SQLite & Desktop Mode (Electron/Tauri):** Uses Node's built-in `node:sqlite` driver with zero compilation overhead, plus first-class `desktop: true` mode (`app.runDesktop()`) for read-only `.asar` bundles.
26
- - **Comprehensive Client UI Kit:** Built-in `bluebird-client.js` with toasts, snackbars, drawers, command palette (`Ctrl+K`), responsive data tables, tabs, carousels, declarative forms (`data-bb-form`), and View Transitions SPA routing.
27
- - **Decoupled Caching:** High-speed in-memory LRU cache by default, persistent filesystem fallback, and modular Redis support via `core/redis.js`.
28
- - **CSRF, Rate Limiting & Security:** Native HMAC-SHA256 signed CSRF protection, built-in Rate Limiter (`rateLimit` in `App` or `App.rateLimit()`), automatic `/sitemap.xml` & `/robots.txt` generation, and secure HTTP headers.
29
- - **Production Ready:** Built-in PM2 clustering CLI (`npx bluebird-js make:ecosystem`), optimized Nginx generator (`npx bluebird-js nginx:conf`), and native runner (`npm start`).
30
-
31
- ---
32
-
33
- ## Quick Start
34
-
35
- ### 1. Requirements
36
-
37
- - Node.js 22.18.0 or higher
38
- - npm 10+
39
-
40
- ### 2. Installation and Initialization
41
-
42
- ```bash
43
- npm install @seip/bluebird-js
44
- npx bluebird-js
45
- ```
46
-
47
- The interactive CLI configures:
48
- - Project title and port settings
49
- - Database engine: `sqlite` (default, native zero-configuration), `mysql`, `postgres`, or `none`
50
- - Connection credentials and database paths
51
- - Automatic generation of `index.js`, `.env`, `jsconfig.json`, `app/`, and `public/`
52
-
53
- ### 3. Development Server
54
-
55
- ```bash
56
- npm run dev
57
- ```
58
-
59
- The server starts with Node's native file watcher (`--watch`) and loads `.env` automatically via `--env-file=.env`.
60
-
61
- ---
62
-
63
- ## Project Structure
64
-
65
- ```
66
- project/
67
- ├── index.js # Main application entrypoint
68
- ├── app/
69
- │ ├── models/ # BaseModel definitions
70
- │ │ ├── user.js # User model schema & methods
71
- │ │ └── post.js # Post model schema & relations
72
- │ ├── routes/ # Application routes
73
- │ │ ├── api.js # REST API routes
74
- │ │ └── web.js # HTML page routes
75
- │ ├── views/ # React JSX (.jsx) & JavaScript (.js) SSR views
76
- │ │ ├── components/ # Reusable JSX components (e.g. Header.jsx)
77
- │ │ ├── layouts/ # Shared page layouts (e.g. main/view.jsx)
78
- │ │ ├── index.jsx # Public home view (Auto-Route: /)
79
- │ │ ├── about.jsx # About page view (Auto-Route: /about)
80
- │ │ ├── login.jsx # Sign-in page view (Auto-Route: /login)
81
- │ │ └── dashboard.jsx # Protected dashboard view (Auto-Route: /dashboard)
82
- │ └── jobs/ # Background worker job handlers
83
- ├── public/ # Public static assets (CSS, JS, images, fonts)
84
- │ ├── js/
85
- │ │ ├── tailwind.js # Built-in Tailwind CSS runtime
86
- │ │ └── bluebird-client.js # Client UI kit, View Transitions & SPA router
87
- │ └── images/
88
- ├── core/ # Bluebird.js framework core
89
- ├── database/ # SQLite storage and SQL migrations
90
- │ └── migrations/ # Version-controlled SQL migrations
91
- ├── .env # Environment variables
92
- └── package.json
93
- ```
94
-
95
- ---
96
-
97
- ## Core Features & Usage Examples
98
-
99
- ### 1. Application Entrypoint (`index.js`)
100
-
101
- ```javascript
102
- import App from "@seip/bluebird-js/core/app.js";
103
- import routerApi from "./app/routes/api.js";
104
- import routerWeb from "./app/routes/web.js";
105
-
106
- const app = new App({
107
- routes: [routerWeb, routerApi],
108
- port: process.env.PORT || 3000,
109
- rateLimit: { max: 120, windowMs: 60000 },
110
- });
111
-
112
- app.run();
113
- ```
114
-
115
- For **Electron / Desktop** applications:
116
-
117
- ```javascript
118
- const app = new App({
119
- desktop: true,
120
- userDataPath: electronApp.getPath("userData"),
121
- routes: [routerWeb, routerApi],
122
- });
123
-
124
- const { url, lanUrl } = await app.runDesktop({ allowLan: true });
125
- mainWindow.loadURL(url);
126
- ```
127
-
128
- ---
129
-
130
- ### 2. BaseModel & Smart Automatic Migrations (`app/models/`)
131
-
132
- #### Defining a Model (`app/models/user.js`)
133
-
134
- ```javascript
135
- import Model from "@seip/bluebird-js/core/model.js";
136
-
137
- export default class User extends Model {
138
- static table = "users";
139
- static primaryKey = "id";
140
- static timestamps = true;
141
- static softDelete = true;
142
-
143
- static schema = {
144
- id: { type: "int", primary: true, auto: true },
145
- name: { type: "string", length: 150, required: true },
146
- email: { type: "string", length: 150, unique: true, required: true, email: true },
147
- password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
148
- role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
149
- };
150
- }
151
- ```
152
-
153
- #### Foreign Key References (`app/models/post.js`)
154
-
155
- ```javascript
156
- import Model from "@seip/bluebird-js/core/model.js";
157
-
158
- export default class Post extends Model {
159
- static table = "posts";
160
- static schema = {
161
- id: { type: "int", primary: true, auto: true },
162
- title: { type: "string", length: 200, required: true },
163
- content: { type: "text" },
164
- author_id: { type: "int", references: "users.id", onDelete: "cascade" },
165
- };
166
- }
167
- ```
168
-
169
- #### Powerful Query Methods
170
-
171
- ```javascript
172
- const totalUsers = await User.count({ role: "user" });
173
- const userExists = await User.exists({ email: "alice@example.com" });
174
-
175
- const activeUsers = await User.all({
176
- where: {
177
- id: [1, 2, 3],
178
- role: { $ne: "banned" },
179
- views: { $gt: 100 },
180
- },
181
- });
182
-
183
- const user = await User.firstOrCreate(
184
- { email: "john@example.com" },
185
- { name: "John Doe", role: "user" }
186
- );
187
-
188
- const updated = await User.updateOrCreate(
189
- { email: "john@example.com" },
190
- { name: "Johnathan Doe" }
191
- );
192
- ```
193
-
194
- #### Smart Automatic Migrations CLI
195
-
196
- When you create or modify models, simply run:
197
-
198
- ```bash
199
- npx bluebird-js make:migration
200
- ```
201
-
202
- Bluebird inspects your models in `app/models/`, connects to your database, sorts tables by foreign key dependencies topologically, and detects all missing tables and columns (`CREATE TABLE` and `ALTER TABLE ADD COLUMN`). It generates a consolidated SQL migration file and asks:
203
-
204
- ```
205
- [INFO] Detected database schema changes:
206
- + CREATE TABLE: users
207
- + CREATE TABLE: posts
208
- [OK] Migration created: database/migrations/20261022_120000_auto_migration.sql
209
- ? Do you want to execute pending migrations now? (Y/n):
210
- ```
211
-
212
- To run migrations directly without prompts (ideal for CI/CD):
213
- ```bash
214
- npx bluebird-js migrate --yes
215
- ```
216
-
217
- ---
218
-
219
- ### 3. React JSX SSR, Declarative Auto-Routes & `<Client>` Skeletons
220
-
221
- #### Default Tailwind CSS & Inter Typography
222
-
223
- The default layout (`app/views/layouts/main/view.jsx`) comes pre-wired with Google Fonts `Inter` and the standalone Tailwind CSS v4 runtime (`/js/tailwind.js`). You can write pure Tailwind utility classes immediately without running Vite, PostCSS, or Tailwind CLI.
224
-
225
- #### Native `.jsx` Views & Declarative Auto-Routes
226
-
227
- Bluebird compiles `.jsx` files in memory using Node's native module hooks (`core/jsx.js`)—no external bundler or disk temp files required. Even better, any view inside `app/views/` (excluding `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) can export its own route configuration (`route`, `cache`, `middlewares`, `layout`, `seo`) and `App` mounts it automatically on startup (pass `noAutoDiscoverRoutes: true` to `new App()` if you prefer manual registration only):
228
-
229
- ```jsx
230
- // app/views/components/Header.jsx
231
- export default function Header({ title, user, count = 0 }) {
232
- return (
233
- <header className="flex items-center justify-between p-6 border-b border-slate-800">
234
- <div>
235
- <h1 className="text-2xl font-bold text-slate-100">{title}</h1>
236
- <p className="text-sm text-slate-400">Welcome back, {user?.name || "Guest"}</p>
237
- </div>
238
- <span className="px-3 py-1 rounded-full text-xs font-semibold bg-sky-500/10 text-sky-400 border border-sky-500/20">
239
- Notifications: {count}
240
- </span>
241
- </header>
242
- );
243
- }
244
- ```
245
-
246
- ```jsx
247
- // app/views/dashboard.jsx
248
- import Auth from "@seip/bluebird-js/core/auth.js";
249
- import Actions from "@seip/bluebird-js/core/actions.js";
250
- import { Client } from "@seip/bluebird-js/core/jsx.js";
251
- import Header from "./components/Header.jsx";
252
- import LiveCounter from "./components/LiveCounter.js";
253
-
254
- export const route = "/dashboard";
255
- export const layout = "main";
256
- export const middlewares = [Auth.protect({ redirect: "/login" })];
257
- export const seo = false;
258
- export const head = (data) => ({ title: `Dashboard — ${data.user?.name || "Member"}` });
259
-
260
- // Server Actions: automatic CSRF, 16KB maxBytes guard, prototype pollution filter & Validator schema
261
- export const actions = {
262
- syncCount: Actions.define(
263
- {
264
- maxBytes: "16kb",
265
- schema: { count: { required: true, number: true } },
266
- },
267
- async ({ body, user }) => {
268
- return { syncedCount: Number(body.count), updatedBy: user?.email };
269
- }
270
- ),
271
- };
272
-
273
- export default async function DashboardView({ user, syncedCount = 7 }) {
274
- return (
275
- <>
276
- <Header title="Protected Dashboard" user={user} count={syncedCount} />
277
-
278
- <div className="space-y-6 mt-6">
279
- {/* Reusable imported Client component with persistent state & anti-CLS skeleton */}
280
- <Client
281
- component={LiveCounter}
282
- props={{ initial: syncedCount }}
283
- persistent={true}
284
- minHeight={56}
285
- skeleton={
286
- <div className="h-14 rounded-xl bg-slate-900 animate-pulse flex items-center px-4 text-xs text-slate-400">
287
- Loading interactive widget...
288
- </div>
289
- }
290
- />
291
- </div>
292
- </>
293
- );
294
- }
295
- ```
296
-
297
- #### Reactive Client Components & `useAction` (`LiveCounter.jsx`)
298
-
299
- Client components run in the browser using Bluebird's micro-reactive runtime with hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `useRef`, `html` tagged templates). You can invoke Server Actions or standard API endpoints and handle native DOM events with standard `event.preventDefault()`:
300
-
301
- ```jsx
302
- // app/views/components/LiveCounter.jsx
303
- import { useState, useEffect, useAction } from "@seip/bluebird-js/core/jsx.js";
304
- import { html } from "@seip/bluebird-js/core/html.js";
305
-
306
- export default function LiveCounter({ initial = 7, label = "Client Counter" }) {
307
- const [count, setCount] = useState(Number(initial) || 0);
308
- const [sync, isPending] = useAction("syncCount", {
309
- onSuccess(res) {
310
- window.toast?.({ title: "Synced", description: res.data.message });
311
- },
312
- });
313
-
314
- const actualizarDashboard = (event) => {
315
- event.preventDefault(); // Native DOM event support
316
- sync({ count }); // Dispatches Server Action with pending states
317
- };
318
-
319
- return html`
320
- <div class="h-14 rounded-xl border border-slate-800 bg-slate-950/90 px-4 flex items-center justify-between">
321
- <span class="text-xs text-slate-300">${label}: <strong class="text-sky-400 font-mono">${count}</strong></span>
322
- <div class="flex items-center gap-2">
323
- <button type="button" onClick=${() => setCount(count + 1)} class="px-2.5 py-1 bg-sky-500 rounded text-xs font-bold text-slate-950">+1</button>
324
- <button type="button" onClick=${actualizarDashboard} disabled=${isPending} class="px-2.5 py-1 bg-emerald-500/15 border border-emerald-500/30 rounded text-xs text-emerald-300">
325
- ${isPending ? "Syncing..." : "Sync Server Action"}
326
- </button>
327
- </div>
328
- </div>
329
- `;
330
- }
331
- ```
332
-
333
- #### `<ErrorBoundary>` & Dynamic `<Head>` Hoisting
334
-
335
- Catch rendering errors during SSR in subtrees and hoist metadata directly into the document `<head>`:
336
-
337
- ```jsx
338
- import { ErrorBoundary, Head, Title, Meta } from "@seip/bluebird-js/core/jsx.js";
339
-
340
- export default function ProfilePage({ user }) {
341
- return (
342
- <>
343
- <Head>
344
- <Title>Profile — {user.name}</Title>
345
- <Meta name="robots" content="noindex,nofollow" />
346
- </Head>
347
-
348
- <ErrorBoundary fallback={(err) => <div className="p-4 bg-red-950 text-red-400 rounded-xl">Error: {err.message}</div>}>
349
- <UserProfileWidget userId={user.id} />
350
- </ErrorBoundary>
351
- </>
352
- );
353
- }
354
- ```
355
-
356
- #### Streaming SSR with `<Suspense>` & Instant Cache HIT
357
-
358
- Stream progressive chunked HTML responses with immediate skeletons. If route cache is enabled (`cache: 60`), cache misses stream progressively while caching the assembled final HTML, and subsequent requests are served as **instant Cache HITs** without streaming overhead:
359
-
360
- ```jsx
361
- import { Suspense } from "@seip/bluebird-js/core/jsx.js";
362
-
363
- export const cache = 60; // Subsequent hits served instantly from RAM LRU
364
-
365
- export default function FeedPage() {
366
- return (
367
- <div>
368
- <h1>Live Activity</h1>
369
- <Suspense fallback={<div className="h-40 animate-pulse bg-slate-900 rounded-xl">Loading feed...</div>}>
370
- <AsyncFeedList />
371
- </Suspense>
372
- </div>
373
- );
374
- }
375
- ```
376
-
377
- #### Zero-Build TypeScript & TSX Support (`.tsx`, `.ts`)
378
-
379
- Write views and components directly in TypeScript. Bluebird strips type annotations natively in memory using Node's native module customization hooks with zero build steps and zero disk temp files:
380
-
381
- ```tsx
382
- // app/views/components/UserCard.tsx
383
- interface UserProps {
384
- id: number;
385
- name: string;
386
- role: "admin" | "member";
387
- }
388
-
389
- export default function UserCard({ id, name, role }: UserProps): any {
390
- return (
391
- <div className="user-card" data-id={id}>
392
- <strong>{name}</strong> <span>({role})</span>
393
- </div>
394
- );
395
- }
396
- ```
397
-
398
- ---
399
-
400
- ### 4. Built-in Client UI Kit (`public/js/bluebird-client.js`)
401
-
402
- Bluebird includes a lightweight, dependency-free client UI toolkit with Tailwind CSS styles built right into `public/js/bluebird-client.js`:
403
-
404
- #### Toasts & Snackbars
405
-
406
- ```javascript
407
- toast({
408
- title: "Profile Updated",
409
- description: "Your settings have been saved successfully.",
410
- type: "success",
411
- position: "top-right",
412
- duration: 4000,
413
- });
414
-
415
- snackbar({ message: "Network connection restored", type: "info" });
416
- ```
417
-
418
- Or trigger them declaratively via HTML attributes:
419
- ```html
420
- <button data-toast="Settings saved successfully!" data-toast-type="success">Save</button>
421
- <button data-snackbar="Item deleted" data-snackbar-type="error">Delete</button>
422
- ```
423
-
424
- #### Drawers & Mobile Navigation
425
-
426
- ```html
427
- <button data-drawer-target="cartDrawer">Open Cart</button>
428
-
429
- <div id="cartDrawer" class="hidden fixed top-0 right-0 h-full w-80 bg-slate-900 p-6 z-50">
430
- <button data-drawer-close="cartDrawer" class="text-slate-400">&times;</button>
431
- <h3>Shopping Cart</h3>
432
- </div>
433
- ```
434
-
435
- #### Responsive Data Table (`ResponsiveDataTable`)
436
-
437
- Transforms tables dynamically into touch-friendly cards on mobile devices:
438
-
439
- ```javascript
440
- new ResponsiveDataTable("usersTableContainer", {
441
- columns: [
442
- { key: "id", label: "ID", sortable: true },
443
- { key: "name", label: "Name", sortable: true },
444
- { key: "email", label: "Email" },
445
- { key: "role", label: "Role" },
446
- ],
447
- data: usersList,
448
- searchable: true,
449
- pagination: true,
450
- pageSize: 10,
451
- onEdit: (row) => editUser(row.id),
452
- onDelete: (row) => deleteUser(row.id),
453
- });
454
- ```
455
-
456
- #### Declarative SPA Forms (`data-bb-form`)
457
-
458
- ```html
459
- <form action="/api/profile" method="POST" data-bb-form="true">
460
- <input type="text" name="name" required />
461
- <button type="submit">Update</button>
462
- </form>
463
- ```
464
- Submissions are automatically handled via `fetch`, CSRF tokens are injected, and toasts/redirects are handled seamlessly via View Transitions.
465
-
466
- #### Declarative DOM Helpers
467
-
468
- - `data-copy="Text to copy"`: Copies text to clipboard on click.
469
- - `data-confirm="Are you sure?"`: Confirms before link navigation or button click.
470
- - `data-toggle="theme"`: Switches between dark and light modes and updates the `dark` class on `<html>`.
471
- - `data-password-toggle="passwordFieldId"`: Toggles password visibility.
472
- - `data-filter-target="tableId"`: Live filters rows or cards matching input value.
473
-
474
- ---
475
-
476
- ### 5. Multi-Driver Caching (`core/cache.js`)
477
-
478
- ```javascript
479
- import Cache from "@seip/bluebird-js/core/cache.js";
480
-
481
- await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
482
- const metrics = await Cache.get("metrics", { driver: "memory" });
483
-
484
- await Cache.set("report", htmlContent, 300, { driver: "file" });
485
- ```
486
-
487
- ---
488
-
489
- ### 6. Desktop Applications (Electron & Desktop Mode)
490
-
491
- Bluebird.js runs natively embedded inside **Electron** applications with ultra-fast boot (<200ms) and minimal RAM consumption (~25–40 MB vs ~300 MB with Nextron):
492
-
493
- - **Automatic Writable Paths:** Routes SQLite database, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`app.getPath("userData")`) to avoid read-only errors inside `.asar` archives.
494
- - **Dynamic Port & LAN / QR Access:** Binds to dynamic port `0` and generates LAN URLs (`allowLan: true`) for companion mobile/QR code access.
495
- - **Clean WAL Shutdown:** `await app.close()` truncates SQLite WAL and frees file locks cleanly on Windows/Mac/Linux.
496
-
497
- ```bash
498
- npx bluebird-js add electron
499
- ```
500
-
501
- ---
502
-
503
- ## Developer Tooling CLI
504
-
505
- ```bash
506
- npx bluebird-js doctor # Diagnostic audit and HTTP smoke tests
507
- npx bluebird-js make:model <Name> # Generates BaseModel class
508
- npx bluebird-js make:route <name> [--auth] # Scaffolds REST route
509
- npx bluebird-js make:view <name> [--ejs] # Scaffolds HTML/EJS template
510
- npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
511
- npx bluebird-js make:migration --model <Model> # Generates migration for specific Model
512
- npx bluebird-js migrate [--yes] # Executes pending migrations
513
- npx bluebird-js migrate:status # Displays applied migration batches
514
- npx bluebird-js migrate:rollback # Reverts latest migration batch
515
- npx bluebird-js make:seed <name> # Creates database seed file
516
- npx bluebird-js seed # Executes database seeds
517
- npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
518
- npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
519
- npx bluebird-js add electron # Scaffolds Electron desktop app & desktop.js
520
- npx bluebird-js add react-islands # Scaffolds React Islands, Vite & Client Router
521
- npx bluebird-js add <module> # Installs optional on-demand package
522
- ```
523
-
524
- ---
525
-
526
- ## License
527
-
528
- MIT License. Copyright (c) 2026 Seip25.
1
+ # Bluebird.js Framework
2
+
3
+ **Performance-first Node.js API and web framework with native JavaScript ESM, built-in Tailwind CSS, Inter fonts, declarative UI components, JWT auth, BaseModel, smart migrations, and multi-level caching.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@seip/bluebird-js.svg)](https://www.npmjs.com/package/@seip/bluebird-js)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+ [![Node.js Version](https://img.shields.io/badge/node-%3E%3D22.18.0-brightgreen.svg)](https://nodejs.org)
8
+
9
+ ---
10
+
11
+ ## Introduction
12
+
13
+ Bluebird.js (`@seip/bluebird-js`) is a high-performance web and API framework built on Express (Node.js 22.18+). It provides native modern JavaScript ESM execution, built-in Tailwind CSS v4 runtime and Google Fonts (`Inter`), zero-build SSR with React/Next.js-style component tags, multi-driver caching (in-memory LRU by default with filesystem and Redis support), AES-256-GCM encrypted JWT authentication, BaseModel schema definitions with smart migrations, CSRF protection, background queues, and PM2 production clustering into a cohesive developer experience.
14
+
15
+ ### Key Highlights
16
+
17
+ - **Native Zero-Build React JSX & TSX SSR (`app/views/*.jsx`, `*.tsx`):** Compiles `.jsx` and TypeScript `.tsx` modules in memory via Node 22.18+ `module.registerHooks()` with zero temporary disk files, automatic TypeScript type stripping, and zero build steps.
18
+ - **`<ErrorBoundary>` & Dynamic `<Head>` Hoisting:** Native JSX error boundary (`<ErrorBoundary fallback={...}>`) protects against subtree SSR errors, while `<Head>`, `<Title>`, and `<Meta>` automatically hoist metadata into the page head.
19
+ - **Streaming SSR with `<Suspense>` & Instant Caching:** Chunked progressive rendering (`Render.stream()`) with fallback skeletons and seamless deferred template swapping, automatically caching assembled output for instant cache HITs.
20
+ - **Client Components with `useAction` & `useActionState`:** Micro-reactive client runtime with standard hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `html` tagged templates), plus anti-CLS layout locking (`minHeight`, `minWidth`) and automatic button/form pending states.
21
+ - **Declarative Auto-Routes from Views:** Export `const route`, `const cache`, `const middlewares`, `const layout`, and `const seo` directly from `app/views/*.jsx` or `*.tsx` to mount cached, protected web routes automatically (`noAutoDiscoverRoutes: true` in `new App()` to disable).
22
+ - **Built-In Tailwind CSS & Inter Font:** Includes the official standalone Tailwind CSS runtime (`/js/tailwind.js`) and Google Fonts `Inter` by default with zero configuration or compilers.
23
+ - **Smart Automatic Migrations:** CLI detects schema changes across `app/models/`, resolves foreign key dependencies topologically, generates consolidated `CREATE TABLE` / `ALTER TABLE ADD COLUMN` SQL files, and executes them with interactive terminal prompts.
24
+ - **Lightweight BaseModel:** Static facade providing readable schemas, CRUD shortcuts, query operators (`IN`, `$gt`, `$like`), `count()`, `exists()`, `firstOrCreate()`, `updateOrCreate()`, smart relations without N+1 queries, soft deletes, and automatic query cache invalidation.
25
+ - **Native SQLite & Desktop Mode (Electron/Tauri):** Uses Node's built-in `node:sqlite` driver with zero compilation overhead, plus first-class `desktop: true` mode (`app.runDesktop()`) for read-only `.asar` bundles.
26
+ - **Comprehensive Client UI Kit:** Built-in `bluebird-client.js` with toasts, snackbars, drawers, command palette (`Ctrl+K`), responsive data tables, tabs, carousels, declarative forms (`data-bb-form`), and View Transitions SPA routing.
27
+ - **Decoupled Caching:** High-speed in-memory LRU cache by default, persistent filesystem fallback, and modular Redis support via `core/redis.js`.
28
+ - **Unified AI Client (`core/ai.js`):** Native zero-dependency client with DeepSeek default (`deepseek-flash`), Gemini 3.5/3.8, and OpenAI, featuring reversible PII data masking, 0ms prompt caching, sliding window rate limits ("Anti-Quiebra"), and JSON schema validation.
29
+ - **Atomic Database Backups & Verification:** WAL-safe, non-blocking online SQLite snapshots using `VACUUM INTO` and gzip compression, with automated retention rotation (`--keep 10`) and integrity-verified restore.
30
+ - **CSRF, Rate Limiting & Security:** Native HMAC-SHA256 signed CSRF protection, built-in Rate Limiter (`rateLimit` in `App` or `App.rateLimit()`), automatic `/sitemap.xml` & `/robots.txt` generation, and secure HTTP headers.
31
+ - **Production Ready:** Built-in PM2 clustering CLI (`npx bluebird-js make:ecosystem`), optimized Nginx generator (`npx bluebird-js nginx:conf`), and native runner (`npm start`).
32
+
33
+ ---
34
+
35
+ ## Quick Start
36
+
37
+ ### 1. Requirements
38
+
39
+ - Node.js 22.18.0 or higher
40
+ - npm 10+
41
+
42
+ ### 2. Installation and Initialization
43
+
44
+ ```bash
45
+ npm install @seip/bluebird-js
46
+ npx bluebird-js
47
+ ```
48
+
49
+ The interactive CLI configures:
50
+ - Project title and port settings
51
+ - Database engine: `sqlite` (default, native zero-configuration), `mysql`, `postgres`, or `none`
52
+ - Connection credentials and database paths
53
+ - Automatic generation of `index.js`, `.env`, `jsconfig.json`, `app/`, and `public/`
54
+
55
+ ### 3. Development Server
56
+
57
+ ```bash
58
+ npm run dev
59
+ ```
60
+
61
+ The server starts with Node's native file watcher (`--watch`) and loads `.env` automatically via `--env-file=.env`.
62
+
63
+ ---
64
+
65
+ ## Project Structure
66
+
67
+ ```
68
+ project/
69
+ ├── index.js # Main application entrypoint
70
+ ├── app/
71
+ │ ├── models/ # BaseModel definitions
72
+ │ │ ├── user.js # User model schema & methods
73
+ │ │ └── post.js # Post model schema & relations
74
+ │ ├── routes/ # Application routes
75
+ │ │ ├── api.js # REST API routes
76
+ │ │ └── web.js # HTML page routes
77
+ │ ├── views/ # React JSX (.jsx) & JavaScript (.js) SSR views
78
+ │ │ ├── components/ # Reusable JSX components (e.g. Header.jsx)
79
+ │ │ ├── layouts/ # Shared page layouts (e.g. main/view.jsx)
80
+ │ │ ├── index.jsx # Public home view (Auto-Route: /)
81
+ │ │ ├── about.jsx # About page view (Auto-Route: /about)
82
+ │ │ ├── login.jsx # Sign-in page view (Auto-Route: /login)
83
+ │ │ └── dashboard.jsx # Protected dashboard view (Auto-Route: /dashboard)
84
+ │ └── jobs/ # Background worker job handlers
85
+ ├── public/ # Public static assets (CSS, JS, images, fonts)
86
+ │ ├── js/
87
+ │ │ ├── tailwind.js # Built-in Tailwind CSS runtime
88
+ │ │ └── bluebird-client.js # Client UI kit, View Transitions & SPA router
89
+ │ └── images/
90
+ ├── core/ # Bluebird.js framework core
91
+ ├── database/ # SQLite storage and SQL migrations
92
+ │ └── migrations/ # Version-controlled SQL migrations
93
+ ├── .env # Environment variables
94
+ └── package.json
95
+ ```
96
+
97
+ ---
98
+
99
+ ## Core Features & Usage Examples
100
+
101
+ ### 1. Application Entrypoint (`index.js`)
102
+
103
+ ```javascript
104
+ import App from "@seip/bluebird-js/core/app.js";
105
+ import routerApi from "./app/routes/api.js";
106
+ import routerWeb from "./app/routes/web.js";
107
+
108
+ const app = new App({
109
+ routes: [routerWeb, routerApi],
110
+ port: process.env.PORT || 3000,
111
+ rateLimit: { max: 120, windowMs: 60000 },
112
+ });
113
+
114
+ app.run();
115
+ ```
116
+
117
+ For **Electron / Desktop** applications:
118
+
119
+ ```javascript
120
+ const app = new App({
121
+ desktop: true,
122
+ userDataPath: electronApp.getPath("userData"),
123
+ routes: [routerWeb, routerApi],
124
+ });
125
+
126
+ const { url, lanUrl } = await app.runDesktop({ allowLan: true });
127
+ mainWindow.loadURL(url);
128
+ ```
129
+
130
+ ---
131
+
132
+ ### 2. BaseModel & Smart Automatic Migrations (`app/models/`)
133
+
134
+ #### Defining a Model (`app/models/user.js`)
135
+
136
+ ```javascript
137
+ import Model from "@seip/bluebird-js/core/model.js";
138
+
139
+ export default class User extends Model {
140
+ static table = "users";
141
+ static primaryKey = "id";
142
+ static timestamps = true;
143
+ static softDelete = true;
144
+
145
+ static schema = {
146
+ id: { type: "int", primary: true, auto: true },
147
+ name: { type: "string", length: 150, required: true },
148
+ email: { type: "string", length: 150, unique: true, required: true, email: true },
149
+ password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
150
+ role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
151
+ };
152
+ }
153
+ ```
154
+
155
+ #### Foreign Key References (`app/models/post.js`)
156
+
157
+ ```javascript
158
+ import Model from "@seip/bluebird-js/core/model.js";
159
+
160
+ export default class Post extends Model {
161
+ static table = "posts";
162
+ static schema = {
163
+ id: { type: "int", primary: true, auto: true },
164
+ title: { type: "string", length: 200, required: true },
165
+ content: { type: "text" },
166
+ author_id: { type: "int", references: "users.id", onDelete: "cascade" },
167
+ };
168
+ }
169
+ ```
170
+
171
+ #### Powerful Query Methods
172
+
173
+ ```javascript
174
+ const totalUsers = await User.count({ role: "user" });
175
+ const userExists = await User.exists({ email: "alice@example.com" });
176
+
177
+ const activeUsers = await User.all({
178
+ where: {
179
+ id: [1, 2, 3],
180
+ role: { $ne: "banned" },
181
+ views: { $gt: 100 },
182
+ },
183
+ });
184
+
185
+ const user = await User.firstOrCreate(
186
+ { email: "john@example.com" },
187
+ { name: "John Doe", role: "user" }
188
+ );
189
+
190
+ const updated = await User.updateOrCreate(
191
+ { email: "john@example.com" },
192
+ { name: "Johnathan Doe" }
193
+ );
194
+ ```
195
+
196
+ #### Smart Automatic Migrations CLI
197
+
198
+ When you create or modify models, simply run:
199
+
200
+ ```bash
201
+ npx bluebird-js make:migration
202
+ ```
203
+
204
+ Bluebird inspects your models in `app/models/`, connects to your database, sorts tables by foreign key dependencies topologically, and detects all missing tables and columns (`CREATE TABLE` and `ALTER TABLE ADD COLUMN`). It generates a consolidated SQL migration file and asks:
205
+
206
+ ```
207
+ [INFO] Detected database schema changes:
208
+ + CREATE TABLE: users
209
+ + CREATE TABLE: posts
210
+ [OK] Migration created: database/migrations/20261022_120000_auto_migration.sql
211
+ ? Do you want to execute pending migrations now? (Y/n):
212
+ ```
213
+
214
+ To run migrations directly without prompts (ideal for CI/CD):
215
+ ```bash
216
+ npx bluebird-js migrate --yes
217
+ ```
218
+
219
+ ---
220
+
221
+ ### 3. React JSX SSR, Declarative Auto-Routes & `<Client>` Skeletons
222
+
223
+ #### Default Tailwind CSS & Inter Typography
224
+
225
+ The default layout (`app/views/layouts/main/view.jsx`) comes pre-wired with Google Fonts `Inter` and the standalone Tailwind CSS v4 runtime (`/js/tailwind.js`). You can write pure Tailwind utility classes immediately without running Vite, PostCSS, or Tailwind CLI.
226
+
227
+ #### Native `.jsx` Views & Declarative Auto-Routes
228
+
229
+ Bluebird compiles `.jsx` files in memory using Node's native module hooks (`core/jsx.js`)—no external bundler or disk temp files required. Even better, any view inside `app/views/` (excluding `layouts/`, `components/`, `partials/`, `islands/`, and `/api`) can export its own route configuration (`route`, `cache`, `middlewares`, `layout`, `seo`) and `App` mounts it automatically on startup (pass `noAutoDiscoverRoutes: true` to `new App()` if you prefer manual registration only):
230
+
231
+ ```jsx
232
+ // app/views/components/Header.jsx
233
+ export default function Header({ title, user, count = 0 }) {
234
+ return (
235
+ <header className="flex items-center justify-between p-6 border-b border-slate-800">
236
+ <div>
237
+ <h1 className="text-2xl font-bold text-slate-100">{title}</h1>
238
+ <p className="text-sm text-slate-400">Welcome back, {user?.name || "Guest"}</p>
239
+ </div>
240
+ <span className="px-3 py-1 rounded-full text-xs font-semibold bg-sky-500/10 text-sky-400 border border-sky-500/20">
241
+ Notifications: {count}
242
+ </span>
243
+ </header>
244
+ );
245
+ }
246
+ ```
247
+
248
+ ```jsx
249
+ // app/views/pages/dashboard.jsx
250
+ import Auth from "@seip/bluebird-js/core/auth.js";
251
+ import { action } from "@seip/bluebird-js/core/actions.js";
252
+ import { Script } from "@seip/bluebird-js/core/jsx.js";
253
+ import Header from "../components/Header.jsx";
254
+ import LiveCounter from "../components/LiveCounter.jsx";
255
+
256
+ export const route = "/dashboard";
257
+ export const layout = "main";
258
+ export const middlewares = [Auth.protect({ redirect: "/login" })];
259
+ export const seo = false;
260
+ export const head = (data) => ({ title: `Dashboard — ${data.user?.name || "Member"}` });
261
+
262
+ // Server Actions: automatic CSRF verification, 64KB maxBytes guard & prototype pollution sanitization
263
+ export const actions = {
264
+ // Direct plain async function with automatic security defaults
265
+ async syncCount({ body, user }) {
266
+ return { syncedCount: Number(body.count), updatedBy: user?.email };
267
+ },
268
+ };
269
+
270
+ export default async function DashboardView({ user, syncedCount = 7 }) {
271
+ return (
272
+ <>
273
+ <Header title="Protected Dashboard" user={user} count={syncedCount} />
274
+
275
+ <div className="space-y-6 mt-6">
276
+ {/* Direct JSX invocation with automatic anti-CLS skeleton */}
277
+ <LiveCounter initial={syncedCount} />
278
+ </div>
279
+
280
+ {/* Native JSX Script component */}
281
+ <Script data={{ initialCount: syncedCount }} onPageLoad>
282
+ {({ initialCount }) => {
283
+ console.log("Mounted dashboard with count:", initialCount);
284
+ return () => console.log("Cleanup on page transition");
285
+ }}
286
+ </Script>
287
+ </>
288
+ );
289
+ }
290
+ ```
291
+
292
+ #### Reactive Client Components & `useAction` (`LiveCounter.jsx`)
293
+
294
+ Client components run in the browser using Bluebird's zero-build runtime with pure React JSX and hooks (`useState`, `useEffect`, `useAction`, `useActionState`, `useRef`). Wrapping the component with `client(LiveCounter, options)` locks layout dimensions (`minHeight`) to prevent layout shifts and allows invoking it directly as a standard JSX tag:
295
+
296
+ ```jsx
297
+ // app/views/components/LiveCounter.jsx
298
+ import { useState, useAction, client } from "@seip/bluebird-js/core/jsx.js";
299
+
300
+ export function LiveCounter({ initial = 7, label = "Client Counter" }) {
301
+ const [count, setCount] = useState(Number(initial) || 0);
302
+
303
+ // useAction accepts action name string ("syncCount") or imported function reference
304
+ const [sync, isPending] = useAction("syncCount", {
305
+ onSuccess(res) {
306
+ window.toast?.({ title: "Synced", description: res.data?.message || "OK" });
307
+ },
308
+ });
309
+
310
+ return (
311
+ <div className="h-14 rounded-xl border border-slate-800 bg-slate-950/90 px-4 flex items-center justify-between">
312
+ <span className="text-xs text-slate-300">
313
+ {label}: <strong className="text-sky-400 font-mono">{count}</strong>
314
+ </span>
315
+ <div className="flex items-center gap-2">
316
+ <button
317
+ type="button"
318
+ onClick={() => setCount(count + 1)}
319
+ className="px-2.5 py-1 bg-sky-500 rounded text-xs font-bold text-slate-950"
320
+ >
321
+ +1
322
+ </button>
323
+ <button
324
+ type="button"
325
+ onClick={() => sync({ count })}
326
+ disabled={isPending}
327
+ className="px-2.5 py-1 bg-emerald-500/15 border border-emerald-500/30 rounded text-xs text-emerald-300"
328
+ >
329
+ {isPending ? "Syncing..." : "Sync Server Action"}
330
+ </button>
331
+ </div>
332
+ </div>
333
+ );
334
+ }
335
+
336
+ // Export wrapped with default anti-CLS minHeight & persistence options
337
+ export default client(LiveCounter, { minHeight: 56 });
338
+ ```
339
+
340
+ #### `<ErrorBoundary>` & Dynamic `<Head>` Hoisting
341
+
342
+ Catch rendering errors during SSR in subtrees and hoist metadata directly into the document `<head>`:
343
+
344
+ ```jsx
345
+ import { ErrorBoundary, Head, Title, Meta } from "@seip/bluebird-js/core/jsx.js";
346
+
347
+ export default function ProfilePage({ user }) {
348
+ return (
349
+ <>
350
+ <Head>
351
+ <Title>Profile — {user.name}</Title>
352
+ <Meta name="robots" content="noindex,nofollow" />
353
+ </Head>
354
+
355
+ <ErrorBoundary fallback={(err) => <div className="p-4 bg-red-950 text-red-400 rounded-xl">Error: {err.message}</div>}>
356
+ <UserProfileWidget userId={user.id} />
357
+ </ErrorBoundary>
358
+ </>
359
+ );
360
+ }
361
+ ```
362
+
363
+ #### Streaming SSR with `<Suspense>` & Instant Cache HIT
364
+
365
+ Stream progressive chunked HTML responses with immediate skeletons. If route cache is enabled (`cache: 60`), cache misses stream progressively while caching the assembled final HTML, and subsequent requests are served as **instant Cache HITs** without streaming overhead:
366
+
367
+ ```jsx
368
+ import { Suspense } from "@seip/bluebird-js/core/jsx.js";
369
+
370
+ export const cache = 60; // Subsequent hits served instantly from RAM LRU
371
+
372
+ export default function FeedPage() {
373
+ return (
374
+ <div>
375
+ <h1>Live Activity</h1>
376
+ <Suspense fallback={<div className="h-40 animate-pulse bg-slate-900 rounded-xl">Loading feed...</div>}>
377
+ <AsyncFeedList />
378
+ </Suspense>
379
+ </div>
380
+ );
381
+ }
382
+ ```
383
+
384
+ #### Zero-Build TypeScript & TSX Support (`.tsx`, `.ts`)
385
+
386
+ Write views and components directly in TypeScript. Bluebird strips type annotations natively in memory using Node's native module customization hooks with zero build steps and zero disk temp files:
387
+
388
+ ```tsx
389
+ // app/views/components/UserCard.tsx
390
+ interface UserProps {
391
+ id: number;
392
+ name: string;
393
+ role: "admin" | "member";
394
+ }
395
+
396
+ export default function UserCard({ id, name, role }: UserProps): any {
397
+ return (
398
+ <div className="user-card" data-id={id}>
399
+ <strong>{name}</strong> <span>({role})</span>
400
+ </div>
401
+ );
402
+ }
403
+ ```
404
+
405
+ ---
406
+
407
+ ### 4. Built-in Client UI Kit (`public/js/bluebird-client.js`)
408
+
409
+ Bluebird includes a lightweight, dependency-free client UI toolkit with Tailwind CSS styles built right into `public/js/bluebird-client.js`:
410
+
411
+ #### Toasts & Snackbars
412
+
413
+ ```javascript
414
+ toast({
415
+ title: "Profile Updated",
416
+ description: "Your settings have been saved successfully.",
417
+ type: "success",
418
+ position: "top-right",
419
+ duration: 4000,
420
+ });
421
+
422
+ snackbar({ message: "Network connection restored", type: "info" });
423
+ ```
424
+
425
+ Or trigger them declaratively via HTML attributes:
426
+ ```html
427
+ <button data-toast="Settings saved successfully!" data-toast-type="success">Save</button>
428
+ <button data-snackbar="Item deleted" data-snackbar-type="error">Delete</button>
429
+ ```
430
+
431
+ #### Drawers & Mobile Navigation
432
+
433
+ ```html
434
+ <button data-drawer-target="cartDrawer">Open Cart</button>
435
+
436
+ <div id="cartDrawer" class="hidden fixed top-0 right-0 h-full w-80 bg-slate-900 p-6 z-50">
437
+ <button data-drawer-close="cartDrawer" class="text-slate-400">&times;</button>
438
+ <h3>Shopping Cart</h3>
439
+ </div>
440
+ ```
441
+
442
+ #### Responsive Data Table (`ResponsiveDataTable`)
443
+
444
+ Transforms tables dynamically into touch-friendly cards on mobile devices:
445
+
446
+ ```javascript
447
+ new ResponsiveDataTable("usersTableContainer", {
448
+ columns: [
449
+ { key: "id", label: "ID", sortable: true },
450
+ { key: "name", label: "Name", sortable: true },
451
+ { key: "email", label: "Email" },
452
+ { key: "role", label: "Role" },
453
+ ],
454
+ data: usersList,
455
+ searchable: true,
456
+ pagination: true,
457
+ pageSize: 10,
458
+ onEdit: (row) => editUser(row.id),
459
+ onDelete: (row) => deleteUser(row.id),
460
+ });
461
+ ```
462
+
463
+ #### Declarative SPA Forms (`data-bb-form`)
464
+
465
+ ```html
466
+ <form action="/api/profile" method="POST" data-bb-form="true">
467
+ <input type="text" name="name" required />
468
+ <button type="submit">Update</button>
469
+ </form>
470
+ ```
471
+ Submissions are automatically handled via `fetch`, CSRF tokens are injected, and toasts/redirects are handled seamlessly via View Transitions.
472
+
473
+ #### Declarative DOM Helpers
474
+
475
+ - `data-copy="Text to copy"`: Copies text to clipboard on click.
476
+ - `data-confirm="Are you sure?"`: Confirms before link navigation or button click.
477
+ - `data-toggle="theme"`: Switches between dark and light modes and updates the `dark` class on `<html>`.
478
+ - `data-password-toggle="passwordFieldId"`: Toggles password visibility.
479
+ - `data-filter-target="tableId"`: Live filters rows or cards matching input value.
480
+
481
+ ---
482
+
483
+ ### 5. Multi-Driver Caching (`core/cache.js`)
484
+
485
+ ```javascript
486
+ import Cache from "@seip/bluebird-js/core/cache.js";
487
+
488
+ await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
489
+ const metrics = await Cache.get("metrics", { driver: "memory" });
490
+
491
+ await Cache.set("report", htmlContent, 300, { driver: "file" });
492
+ ```
493
+
494
+ ---
495
+
496
+ ### 6. Desktop Applications (Electron & Desktop Mode)
497
+
498
+ Bluebird.js runs natively embedded inside **Electron** applications with ultra-fast boot (<200ms) and minimal RAM consumption (~25–40 MB vs ~300 MB with Nextron):
499
+
500
+ - **Automatic Writable Paths:** Routes SQLite database, `logs/`, `app/cache/`, and file uploads (`Upload.storage()`) to `Config.userDataDir()` (`app.getPath("userData")`) to avoid read-only errors inside `.asar` archives.
501
+ - **Dynamic Port & LAN / QR Access:** Binds to dynamic port `0` and generates LAN URLs (`allowLan: true`) for companion mobile/QR code access.
502
+ - **Clean WAL Shutdown:** `await app.close()` truncates SQLite WAL and frees file locks cleanly on Windows/Mac/Linux.
503
+
504
+ ```bash
505
+ npx bluebird-js add electron
506
+ ```
507
+
508
+ ---
509
+
510
+ ### 7. Unified AI Client (`core/ai.js`)
511
+
512
+ Native zero-dependency AI client supporting **DeepSeek (default)**, **Google Gemini**, and **OpenAI** with reversible PII data masking, 0ms prompt caching, sliding window rate limits, and JSON schema validation:
513
+
514
+ - **DeepSeek by Default (`deepseek-flash`):** Default endpoint `https://api.deepseek.com`, served by DeepSeek-V4.1-Flash-1017 (legacy names `deepseek-v4-flash`, `deepseek-chat` supported). Optional thinking mode (`thinking: { type: "enabled" }`, `reasoningEffort: "high"`).
515
+ - **Google Gemini & OpenAI:** Built-in REST connectors for `gemini-3.5-flash`, `gemini-3.8-flash`, `gemini-2.5-flash`, `gpt-4o-mini`, and custom endpoints via `baseURL`.
516
+ - **Accurate Real IP Detection (`getClientIp`):** Resolves real visitor IPs across Cloudflare (`cf-connecting-ip`, `true-client-ip`), Nginx (`x-real-ip`), proxy chains (`x-forwarded-for`), and cleans IPv6 mappings.
517
+ - **Reversible PII Masking:** Replaces sensitive user keys (`name`, `email`, `dni`, etc.) with anonymous tokens (`[name_01]`, `[email_01]`) before transmission, restoring original values in responses.
518
+ - **0ms Prompt Cache Hit:** Computes cache hashes on *anonymized* prompts so multiple users querying identical prompt templates trigger an immediate $0 / 0ms Cache Hit.
519
+ - **Rate Limit Protection ("Anti-Quiebra"):** Configurable per-minute/per-day sliding windows (e.g. `{ minute: 6, day: 30 }`), returning clean HTTP 429 errors via `ai.protect()` middleware before depleting API budget.
520
+
521
+ ```javascript
522
+ import AI, { ai } from "@seip/bluebird-js/core/ai.js";
523
+
524
+ const supportAi = new AI({
525
+ provider: "deepseek", // "deepseek" (default) | "gemini" | "openai" | "custom"
526
+ model: "deepseek-flash",
527
+ rateLimit: { minute: 6, day: 30 }, // Sliding window rate limit
528
+ cacheTtl: 3600, // Cache responses for 1 hour
529
+ });
530
+
531
+ routerApi.post("/support/reply", supportAi.protect(), async (req, res) => {
532
+ const result = await supportAi.ask("Draft a courteous support reply for this user:", {
533
+ data: {
534
+ name: "Maria Garcia",
535
+ email: "maria@example.com",
536
+ dni: "45123987",
537
+ issue: "I would like to update my billing details",
538
+ },
539
+ sensitiveKeys: ["name", "email", "dni"], // Masked before leaving server!
540
+ request: req, // Automatic IP rate limiting
541
+ json: true,
542
+ });
543
+
544
+ // result.text is returned fully restored with 'Maria Garcia' and 'maria@example.com'!
545
+ res.ok(result);
546
+ });
547
+
548
+ // Real-time streaming directly to client response via Server-Sent Events (SSE)
549
+ routerApi.post("/support/stream", async (req, res) => {
550
+ await supportAi.pipe(res, req.body.message, { sse: true, request: req });
551
+ });
552
+
553
+ // Or iterate chunks manually via async generator
554
+ for await (const chunk of supportAi.askStream("Explain quantum computing in simple terms")) {
555
+ process.stdout.write(chunk.text);
556
+ }
557
+ ```
558
+
559
+ ---
560
+
561
+ ### 8. Atomic Database Backups & Verification (`core/database.js`)
562
+
563
+ WAL-safe, non-blocking snapshots for SQLite using `VACUUM INTO` and gzip compression, with automated retention rotation and integrity-verified restore:
564
+
565
+ ```javascript
566
+ import Database from "@seip/bluebird-js/core/database.js";
567
+
568
+ // Atomic, WAL-safe gzip backup with retention rotation (keeps latest 10)
569
+ const backup = await Database.backup({ out: "database/backups", keep: 10, compress: true });
570
+
571
+ // Integrity-verified restore with pre-restore safety snapshot
572
+ await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.gz", {
573
+ safetyBackup: true,
574
+ verify: true,
575
+ });
576
+ ```
577
+
578
+ ---
579
+
580
+ ## Developer Tooling CLI
581
+
582
+ ```bash
583
+ npx bluebird-js doctor # Diagnostic audit and HTTP smoke tests
584
+ npx bluebird-js make:model <Name> # Generates BaseModel class
585
+ npx bluebird-js make:route <name> [--auth] # Scaffolds REST route
586
+ npx bluebird-js make:view <name> [--ejs] # Scaffolds HTML/EJS template
587
+ npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
588
+ npx bluebird-js make:migration --model <Model> # Generates migration for specific Model
589
+ npx bluebird-js migrate [--yes] # Executes pending migrations
590
+ npx bluebird-js migrate:status # Displays applied migration batches
591
+ npx bluebird-js migrate:rollback # Reverts latest migration batch
592
+ npx bluebird-js make:seed <name> # Creates database seed file
593
+ npx bluebird-js seed # Executes database seeds
594
+ npx bluebird-js db:backup [--keep 10] [--out dir] # Compressed WAL-safe database backup with retention rotation
595
+ npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
596
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
597
+ npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
598
+ npx bluebird-js add electron # Scaffolds Electron desktop app & desktop.js
599
+ npx bluebird-js add react-islands # Scaffolds React Islands, Vite & Client Router
600
+ npx bluebird-js add <module> # Installs optional on-demand package
601
+ ```
602
+
603
+ ---
604
+
605
+ ## License
606
+
607
+ MIT License. Copyright (c) 2026 Seip25.