@seip/bluebird-js 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/AGENTS.md +726 -620
  2. package/README.md +615 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +54 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/terms.html +46 -0
  8. package/app/resources/index.html +27 -0
  9. package/app/resources/layouts/AppLayout.jsx +89 -0
  10. package/app/resources/main.jsx +18 -0
  11. package/app/resources/pages/Dashboard.jsx +98 -0
  12. package/app/resources/pages/Home.jsx +140 -0
  13. package/app/resources/pages/Login.jsx +35 -0
  14. package/app/resources/pages/NotFound.jsx +16 -0
  15. package/app/resources/pages/Register.jsx +55 -0
  16. package/app/resources/routes.jsx +54 -0
  17. package/app/resources/spa.js +67 -0
  18. package/app/resources/styles.css +9 -0
  19. package/app/routes/api.js +85 -50
  20. package/app/routes/auth.js +209 -0
  21. package/app/routes/web.js +59 -47
  22. package/core/ai.js +30 -10
  23. package/core/app.d.ts +2 -18
  24. package/core/app.js +987 -801
  25. package/core/auth.d.ts +2 -13
  26. package/core/auth.js +444 -326
  27. package/core/cli/build.js +37 -0
  28. package/core/cli/dev.js +155 -0
  29. package/core/cli/doctor.js +37 -2
  30. package/core/cli/export.js +191 -0
  31. package/core/cli/init.js +91 -322
  32. package/core/cli/nginx.js +1 -1
  33. package/core/cli/templates.js +139 -0
  34. package/core/cli/view.js +98 -161
  35. package/core/config.js +44 -2
  36. package/core/csrf.js +156 -24
  37. package/core/database.js +1184 -1131
  38. package/core/debug.js +1 -1
  39. package/core/html.js +8 -1
  40. package/core/index.d.ts +126 -310
  41. package/core/paths.js +55 -0
  42. package/core/ratelimit.js +10 -1
  43. package/core/react/client/api.js +237 -0
  44. package/core/react/client/auth.js +236 -0
  45. package/core/react/client/components.js +1321 -0
  46. package/core/react/client/i18n.js +338 -0
  47. package/core/react/client/index.d.ts +249 -0
  48. package/core/react/client/index.js +49 -0
  49. package/core/react/client/router.js +26 -0
  50. package/core/react/client/theme.css +512 -0
  51. package/core/render-cache.js +250 -212
  52. package/core/render.d.ts +25 -21
  53. package/core/render.js +738 -736
  54. package/core/router.d.ts +2 -3
  55. package/core/router.js +171 -171
  56. package/core/seo.js +10 -0
  57. package/core/spa.js +599 -0
  58. package/core/view-loader.js +155 -613
  59. package/core/vite-plugin.d.ts +18 -0
  60. package/core/vite-plugin.js +162 -0
  61. package/core/vite.js +250 -145
  62. package/index.js +22 -18
  63. package/jsconfig.json +5 -3
  64. package/package.json +114 -92
  65. package/production.md +8 -3
  66. package/public/js/bluebird.js +1160 -0
  67. package/templates/_auth/app/database.js +19 -0
  68. package/templates/_auth/app/models/user.js +22 -0
  69. package/templates/_auth/app/routes/auth-router.js +304 -0
  70. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  71. package/templates/_base/app/resources/html/notFound.html +14 -0
  72. package/templates/_base/app/resources/index.html +27 -0
  73. package/templates/_base/app/resources/styles.css +9 -0
  74. package/templates/api/app/models/note.js +18 -0
  75. package/templates/api/app/routes/api.js +82 -0
  76. package/templates/api/app/routes/auth.js +11 -0
  77. package/templates/api/index.js +19 -0
  78. package/templates/api/template.json +13 -0
  79. package/templates/auth/app/mail.js +11 -0
  80. package/templates/auth/app/models/password_reset.js +18 -0
  81. package/templates/auth/app/resources/html/home.html +21 -0
  82. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  83. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  84. package/templates/auth/app/resources/main.jsx +18 -0
  85. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  86. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  87. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  88. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  89. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  90. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  91. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  92. package/templates/auth/app/resources/routes.jsx +54 -0
  93. package/templates/auth/app/resources/spa.js +29 -0
  94. package/templates/auth/app/routes/api.js +17 -0
  95. package/templates/auth/app/routes/auth.js +13 -0
  96. package/templates/auth/app/routes/web.js +21 -0
  97. package/templates/auth/index.js +19 -0
  98. package/templates/auth/template.json +15 -0
  99. package/templates/blank/app/models/.gitkeep +0 -0
  100. package/templates/blank/app/resources/html/home.html +27 -0
  101. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  102. package/templates/blank/app/resources/main.jsx +16 -0
  103. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  104. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  105. package/templates/blank/app/resources/routes.jsx +15 -0
  106. package/templates/blank/app/resources/spa.js +24 -0
  107. package/templates/blank/app/routes/api.js +11 -0
  108. package/templates/blank/app/routes/web.js +21 -0
  109. package/templates/blank/index.js +13 -0
  110. package/templates/blank/template.json +12 -0
  111. package/templates/blog/app/lib/blog.js +149 -0
  112. package/templates/blog/app/models/post.js +22 -0
  113. package/templates/blog/app/resources/html/home.html +28 -0
  114. package/templates/blog/app/resources/html/not-found.html +5 -0
  115. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  116. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  117. package/templates/blog/app/resources/html/post.html +8 -0
  118. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  119. package/templates/blog/app/resources/main.jsx +18 -0
  120. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  121. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  122. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  123. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  124. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  125. package/templates/blog/app/resources/routes.jsx +51 -0
  126. package/templates/blog/app/resources/spa.js +25 -0
  127. package/templates/blog/app/resources/styles.css +40 -0
  128. package/templates/blog/app/routes/api.js +77 -0
  129. package/templates/blog/app/routes/auth.js +10 -0
  130. package/templates/blog/app/routes/web.js +114 -0
  131. package/templates/blog/index.js +21 -0
  132. package/templates/blog/template.json +14 -0
  133. package/vite.config.js +11 -0
  134. package/app/views/components/Header.jsx +0 -42
  135. package/app/views/components/LiveCounter.jsx +0 -67
  136. package/app/views/layouts/main/view.jsx +0 -201
  137. package/app/views/legal/terms.html +0 -29
  138. package/app/views/pages/about.jsx +0 -98
  139. package/app/views/pages/dashboard.jsx +0 -278
  140. package/app/views/pages/index.jsx +0 -123
  141. package/app/views/pages/login.jsx +0 -141
  142. package/core/actions.d.ts +0 -4
  143. package/core/actions.js +0 -355
  144. package/core/jsx.d.ts +0 -38
  145. package/core/jsx.js +0 -1597
  146. package/core/vite.d.ts +0 -3
  147. package/public/js/bluebird-client.js +0 -3265
  148. package/public/js/tailwind.js +0 -8
package/README.md CHANGED
@@ -1,607 +1,615 @@
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.
1
+ # Bluebird.js Framework
2
+
3
+ **Performance-first Node.js framework: Express + HTML `{{ }}` SSR templates + React Router SPA with Vite, Tailwind CSS v4, JWT auth with roles, 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+). Public landings and SEO pages render cleanly on the server with **HTML `{{ }}` templates** (`app/resources/html/`), while interactive dashboards and web applications run as **client-rendered React 19 + React Router SPAs** mounted via `router.spa()`, bundled with Vite and styled with Tailwind CSS v4 (dark and light themes). It ships with JWT authentication (with optional role checks and `/api/auth/*` routes), vanilla HTML UI helpers (`public/js/bluebird.js`), Tailwind React components, multi-driver caching (in-memory LRU, filesystem, and Redis), BaseModel with smart migrations, CSRF protection, background queues, and PM2 production clustering.
14
+
15
+ ### Key Highlights
16
+
17
+ - **HTML `{{ }}` SSR Engine:** Fast `.html` views, layouts (`{{{ body }}}`), partials (`{{> name }}`), `{{if}}`/`{{else}}`, `{{each}}`, raw `{{{ html }}}`, and `{{ vite "app/resources/styles.css" }}`, and `\{{ literal }}` escapes.
18
+ - **React Router SPA (`router.spa()`):** Serves the React shell `app/resources/index.html` with per-URL SEO metadata (`title`, `description`, `keywords`, `canonical`, Open Graph, `robots`, `jsonld`), custom scripts/styles, and a full-width anti-CLS skeleton inside `<div id="root">`.
19
+ - **One React Codebase, Web + Desktop + Mobile:** Zero server-injected props in the SPA — React talks directly to `/api/*` via `api()`. `npx bluebird-js export` turns the same code into a 100% static HTML/JS/CSS build for Electron (`loadFile`), Capacitor, or any static host, with bearer-token auth against your Bluebird API.
20
+ - **Vite & Tailwind CSS v4:** Vite middleware HMR on the same port as Express in development; client bundle + manifest in `public/build/` via `npx bluebird-js build`. Built-in dark and light theme synchronization.
21
+ - **AuthProvider & Role Guards:** Client `AuthProvider`, `useAuth()`, `RequireAuth` (with optional `roles`), `GuestOnly`, plus default `/api/auth/login`, `/logout`, `/me`, and optional `/register`.
22
+ - **UI Kits for Both Worlds:** React UI components (`Link`, `Button`, `Form`, `Input`, `Select`, `Textarea`, `Card`, `Badge`, `Carousel`, `Modal`, `Drawer`, `Skeleton`, `ThemeToggle`, `Toaster` / `toast`) and dependency-free vanilla `public/js/bluebird.js` (`data-carousel`, `data-toast`, `data-modal`, `data-dropdown`, `data-tabs`, `data-theme-toggle`, `data-form`).
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 (no native compilation), plus first-class `desktop: true` mode (`app.runDesktop()`) for read-only `.asar` bundles.
26
+ - **Decoupled Caching:** High-speed in-memory LRU cache by default, persistent filesystem fallback, and modular Redis support via `core/redis.js`.
27
+ - **Unified AI Client (`core/ai.js`):** Built-in client (no provider SDKs) 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.
28
+ - **Atomic Database Backups & Verification:** WAL-safe, non-blocking online SQLite snapshots using `VACUUM INTO` and gzip compression, with automated retention rotation (`--keep 10`, ordered by filename timestamp so same-millisecond backups never drop the newest one) and integrity-verified restore.
29
+ - **CSRF, Rate Limiting & Security:** Native HMAC-SHA256 signed CSRF protection (timing-safe, rotated on login/logout, never leaked through cached pages), built-in Rate Limiter (`rateLimit` in `App`, `App.rateLimit()`), secure-by-default CORS, CSP nonces (`'nonce-{nonce}'`) applied to every inline script/style, automatic `/sitemap.xml` & `/robots.txt` generation, and secure HTTP headers.
30
+ - **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`).
31
+
32
+ ---
33
+
34
+ ## Quick Start
35
+
36
+ ### 1. Requirements
37
+
38
+ - Node.js 22.18.0 or higher
39
+ - npm 10+
40
+
41
+ ### 2. Installation and Initialization
42
+
43
+ ```bash
44
+ npm install @seip/bluebird-js
45
+ npx bluebird-js
46
+ ```
47
+
48
+ The interactive CLI configures:
49
+ - Project title and port settings
50
+ - Project template (see below), `blank` by default
51
+ - Database engine: `sqlite` (default, built into Node.js), `mysql`, `postgres`, or `none`
52
+ - Connection credentials and database paths
53
+ - Automatic generation of `index.js`, `vite.config.js`, `.env`, `jsconfig.json`, `app/`, and `public/`
54
+
55
+ #### Project Templates
56
+
57
+ Pick a starting point with a flag (or answer the prompt). Every template starts clean, so there is nothing to delete before building your own app:
58
+
59
+ ```bash
60
+ npx bluebird-js # asks for the template (default: blank)
61
+ npx bluebird-js --blank # HTML {{ }} page on / + one-page React SPA on /app/*
62
+ npx bluebird-js --auth # + login, register, forgot/reset password, dashboard, profile
63
+ npx bluebird-js --blog # SEO blog (HTML list, posts, RSS, sitemap) + React admin on /app
64
+ npx bluebird-js --api # headless REST API: JWT auth (cookie or bearer) + CRUD example
65
+ npx bluebird-js --demo # full showcase used to develop the framework
66
+ npx bluebird-js --auth --yes --title "My App" # non-interactive
67
+ ```
68
+
69
+ | Template | Server | React (`/app`) | Database |
70
+ |---|---|---|---|
71
+ | `blank` | `/` HTML page, `/api/hello` | `Home.jsx` only | optional |
72
+ | `auth` | `/` landing, `/api/auth/*` (me, login, logout, register, forgot/reset password, profile, password), `/api/dashboard` | Login, Register, ForgotPassword, ResetPassword, Dashboard, Profile | required (tables created on first run) |
73
+ | `blog` | `/`, `/blog/:slug` (cached, JSON-LD), `/feed.xml`, posts in `/sitemap.xml`, `/api/posts` (admin) | Login, one-time admin Register, Posts, PostEditor | required |
74
+ | `api` | `/api/auth/*`, `/api/notes` (paginated, owner-scoped CRUD), no Vite | none | required |
75
+
76
+ - In `auth` and `api`, every new account gets the `user` role; promote admins yourself, e.g. in a seed: `await User.update(id, { role: "admin" })`. In `blog`, only the first account can register: it becomes the `admin` and registration closes.
77
+ - Sessions are checked against the database on every protected request (`Auth.configure({ resolveUser })`): changing or resetting the password signs out every other device (the current one gets a fresh token), `POST /api/auth/logout-all` signs out everywhere, deleted accounts lose access, and role changes apply immediately. Changing the sign-in email requires `current_password`.
78
+ - Password reset links are printed in the server console by `app/mail.js` until you plug in a mail provider there.
79
+ - Tables are created with `CREATE TABLE IF NOT EXISTS` at startup (`app/database.js`); use `make:migration` / `migrate` for later schema changes.
80
+ - Existing files are never overwritten, so the command is safe to run inside an existing folder.
81
+
82
+ Dependencies: `express`, `react`, `react-dom`, `react-router`, `vite`, `@vitejs/plugin-react`, `tailwindcss` and `@tailwindcss/vite` are installed with the framework; database drivers, Redis, uploads, WebSockets, Swagger and Helmet are optional (`npx bluebird-js add <module>`).
83
+
84
+ ### 3. Development Server
85
+
86
+ ```bash
87
+ npm run dev
88
+ ```
89
+
90
+ `npm run dev` runs `bluebird-js dev`: Express and Vite share one port, with React Fast Refresh and Tailwind CSS HMR for `app/resources/` (HTML `{{ }}` pages included). The server restarts when any server file under `app/` changes (routes, models, jobs, `app/lib/`...), or `index.js`, `.env`, `app/resources/spa.js`; client files in `app/resources/` hot-reload through Vite instead, and writes to `logs/`, `node_modules/`, or build output never restart it. Watch extra folders with `bluebird-js dev index.js --watch app/services`.
91
+
92
+ ### 4. Production Build
93
+
94
+ ```bash
95
+ npx bluebird-js build # Builds client SPA & Tailwind CSS bundle into public/build/
96
+ npm start
97
+ ```
98
+
99
+ ### 5. Static Export (Electron, Capacitor, static hosting)
100
+
101
+ ```bash
102
+ npx bluebird-js export --api https://api.example.com # dist/client/index.html + assets/
103
+ ```
104
+
105
+ ---
106
+
107
+ ## Project Structure
108
+
109
+ ```
110
+ project/
111
+ ├── index.js # Main application entrypoint
112
+ ├── vite.config.js # Optional Vite config (React, Tailwind, Bluebird plugins)
113
+ ├── app/
114
+ │ ├── resources/ # Everything client-side
115
+ │ │ ├── index.html # React SPA shell (router.spa() + npx bluebird-js export)
116
+ │ │ ├── spa.js # SPA config: mount, title, description, per-URL meta tree
117
+ │ │ ├── styles.css # Tailwind CSS v4 entry (shared by HTML SSR + React SPA)
118
+ │ │ ├── main.jsx # createRoot + AuthProvider + RouterProvider
119
+ │ │ ├── routes.jsx # createRouter + lazy routes
120
+ │ │ ├── layouts/AppLayout.jsx
121
+ │ │ ├── pages/ # Home.jsx, Login.jsx, Register.jsx, Dashboard.jsx, NotFound.jsx
122
+ │ │ └── html/ # HTML {{ }} SSR templates
123
+ │ │ ├── layouts/main.html
124
+ │ │ ├── partials/
125
+ │ │ ├── home.html
126
+ │ │ ├── terms.html
127
+ │ │ └── notFound.html (404 page for unknown routes)
128
+ │ ├── models/ # BaseModel definitions (user.js)
129
+ │ ├── routes/ # Express routes (web.js, auth.js, api.js)
130
+ │ └── jobs/ # Background worker job handlers
131
+ ├── public/ # Static assets (js/bluebird.js, images/, build/)
132
+ ├── core/ # Bluebird.js framework core
133
+ ├── database/ # SQLite storage and SQL migrations
134
+ ├── .env
135
+ └── package.json
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Core Features & Usage Examples
141
+
142
+ ### 1. Application Entrypoint (`index.js`)
143
+
144
+ ```javascript
145
+ import App from "@seip/bluebird-js/core/app.js";
146
+ import routerApi from "./app/routes/api.js";
147
+ import routerWeb from "./app/routes/web.js";
148
+
149
+ const app = new App({
150
+ routes: [routerWeb, routerApi],
151
+ port: process.env.PORT || 3000,
152
+ rateLimit: { max: 120, windowMs: 60000 },
153
+ });
154
+
155
+ app.run();
156
+ ```
157
+
158
+ For **Electron / Desktop** applications:
159
+
160
+ ```javascript
161
+ const app = new App({
162
+ desktop: true,
163
+ userDataPath: electronApp.getPath("userData"),
164
+ routes: [routerWeb, routerApi],
165
+ });
166
+
167
+ const { url, lanUrl } = await app.runDesktop({ allowLan: true });
168
+ mainWindow.loadURL(url);
169
+ ```
170
+
171
+ ---
172
+
173
+ ### 2. BaseModel & Smart Automatic Migrations (`app/models/`)
174
+
175
+ #### Defining a Model (`app/models/user.js`)
176
+
177
+ ```javascript
178
+ import Model from "@seip/bluebird-js/core/model.js";
179
+
180
+ export default class User extends Model {
181
+ static table = "users";
182
+ static primaryKey = "id";
183
+ static timestamps = true;
184
+ static softDelete = true;
185
+
186
+ static schema = {
187
+ id: { type: "int", primary: true, auto: true },
188
+ name: { type: "string", length: 150, required: true },
189
+ email: { type: "string", length: 150, unique: true, required: true, email: true },
190
+ password: { type: "string", length: 255, required: true, min: 8, hidden: true, hash: true },
191
+ role: { type: "string", length: 20, default: "user", in: ["user", "admin"] },
192
+ };
193
+ }
194
+ ```
195
+
196
+ #### Foreign Key References (`app/models/post.js`)
197
+
198
+ ```javascript
199
+ import Model from "@seip/bluebird-js/core/model.js";
200
+
201
+ export default class Post extends Model {
202
+ static table = "posts";
203
+ static schema = {
204
+ id: { type: "int", primary: true, auto: true },
205
+ title: { type: "string", length: 200, required: true },
206
+ content: { type: "text" },
207
+ author_id: { type: "int", references: "users.id", onDelete: "cascade" },
208
+ };
209
+ }
210
+ ```
211
+
212
+ #### Powerful Query Methods
213
+
214
+ ```javascript
215
+ const totalUsers = await User.count({ role: "user" });
216
+ const userExists = await User.exists({ email: "alice@example.com" });
217
+
218
+ const activeUsers = await User.all({
219
+ where: {
220
+ id: [1, 2, 3],
221
+ role: { $ne: "banned" },
222
+ views: { $gt: 100 },
223
+ },
224
+ });
225
+
226
+ const user = await User.firstOrCreate(
227
+ { email: "john@example.com" },
228
+ { name: "John Doe", role: "user" }
229
+ );
230
+
231
+ const updated = await User.updateOrCreate(
232
+ { email: "john@example.com" },
233
+ { name: "Johnathan Doe" }
234
+ );
235
+ ```
236
+
237
+ #### Smart Automatic Migrations CLI
238
+
239
+ When you create or modify models, simply run:
240
+
241
+ ```bash
242
+ npx bluebird-js make:migration
243
+ ```
244
+
245
+ 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:
246
+
247
+ ```
248
+ [INFO] Detected database schema changes:
249
+ + CREATE TABLE: users
250
+ + CREATE TABLE: posts
251
+ [OK] Migration created: database/migrations/20261022_120000_auto_migration.sql
252
+ ? Do you want to execute pending migrations now? (Y/n):
253
+ ```
254
+
255
+ To run migrations directly without prompts (ideal for CI/CD):
256
+ ```bash
257
+ npx bluebird-js migrate --yes
258
+ ```
259
+
260
+ ---
261
+
262
+ ### 3. HTML `{{ }}` SSR Rendering & React Router SPA (`router.spa()`)
263
+
264
+ Bluebird separates **server-rendered HTML pages** (landings, storefronts, marketing, legal pages) from **client-rendered React Router SPAs** (dashboards, admin panels, interactive apps).
265
+
266
+ #### 404 Pages
267
+
268
+ Unknown routes return JSON under `/api` (and for JSON clients), and for browsers render `app/resources/html/notFound.html` (with `{{ path }}`) inside the `main` layout, or a built-in page when that view does not exist. Inside a `router.spa()` mount the React `NotFound` page (`{ path: "*" }` in `routes.jsx`) handles them. Disable it with `new App({ notFound: false })`.
269
+
270
+ #### HTML `{{ }}` Templates (`app/resources/html/`)
271
+
272
+ ```javascript
273
+ // app/routes/web.js
274
+ import Router from "@seip/bluebird-js/core/router.js";
275
+ import Render from "@seip/bluebird-js/core/render.js";
276
+
277
+ const routerWeb = new Router("/", { seo: true });
278
+
279
+ routerWeb.get("/", (req, res) => {
280
+ const clientsHtml = clients.map((c) => `<span>${c.name}</span>`).join("");
281
+ return Render.html(
282
+ res,
283
+ "home",
284
+ { title: "Welcome", clientsHtml, slides },
285
+ { layout: "main", cache: 300 }
286
+ );
287
+ });
288
+ ```
289
+
290
+ ```html
291
+ <!-- app/resources/html/home.html -->
292
+ <section>
293
+ <h1>{{ title }}</h1>
294
+ <div>{{{ clientsHtml }}}</div>
295
+ {{#if slides}}
296
+ <div data-carousel data-autoplay="5000">
297
+ <div data-carousel-track>
298
+ {{#each slides}}<div data-carousel-slide>{{ title }}</div>{{/each}}
299
+ </div>
300
+ <div data-carousel-dots></div>
301
+ </div>
302
+ {{/if}}
303
+ </section>
304
+ ```
305
+
306
+ #### React Router SPA (`router.spa()`)
307
+
308
+ The SPA config lives in `app/resources/spa.js`, so the web server and the static export share the same title, description, and meta tree. `router.spa()` renders the React shell `app/resources/index.html` with per-URL SEO tags, JSON-LD, canonical links, custom scripts/styles, and a full-width inline skeleton inside `<div id="root">`:
309
+
310
+ ```javascript
311
+ // app/resources/spa.js
312
+ export default {
313
+ mount: "/app",
314
+ lang: "en",
315
+ titleTemplate: "%s — My App",
316
+ skeleton: "app",
317
+ meta: {
318
+ "*": { title: "Workspace", robots: "noindex, nofollow", skeleton: "app" },
319
+ "/": { title: "Explore", description: "Interactive workspace", robots: "index, follow", skeleton: "page" },
320
+ "login": { title: "Sign In", keywords: "login, auth", skeleton: "auth", jsonld: { "@type": "WebPage" } },
321
+ "/app/register": { title: "Register", skeleton: "auth" },
322
+ },
323
+ };
324
+ ```
325
+
326
+ ```javascript
327
+ // app/routes/web.js
328
+ import spa from "../resources/spa.js";
329
+
330
+ routerWeb.spa(spa.mount, spa);
331
+ ```
332
+
333
+ Keys inside `meta` accept both relative (`"login"`) and absolute (`"/app/login"`) formats, dynamic functions `(req, params) => ({ ... })`, and `"*"` wildcard defaults. The React entry defaults to `app/resources/main.jsx` and the shell to `app/resources/index.html` (`template: false` uses the built-in shell).
334
+
335
+ The React shell (`app/resources/index.html`) and the HTML SSR layout (`app/resources/html/layouts/main.html`) are separate files on purpose: the first one is also the entry of the static export.
336
+
337
+ #### Design System & Theming
338
+
339
+ Bluebird ships a neutral, shadcn-style design system shared by React components and HTML `{{ }}` views. The Vite plugin injects it right after `@import "tailwindcss"` in your stylesheet, so there is nothing to import:
340
+
341
+ - **Tokens** (light and dark): `background`, `foreground`, `card`, `popover`, `primary`, `secondary`, `muted`, `accent`, `destructive`, `border`, `input`, `ring`, `brand`, `success`, `warning`, `info`, used as Tailwind utilities (`bg-primary`, `text-muted-foreground`, `border-border`...).
342
+ - **Component classes** for plain HTML: `btn` + `btn-primary | btn-secondary | btn-outline | btn-ghost | btn-danger | btn-link` + `btn-sm | btn-lg | btn-icon`, `card` / `card-title` / `card-description`, `field` / `field-label` / `field-hint` / `field-error`, `badge` / `badge-dot`, `nav-link` (active with `aria-current="page"`), `glass`, `bg-app`, and `brand`.
343
+ - **Color is used sparingly**: `primary` (near-black in light, near-white in dark) for the main action, `secondary`/`outline`/`ghost` for the rest, `danger` for destructive actions, and `brand` only for the logo. Badges and toasts stay neutral with a small colored dot for the tone.
344
+
345
+ ```html
346
+ <a href="/app" class="btn btn-primary">Open app</a>
347
+ <button class="btn btn-outline btn-sm">Cancel</button>
348
+ <span class="badge"><span class="badge-dot bg-success"></span>Live</span>
349
+ ```
350
+
351
+ ```jsx
352
+ import { Button, Link, buttonVariants } from "@seip/bluebird-js/react";
353
+
354
+ <Button variant="danger" size="sm">Delete</Button>
355
+ <Link to="/new" className={buttonVariants({ variant: "outline" })}>New post</Link>
356
+ ```
357
+
358
+ Customize it by overriding the variables in `app/resources/styles.css` (your values win over the defaults), or turn the injection off with `bluebird({ theme: false })` in `vite.config.js`:
359
+
360
+ ```css
361
+ :root { --primary: oklch(0.55 0.2 264); --primary-foreground: oklch(0.98 0 0); --brand: oklch(0.65 0.2 30); }
362
+ .dark { --primary: oklch(0.7 0.16 264); --primary-foreground: oklch(0.15 0 0); }
363
+ ```
364
+
365
+ #### Component Languages (i18n)
366
+
367
+ Built-in UI strings (toast badges, close buttons, carousel controls, loading and error fallbacks, theme toggle labels) follow the page language from `<html lang>`: `{{ lang }}` in HTML views and `lang` in `app/resources/spa.js` for the React SPA. English, Spanish, Portuguese, French, German, and Italian are included; regional tags fall back to their base language (`es-AR` uses `es`) and unknown languages fall back to English. In Spanish, `toast.success()` shows **Correcto**, `toast.warning()` **Cuidado**, and `toast.error()` **Error**.
368
+
369
+ ```jsx
370
+ import { addMessages, setLocale, useLocale } from "@seip/bluebird-js/react";
371
+
372
+ addMessages("es", { "toast.warning": "Atención" });
373
+ addMessages("ja", { "toast.success": "成功", "toast.warning": "注意", "toast.error": "エラー" });
374
+ setLocale("es");
375
+
376
+ const { locale, t } = useLocale();
377
+ t("carousel.status", { n: 2, total: 5 });
378
+ ```
379
+
380
+ HTML views get the same strings from `public/js/bluebird.js` through `Bluebird.i18n.t()`, `Bluebird.i18n.addMessages()`, and `Bluebird.i18n.setLocale()`. A custom `badge` on a toast always wins over the translated label.
381
+
382
+ #### Client React API (`@seip/bluebird-js/react`) & Auth
383
+
384
+ ```jsx
385
+ // app/resources/main.jsx
386
+ import { createRoot } from "react-dom/client";
387
+ import { RouterProvider } from "react-router/dom";
388
+ import { AuthProvider, Toaster } from "@seip/bluebird-js/react";
389
+ import "./styles.css";
390
+ import { router } from "./routes.jsx";
391
+
392
+ createRoot(document.getElementById("root")).render(
393
+ <AuthProvider>
394
+ <RouterProvider router={router} />
395
+ <Toaster />
396
+ </AuthProvider>
397
+ );
398
+ ```
399
+
400
+ ```jsx
401
+ // app/resources/routes.jsx
402
+ import { createRouter } from "@seip/bluebird-js/react";
403
+
404
+ export const router = createRouter(routes, { basename: "/app" });
405
+ ```
406
+
407
+ - **Router**: `createRouter()` uses `createBrowserRouter` (with `basename`) on the server and `createHashRouter` in static exports or under `file://`.
408
+ - **Auth hooks & route guards**: `useAuth()` (`user`, `loading`, `authenticated`, `registerEnabled`, `login`, `register`, `logout`, `refresh`, `hasRole`), `<RequireAuth roles={["admin"]} />` (optional `roles` — without `roles`, any signed-in user passes), and `<GuestOnly />`.
409
+ - **REST helper**: `api.get/post/put/patch/delete(url, body)` sends `X-CSRF-Token` (cookie sessions) or `Authorization: Bearer` (token mode), parses JSON, and normalizes `Validator` errors into `ApiError.errors`. Configure with `configureApi({ baseUrl, auth: "cookie" | "token" })`.
410
+ - **UI Components (Light + Dark Tailwind)**: `Link`, `Button`, `Form`, `SubmitButton`, `Input`, `Textarea`, `Select`, `Card`, `Badge`, `Carousel`, `Modal`, `Drawer`, `Skeleton`, `PageSkeleton`, `ProgressBar`, `Spinner`, `ThemeToggle`, `useTheme`, `Toaster` / `toast`, `cn()`.
411
+ - **Vanilla Browser Helpers (`public/js/bluebird.js`)**: `data-carousel`, `data-toast`, `data-modal` / `data-modal-open`, `data-dropdown`, `data-tabs`, `data-theme-toggle`, `data-copy`, `data-confirm`, `data-password-toggle`, and `form[data-form]`.
412
+
413
+ #### Role-Protected Backend & Optional Register (`app/routes/auth.js`)
414
+
415
+ ```javascript
416
+ import Auth from "@seip/bluebird-js/core/auth.js";
417
+ import { createAuthRouter } from "./app/routes/auth.js";
418
+
419
+ const routerAuth = createAuthRouter({ register: true });
420
+
421
+ routerApi.get("/profile", Auth.protect(), (req, res) => res.ok({ user: req.user }));
422
+ routerApi.get("/admin/stats", Auth.protect({ roles: "admin" }), (req, res) => res.ok({ ok: true }));
423
+ ```
424
+
425
+ The auth and API routers apply `Csrf.middleware()`. Browser sessions use an HttpOnly cookie; clients sending `X-Auth-Mode: token` (static exports) receive `{ user, token }` and authenticate with `Authorization: Bearer`, which is CSRF-exempt because it is never sent automatically by the browser.
426
+
427
+ #### Static Export: Electron, Capacitor & Static Hosting (`npx bluebird-js export`)
428
+
429
+ Builds the same React code, `index.html` shell, and `spa.js` metadata into a 100% static HTML/JS/CSS folder:
430
+
431
+ ```bash
432
+ npx bluebird-js export --api https://api.example.com # dist/client (hash router, ./ assets)
433
+ npx bluebird-js export --out mobile/www --api https://api.example.com
434
+ npx bluebird-js export --router browser --base / --out dist/web # static host with history fallback
435
+ ```
436
+
437
+ | Option | Default | Purpose |
438
+ |---|---|---|
439
+ | `--out <dir>` | `dist/client` | Output folder (refuses `app/`, `core/`, `public/`, or the project root) |
440
+ | `--api <url>` | `EXPORT_API_URL` or `APP_URL` | Base URL prepended by `api()` to `/api/*` |
441
+ | `--router <mode>` | `hash` | `hash` (works with `file://`), `browser`, or `memory` |
442
+ | `--base <path>` | `./` (`/` for browser) | Asset base URL |
443
+ | `--auth <mode>` | `token` | `token` (Bearer in `localStorage`) or `cookie` |
444
+ | `--config <file>` | `app/resources/spa.js` | SPA config module |
445
+ | `--no-public` | | Skip copying `public/` |
446
+
447
+ ```javascript
448
+ // Electron main process (static client, no embedded server)
449
+ mainWindow.loadFile(path.join(__dirname, "dist/client/index.html"));
450
+ ```
451
+
452
+ ```json
453
+ // capacitor.config.json
454
+ { "appId": "com.example.app", "appName": "Example", "webDir": "dist/client" }
455
+ ```
456
+
457
+ Use `isExported()` to hide web-only UI (for example links to HTML pages) inside the exported build. The embedded-server Electron mode (`desktop: true`) keeps working as before.
458
+
459
+ #### Development & Production
460
+
461
+ ```bash
462
+ npm run dev # bluebird-js dev: Express + Vite on one port (HMR + Tailwind v4), restarts on server file changes
463
+ npx bluebird-js build # Builds client SPA & Tailwind CSS bundle into public/build/
464
+ npm start # Production: serves public/build/.vite/manifest.json
465
+ npx bluebird-js export # Static React build for Electron, Capacitor, or static hosting
466
+ ```
467
+
468
+ ---
469
+
470
+ ### 4. Multi-Driver Caching (`core/cache.js`)
471
+
472
+ ```javascript
473
+ import Cache from "@seip/bluebird-js/core/cache.js";
474
+
475
+ await Cache.set("metrics", { activeUsers: 450 }, 60, { driver: "memory" });
476
+ const metrics = await Cache.get("metrics", { driver: "memory" });
477
+
478
+ await Cache.set("report", htmlContent, 300, { driver: "file" });
479
+ ```
480
+
481
+ HTML render caches (`Render.html(..., { cache: 300 })`, `Render.cache(300)`, `router.spa(..., { cache: 300 })`) are keyed by path. Query strings bypass the cache unless allowlisted (`cacheQuery: ["page"]` or `Render.cache(300, { query: ["page"] })`), preventing cache flooding. Cached pages restore each visitor's own CSRF token and CSP nonce.
482
+
483
+ #### Security Defaults (CORS & CSP)
484
+
485
+ ```javascript
486
+ const app = new App({
487
+ routes: [routerWeb, routerApi],
488
+ // "*" never reflects origins nor sends credentials. Credentialed CORS requires an allowlist:
489
+ cors: { origin: ["https://app.example.com"], credentials: true },
490
+ // {nonce} becomes a per-request nonce added to every inline <script>/<style> Bluebird renders:
491
+ security: { csp: "default-src 'self'; script-src 'self' 'nonce-{nonce}'" },
492
+ });
493
+ ```
494
+
495
+ ---
496
+
497
+ ### 5. Desktop Applications (Electron & Desktop Mode)
498
+
499
+ 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):
500
+
501
+ - **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.
502
+ - **Dynamic Port & LAN / QR Access:** Binds to dynamic port `0` and generates LAN URLs (`allowLan: true`) for companion mobile/QR code access.
503
+ - **Clean WAL Shutdown:** `await app.close()` truncates SQLite WAL and frees file locks cleanly on Windows/Mac/Linux.
504
+
505
+ ```bash
506
+ npx bluebird-js add electron
507
+ ```
508
+
509
+ The generated desktop scripts run `npx bluebird-js build` before `electron-builder`, so pages are served from the production build inside the `.asar` bundle.
510
+
511
+ Prefer a client-only desktop or mobile app that talks to a remote API? Use `npx bluebird-js export` (section 3) and load `dist/client/index.html` with `mainWindow.loadFile()` or Capacitor.
512
+
513
+ ---
514
+
515
+ ### 6. Unified AI Client (`core/ai.js`)
516
+
517
+ Built-in AI client (no provider SDKs required) supporting **DeepSeek (default)**, **Google Gemini**, and **OpenAI** with reversible PII data masking, 0ms prompt caching, sliding window rate limits, and JSON schema validation:
518
+
519
+ - **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"`).
520
+ - **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`.
521
+ - **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. Proxy headers are only trusted from local/private reverse proxies (`trustProxy` defaults to `"loopback, linklocal, uniquelocal"`; set it to your CDN hop count when needed), so clients cannot spoof them to bypass rate limits.
522
+ - **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.
523
+ - **0ms Prompt Cache Hit:** Computes cache hashes on *anonymized* prompts so multiple users querying identical prompt templates trigger an immediate $0 / 0ms Cache Hit.
524
+ - **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.
525
+
526
+ ```javascript
527
+ import AI, { ai } from "@seip/bluebird-js/core/ai.js";
528
+
529
+ const supportAi = new AI({
530
+ provider: "deepseek", // "deepseek" (default) | "gemini" | "openai" | "custom"
531
+ model: "deepseek-flash",
532
+ rateLimit: { minute: 6, day: 30 }, // Sliding window rate limit
533
+ cacheTtl: 3600, // Cache responses for 1 hour
534
+ });
535
+
536
+ routerApi.post("/support/reply", supportAi.protect(), async (req, res) => {
537
+ const result = await supportAi.ask("Draft a courteous support reply for this user:", {
538
+ data: {
539
+ name: "Maria Garcia",
540
+ email: "maria@example.com",
541
+ dni: "45123987",
542
+ issue: "I would like to update my billing details",
543
+ },
544
+ sensitiveKeys: ["name", "email", "dni"], // Masked before leaving server!
545
+ request: req, // Automatic IP rate limiting
546
+ json: true,
547
+ });
548
+
549
+ // result.text is returned fully restored with 'Maria Garcia' and 'maria@example.com'!
550
+ res.ok(result);
551
+ });
552
+
553
+ // Real-time streaming directly to client response via Server-Sent Events (SSE)
554
+ routerApi.post("/support/stream", async (req, res) => {
555
+ await supportAi.pipe(res, req.body.message, { sse: true, request: req });
556
+ });
557
+
558
+ // Or iterate chunks manually via async generator
559
+ for await (const chunk of supportAi.askStream("Explain quantum computing in simple terms")) {
560
+ process.stdout.write(chunk.text);
561
+ }
562
+ ```
563
+
564
+ ---
565
+
566
+ ### 7. Atomic Database Backups & Verification (`core/database.js`)
567
+
568
+ WAL-safe, non-blocking snapshots for SQLite using `VACUUM INTO` and gzip compression, with automated retention rotation and integrity-verified restore:
569
+
570
+ ```javascript
571
+ import Database from "@seip/bluebird-js/core/database.js";
572
+
573
+ // Atomic, WAL-safe gzip backup with retention rotation (keeps latest 10)
574
+ const backup = await Database.backup({ out: "database/backups", keep: 10, compress: true });
575
+
576
+ // Integrity-verified restore with pre-restore safety snapshot
577
+ await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.gz", {
578
+ safetyBackup: true,
579
+ verify: true,
580
+ });
581
+ ```
582
+
583
+ ---
584
+
585
+ ## Developer Tooling CLI
586
+
587
+ ```bash
588
+ npx bluebird-js [--blank|--auth|--blog|--api|--demo] # Scaffolds a project from a template (default: blank)
589
+ npx bluebird-js doctor # Diagnostic audit and HTTP smoke tests
590
+ npx bluebird-js make:model <Name> # Generates BaseModel class
591
+ npx bluebird-js make:route <name> [--auth] # Scaffolds REST route
592
+ npx bluebird-js make:view <name> [--partial|--layout] # Scaffolds an HTML {{ }} template view
593
+ npx bluebird-js build # Builds client SPA and Tailwind CSS bundle (public/build/)
594
+ npx bluebird-js export [--api url] [--out dir] # Static React export (Electron, Capacitor, static hosts)
595
+ npx bluebird-js make:migration [name] # Smart auto-migration from app/models/
596
+ npx bluebird-js make:migration --model <Model> # Generates migration for specific Model
597
+ npx bluebird-js migrate [--yes] # Executes pending migrations
598
+ npx bluebird-js migrate:status # Displays applied migration batches
599
+ npx bluebird-js migrate:rollback # Reverts latest migration batch
600
+ npx bluebird-js make:seed <name> # Creates database seed file
601
+ npx bluebird-js seed # Executes database seeds
602
+ npx bluebird-js db:backup [--keep 10] [--out dir] # Compressed WAL-safe database backup with retention rotation
603
+ npx bluebird-js dev [entry] [--watch dir] # Dev server (Vite HMR) restarting only on server file changes
604
+ npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
605
+ npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
606
+ npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
607
+ npx bluebird-js add electron # Scaffolds Electron desktop app & desktop.js
608
+ npx bluebird-js add <module> # Installs optional on-demand package
609
+ ```
610
+
611
+ ---
612
+
613
+ ## License
614
+
615
+ MIT License. Copyright (c) 2026 Seip25.