@seip/bluebird-js 0.1.5 → 0.1.6

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/AGENTS.md CHANGED
@@ -246,6 +246,21 @@ await connection.transaction(async (tx) => {
246
246
  const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
247
247
  await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
248
248
  });
249
+
250
+ // Atomic, WAL-safe compressed database backup with retention rotation
251
+ const backup = await Database.backup({ out: "database/backups", keep: 10, compress: true });
252
+
253
+ // Integrity-verified restore with pre-restore safety snapshot
254
+ await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.gz", {
255
+ safetyBackup: true,
256
+ verify: true,
257
+ });
258
+ ```
259
+
260
+ ## 11. On-Demand Modules & CLI Add
261
+ const id = await tx.query("INSERT INTO users (name) VALUES (?)", ["Alice"]);
262
+ await tx.query("INSERT INTO profiles (user_id) VALUES (?)", [id]);
263
+ });
249
264
  ```
250
265
 
251
266
  ## 11. On-Demand Modules & CLI Add
@@ -377,6 +392,8 @@ npx bluebird-js migrate:status # Displays applied batches
377
392
  npx bluebird-js migrate:rollback # Reverts latest batch
378
393
  npx bluebird-js make:seed <name> # Database seed file creation
379
394
  npx bluebird-js seed # Executes database seeds
395
+ npx bluebird-js db:backup [--keep 10] [--out dir] # Compressed WAL-safe database backup with retention rotation
396
+ npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
380
397
  npx bluebird-js nginx:conf [domain] [port] [root] # Generates Host Nginx reverse proxy
381
398
  npx bluebird-js make:ecosystem [--start] # Generates PM2 cluster configuration
382
399
  ```
@@ -487,7 +504,71 @@ export default async function DashboardView({ user, syncedCount = 7 }) {
487
504
  }
488
505
  ```
489
506
 
490
- ## 17. AI Development Guidelines
507
+ ## 17. Unified AI Client (AI & core/ai.js)
508
+
509
+ Bluebird includes a native, zero-dependency unified AI client (`core/ai.js`) supporting **DeepSeek (default)**, **Google Gemini**, and **OpenAI** out of the box with zero external SDKs required. It features automated PII data masking, 0ms prompt caching, sliding window rate limiting ("Anti-Quiebra"), and structured JSON extraction with schema validation:
510
+
511
+ - **DeepSeek by Default**:
512
+ - Base URL `https://api.deepseek.com`, model `deepseek-flash` (served by DeepSeek-V4.1-Flash-1017; legacy names `deepseek-v4-flash`, `deepseek-chat` supported).
513
+ - OpenAI-compatible format with optional thinking/reasoning mode (`thinking: { type: "enabled" }`, `reasoningEffort: "high"`).
514
+ - **Google Gemini**:
515
+ - REST API with `gemini-3.5-flash` (default), `gemini-3.8-flash`, `gemini-2.5-flash`, etc.
516
+ - **OpenAI & Custom Endpoints**:
517
+ - Compatible with `gpt-4o-mini`, `gpt-4o`, Ollama, OpenRouter, and custom endpoints via `baseURL`.
518
+ - **Accurate Real Client IP Detection (`getClientIp`)**:
519
+ - Extracts real visitor IP behind Cloudflare (`cf-connecting-ip`, `true-client-ip`), Nginx (`x-real-ip`), proxy chains (`x-forwarded-for` first IP), and normalizes IPv6 mappings (`::ffff:`).
520
+ - **Reversible Sensitive Data Masking (PII)**:
521
+ - Personal values (`sensitiveKeys`) in context data and prompt text are replaced with anonymous deterministic tokens (`[name_01]`, `[email_01]`, `[dni_01]`) before leaving the server.
522
+ - Responses (`result.text`) are returned fully restored with original user values.
523
+ - **0ms Prompt Cache Synergy**:
524
+ - Cache hashes are computed against the *anonymized* prompt. Two different users asking the same query template trigger an immediate 0ms, $0 latency/cost Cache Hit with their unique personal values restored cleanly.
525
+ - **Sliding Window Rate Limiting ("Anti-Quiebra")**:
526
+ - Protects API budgets with minute/day limits (e.g. `{ minute: 6, day: 30 }` or `{ max: 15, windowMs: 60000 }`), returning HTTP 429 clean responses before depleting credits.
527
+ - Express route protection middleware available via `ai.protect()`.
528
+ - **Response Streaming & SSE (`ai.pipe` & `askStream`)**:
529
+ - Stream tokens in real time directly to Express responses via `await ai.pipe(res, prompt, { sse: true })` with automatic Nginx anti-buffering (`X-Accel-Buffering: no`), or iterate manually via `for await (const chunk of ai.askStream(prompt))`.
530
+
531
+ ```javascript
532
+ import AI, { ai } from "@seip/bluebird-js/core/ai.js";
533
+
534
+ const supportAi = new AI({
535
+ provider: "deepseek", // "deepseek" (default) | "gemini" | "openai" | "custom"
536
+ model: "deepseek-flash", // default model
537
+ rateLimit: { minute: 6, day: 30 }, // Sliding window protection
538
+ cacheTtl: 3600, // Cache responses for 1 hour
539
+ });
540
+
541
+ routerApi.post("/support/reply", supportAi.protect(), async (req, res) => {
542
+ const userData = {
543
+ name: "Maria Garcia",
544
+ email: "maria@example.com",
545
+ dni: "45123987",
546
+ issue: "Need help updating billing details",
547
+ };
548
+
549
+ const result = await supportAi.ask("Draft a courteous support reply for this user:", {
550
+ data: userData,
551
+ sensitiveKeys: ["name", "email", "dni"], // Masked to [name_01], [email_01], [dni_01] before sending!
552
+ request: req, // Automatic IP rate limiting
553
+ json: true,
554
+ });
555
+
556
+ // result.text is returned fully restored with 'Maria Garcia' and 'maria@example.com'!
557
+ res.ok(result);
558
+ });
559
+
560
+ // Stream real-time Server-Sent Events (SSE) directly to Express client response
561
+ routerApi.post("/support/stream", async (req, res) => {
562
+ await supportAi.pipe(res, req.body.message, { sse: true, request: req });
563
+ });
564
+
565
+ // Or iterate chunks manually via async generator
566
+ for await (const chunk of supportAi.askStream("Explain quantum computing in simple terms")) {
567
+ process.stdout.write(chunk.text);
568
+ }
569
+ ```
570
+
571
+ ## 18. AI Development Guidelines
491
572
 
492
573
  1. **Assets & Views**: Static assets in `public/`. HTML views, layouts (`app/views/layouts/`), and partials (`app/views/partials/`) in `app/views/` served via `Render.view()`, `Render.send()`, or `Render.partial()`.
493
574
  2. **JSON Responses**: Use decorated `res.ok()`, `res.created()`, `res.badRequest()`, etc.
package/README.md CHANGED
@@ -25,6 +25,8 @@ Bluebird.js (`@seip/bluebird-js`) is a high-performance web and API framework bu
25
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
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
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.
28
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.
29
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`).
30
32
 
@@ -500,6 +502,76 @@ npx bluebird-js add electron
500
502
 
501
503
  ---
502
504
 
505
+ ### 7. Unified AI Client (`core/ai.js`)
506
+
507
+ 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:
508
+
509
+ - **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"`).
510
+ - **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`.
511
+ - **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.
512
+ - **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.
513
+ - **0ms Prompt Cache Hit:** Computes cache hashes on *anonymized* prompts so multiple users querying identical prompt templates trigger an immediate $0 / 0ms Cache Hit.
514
+ - **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.
515
+
516
+ ```javascript
517
+ import AI, { ai } from "@seip/bluebird-js/core/ai.js";
518
+
519
+ const supportAi = new AI({
520
+ provider: "deepseek", // "deepseek" (default) | "gemini" | "openai" | "custom"
521
+ model: "deepseek-flash",
522
+ rateLimit: { minute: 6, day: 30 }, // Sliding window rate limit
523
+ cacheTtl: 3600, // Cache responses for 1 hour
524
+ });
525
+
526
+ routerApi.post("/support/reply", supportAi.protect(), async (req, res) => {
527
+ const result = await supportAi.ask("Draft a courteous support reply for this user:", {
528
+ data: {
529
+ name: "Maria Garcia",
530
+ email: "maria@example.com",
531
+ dni: "45123987",
532
+ issue: "I would like to update my billing details",
533
+ },
534
+ sensitiveKeys: ["name", "email", "dni"], // Masked before leaving server!
535
+ request: req, // Automatic IP rate limiting
536
+ json: true,
537
+ });
538
+
539
+ // result.text is returned fully restored with 'Maria Garcia' and 'maria@example.com'!
540
+ res.ok(result);
541
+ });
542
+
543
+ // Real-time streaming directly to client response via Server-Sent Events (SSE)
544
+ routerApi.post("/support/stream", async (req, res) => {
545
+ await supportAi.pipe(res, req.body.message, { sse: true, request: req });
546
+ });
547
+
548
+ // Or iterate chunks manually via async generator
549
+ for await (const chunk of supportAi.askStream("Explain quantum computing in simple terms")) {
550
+ process.stdout.write(chunk.text);
551
+ }
552
+ ```
553
+
554
+ ---
555
+
556
+ ### 8. Atomic Database Backups & Verification (`core/database.js`)
557
+
558
+ WAL-safe, non-blocking snapshots for SQLite using `VACUUM INTO` and gzip compression, with automated retention rotation and integrity-verified restore:
559
+
560
+ ```javascript
561
+ import Database from "@seip/bluebird-js/core/database.js";
562
+
563
+ // Atomic, WAL-safe gzip backup with retention rotation (keeps latest 10)
564
+ const backup = await Database.backup({ out: "database/backups", keep: 10, compress: true });
565
+
566
+ // Integrity-verified restore with pre-restore safety snapshot
567
+ await Database.restore("database/backups/backup-sqlite-2026-11-03_170000_123.db.gz", {
568
+ safetyBackup: true,
569
+ verify: true,
570
+ });
571
+ ```
572
+
573
+ ---
574
+
503
575
  ## Developer Tooling CLI
504
576
 
505
577
  ```bash
@@ -514,6 +586,8 @@ npx bluebird-js migrate:status # Displays applied migrati
514
586
  npx bluebird-js migrate:rollback # Reverts latest migration batch
515
587
  npx bluebird-js make:seed <name> # Creates database seed file
516
588
  npx bluebird-js seed # Executes database seeds
589
+ npx bluebird-js db:backup [--keep 10] [--out dir] # Compressed WAL-safe database backup with retention rotation
590
+ npx bluebird-js db:restore <file> [--yes] # Safe database restore with pre-backup & integrity check
517
591
  npx bluebird-js nginx:conf [domain] [port] [root] # Generates Nginx reverse proxy configuration
518
592
  npx bluebird-js make:ecosystem [--start] # Generates PM2 clustering config
519
593
  npx bluebird-js add electron # Scaffolds Electron desktop app & desktop.js
package/core/ai.d.ts ADDED
@@ -0,0 +1,151 @@
1
+ import type { Request, Response, NextFunction, RequestHandler } from "express";
2
+
3
+ export interface AIOptions {
4
+ provider?: "deepseek" | "gemini" | "openai" | "custom";
5
+ model?: string;
6
+ apiKey?: string;
7
+ baseURL?: string;
8
+ temperature?: number;
9
+ thinking?: boolean | { type: string };
10
+ reasoningEffort?: "low" | "medium" | "high";
11
+ rateLimit?: number | { minute?: number; day?: number } | { max: number; windowMs: number };
12
+ rateWindow?: number;
13
+ cacheTtl?: number | boolean;
14
+ system?: string;
15
+ }
16
+
17
+ export interface AIAskOptions {
18
+ data?: Record<string, any>;
19
+ sensitiveKeys?: string[];
20
+ request?: Request | any;
21
+ req?: Request | any;
22
+ user?: string;
23
+ system?: string;
24
+ json?: boolean;
25
+ schema?: Record<string, any>;
26
+ temperature?: number;
27
+ model?: string;
28
+ provider?: "deepseek" | "gemini" | "openai" | "custom";
29
+ apiKey?: string;
30
+ baseURL?: string;
31
+ cache?: number | boolean;
32
+ thinking?: boolean | { type: string };
33
+ reasoningEffort?: "low" | "medium" | "high";
34
+ maxTokens?: number;
35
+ rateLimit?: number | { minute?: number; day?: number } | { max: number; windowMs: number };
36
+ }
37
+
38
+ export interface AIUsage {
39
+ prompt_tokens?: number;
40
+ completion_tokens?: number;
41
+ total_tokens?: number;
42
+ [key: string]: any;
43
+ }
44
+
45
+ export interface AIResult<T = any> {
46
+ success: boolean;
47
+ text?: string;
48
+ rawText?: string;
49
+ parsed?: T;
50
+ valid?: boolean;
51
+ errors?: any;
52
+ reasoning?: string | null;
53
+ cached?: boolean;
54
+ latency?: number;
55
+ provider?: string;
56
+ model?: string;
57
+ usage?: AIUsage;
58
+ maskedKeys?: string[];
59
+ error?: string;
60
+ message?: string;
61
+ retryAfter?: number;
62
+ }
63
+
64
+ export interface AIStreamChunk {
65
+ text: string;
66
+ done: boolean;
67
+ }
68
+
69
+ export interface MaskResult {
70
+ maskedPrompt: string;
71
+ maskedData: Record<string, any> | null;
72
+ tokenMap: Record<string, string>;
73
+ reverseTokenMap: Record<string, string>;
74
+ }
75
+
76
+ export declare function getClientIp(req: Request | any): string;
77
+
78
+ export declare function maskSensitiveData(
79
+ prompt?: string,
80
+ data?: Record<string, any> | null,
81
+ sensitiveKeys?: string[]
82
+ ): MaskResult;
83
+
84
+ export declare function unmaskSensitiveData(
85
+ text?: string,
86
+ reverseTokenMap?: Record<string, string>
87
+ ): string;
88
+
89
+ export declare function extractJsonString(text?: string): string;
90
+
91
+ export declare class AI {
92
+ provider: string;
93
+ model: string;
94
+ apiKey: string;
95
+ baseURL: string;
96
+ temperature: number;
97
+ thinking: boolean | Object;
98
+ reasoningEffort?: "low" | "medium" | "high";
99
+ rateLimit?: any;
100
+ rateWindow: number;
101
+ cacheTtl: number | boolean;
102
+ system: string;
103
+
104
+ constructor(options?: AIOptions);
105
+
106
+ checkRateLimit(
107
+ clientKey: string,
108
+ limitConfig?: any
109
+ ): { allowed: boolean; retryAfter: number };
110
+
111
+ ask<T = any>(prompt: string | any[], options?: AIAskOptions): Promise<AIResult<T>>;
112
+
113
+ askStream(
114
+ prompt: string | any[],
115
+ options?: AIAskOptions
116
+ ): AsyncGenerator<AIStreamChunk, void, unknown>;
117
+
118
+ pipe(
119
+ res: Response | any,
120
+ prompt: string | any[],
121
+ options?: AIAskOptions & { sse?: boolean }
122
+ ): Promise<void>;
123
+
124
+ stream(
125
+ res: Response | any,
126
+ prompt: string | any[],
127
+ options?: AIAskOptions & { sse?: boolean }
128
+ ): Promise<void>;
129
+
130
+ middleware(options?: { rateLimit?: any; message?: string }): RequestHandler;
131
+
132
+ protect(options?: { rateLimit?: any; message?: string }): RequestHandler;
133
+
134
+ static getClientIp(req: Request | any): string;
135
+
136
+ static mask(
137
+ prompt: string,
138
+ data?: Record<string, any> | null,
139
+ sensitiveKeys?: string[]
140
+ ): MaskResult;
141
+
142
+ static unmask(text: string, reverseTokenMap: Record<string, string>): string;
143
+
144
+ static protect(options?: AIOptions & { message?: string }): RequestHandler;
145
+
146
+ static resetRateLimits(): void;
147
+ }
148
+
149
+ export declare const ai: AI;
150
+ export default AI;
151
+