@nowbackup/shared 1.0.0 → 1.0.3

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 (2) hide show
  1. package/README.md +392 -0
  2. package/package.json +36 -25
package/README.md ADDED
@@ -0,0 +1,392 @@
1
+ # 🚀 NowBackup SDK
2
+
3
+ **Universal Database Auto Backup SDK and CLI for Node.js and Enterprise Environments.**
4
+
5
+ ⚡ Powered by [NowMail](https://nowmail.in)
6
+
7
+ NowBackup is a production-grade, enterprise-ready backup solution that automatically detects your database, creates non-blocking backups, compresses, encrypts, and uploads them to your preferred cloud storage provider.
8
+
9
+ ---
10
+
11
+ ## 📖 Table of Contents
12
+ 1. [Key Features](#-key-features)
13
+ 2. [Installation](#-installation)
14
+ 3. [Quick Start (Zero-Config Auto-Detection)](#-quick-start-zero-config-auto-detection)
15
+ 4. [Programmatic Configuration Reference](#-programmatic-configuration-reference)
16
+ 5. [Database-Specific Setups (All 8 Engines)](#-database-specific-setups)
17
+ - [PostgreSQL](#1-postgresql)
18
+ - [MySQL](#2-mysql)
19
+ - [SQLite](#3-sqlite)
20
+ - [MongoDB](#4-mongodb)
21
+ - [Redis](#5-redis)
22
+ - [MS SQL Server](#6-ms-sql-server)
23
+ - [Apache Cassandra](#7-apache-cassandra)
24
+ - [Neo4j Graph Database](#8-neo4j-graph-database)
25
+ 6. [Storage Providers](#-storage-providers)
26
+ 7. [Built-in Encryption & Compression](#-built-in-encryption--compression)
27
+ 8. [CLI Tool Usage](#-cli-tool-usage)
28
+ 9. [Local Distribution & Tarball Installation](#-local-distribution--tarball-installation)
29
+
30
+ ---
31
+
32
+ ## ⚡ Key Features
33
+
34
+ * **Auto-Detection**: Zero-config setup. Detects database types from environment variables or active package dependencies automatically.
35
+ * **Non-Blocking Streaming**: Direct pipeline stream (`[DB Driver] -> [Gzip] -> [AES-256] -> [Storage]`) keeps memory footprint under **50MB** even for databases larger than **100GB**.
36
+ * **High-Fidelity fallbacks**: Fallback JS engines generate standard backup scripts if system binaries (`pg_dump`, `mysqldump`) are not locally installed.
37
+ * **Multi-Database Scheduling**: Support for backing up multiple databases in a single Node.js instance.
38
+ * **Built-in Rotation**: Retention engine automatically rotates and purges old backups according to your policy.
39
+
40
+ ---
41
+
42
+ ## 📦 Installation
43
+
44
+ ### 1. Unified Package (Recommended)
45
+ Install the self-contained package from npmjs (or your local packaged tarball):
46
+ ```bash
47
+ npm install nowbackup
48
+ ```
49
+
50
+ ---
51
+
52
+ ## 🚀 Quick Start (Zero-Config Auto-Detection)
53
+
54
+ If you have database connection details set up in standard environment variables, NowBackup will automatically detect your database type, construct connection pools, and schedule a cron job:
55
+
56
+ ```javascript
57
+ import { NowBackup } from 'nowbackup';
58
+
59
+ await NowBackup.init({
60
+ database: 'auto', // 👈 Automatically scans and schedules backups for Postgres, MySQL, Mongo, Redis, SQLite, MS SQL, Cassandra, or Neo4j!
61
+ schedule: '0 0 * * *', // Every night at midnight
62
+ storage: {
63
+ provider: 'local',
64
+ options: {
65
+ path: './backups'
66
+ }
67
+ },
68
+ compression: true, // Gzip compression
69
+ retention: {
70
+ keepLast: 10 // Automatically retains the 10 most recent backups
71
+ }
72
+ });
73
+ ```
74
+
75
+ ---
76
+
77
+ ## 🔄 Handling Multiple Auto-Detected Databases (Array return)
78
+
79
+ When you set `database: 'auto'`, NowBackup dynamically scans your environments and dependencies for database details.
80
+ * If **multiple** databases are detected (e.g. your app uses both a Postgres database and a Redis cache), `NowBackup.init()` will return an **Array** of backup instances.
81
+ * If only a **single** database is detected (or you specify a database type explicitly, like `database: 'postgres'`), it returns a **single** backup instance.
82
+
83
+ To handle both cases safely in your code, use the standard `Array.isArray()` check:
84
+
85
+ ```javascript
86
+ import { NowBackup } from 'nowbackup';
87
+
88
+ const backup = await NowBackup.init({
89
+ database: 'auto',
90
+ schedule: '0 0 * * *', // Daily at midnight
91
+ storage: { provider: 'local', options: { path: './backups' } }
92
+ });
93
+
94
+ if (Array.isArray(backup)) {
95
+ console.log(`📡 Auto-detected and scheduled ${backup.length} databases!`);
96
+
97
+ // (Optional) Trigger all backups instantly:
98
+ for (const instance of backup) {
99
+ await instance.run();
100
+ }
101
+ } else {
102
+ console.log(`📡 Auto-detected and scheduled a single database!`);
103
+
104
+ // (Optional) Trigger backup instantly:
105
+ await backup.run();
106
+ }
107
+ ```
108
+
109
+ > [!NOTE]
110
+ > If you provided a `schedule` cron configuration, the background scheduler automatically activates and runs your backups in the background immediately upon calling `.init()`. Calling `await backup.run()` manually is only required if you want to trigger a **one-off, immediate backup** in addition to the schedule.
111
+
112
+ ---
113
+
114
+ ## 📝 Programmatic Multi-Database Configuration (No Environment Variables)
115
+
116
+ If you do **not** use environment variables for your database connection strings, you can still easily backup multiple databases concurrently by passing an **array of configuration objects** directly into `NowBackup.init()`.
117
+
118
+ This approach is completely self-contained and allows you to configure completely different connection URLs, cron schedules, storage destinations, and compression/retention policies for each database separately:
119
+
120
+ ```javascript
121
+ import { NowBackup } from 'nowbackup';
122
+
123
+ // Pass an array of database configurations directly to the SDK
124
+ const backupInstances = await NowBackup.init([
125
+ {
126
+ database: 'postgres',
127
+ databaseUrl: 'postgres://user:pass@localhost:5432/my_production_db',
128
+ schedule: '0 0 * * *', // Every night at midnight
129
+ storage: {
130
+ provider: 'local',
131
+ options: { path: './backups/postgres' }
132
+ },
133
+ compression: true,
134
+ retention: { keepLast: 15 }
135
+ },
136
+ {
137
+ database: 'mysql',
138
+ databaseUrl: 'mysql://root:secret@localhost:3306/another_db',
139
+ schedule: '0 2 * * *', // Daily at 2 AM
140
+ storage: {
141
+ provider: 's3',
142
+ options: {
143
+ bucket: 'my-mysql-s3-backups',
144
+ region: 'us-east-1',
145
+ credentials: {
146
+ accessKeyId: 'AWS_ACCESS_KEY_ID',
147
+ secretAccessKey: 'AWS_SECRET_ACCESS_KEY'
148
+ }
149
+ }
150
+ },
151
+ compression: true
152
+ }
153
+ ]);
154
+
155
+ console.log(`🚀 Successfully initialized and scheduled ${backupInstances.length} database backups programmatically!`);
156
+ ```
157
+
158
+ ---
159
+
160
+ ## ⚙️ Programmatic Configuration Reference
161
+
162
+ The `NowBackup.init(config)` method takes a `BackupConfig` structure:
163
+
164
+ | Parameter | Type | Required | Default | Description |
165
+ | :--- | :--- | :--- | :--- | :--- |
166
+ | `database` | `string` | **Yes** | - | Database driver: `'postgres'`, `'mysql'`, `'sqlite'`, `'mongodb'`, `'redis'`, `'mssql'`, `'cassandra'`, `'neo4j'`, or `'auto'`. |
167
+ | `databaseUrl` | `string` | No | - | Database connection URL. Fallbacks to standard environment variables if left blank. |
168
+ | `schedule` | `string` | No | - | Cron string (e.g. `'0 0 * * *'`). If omitted, backup runs **instantly** once. |
169
+ | `storage.provider` | `string` | **Yes** | - | Storage backend: `'local'` or `'s3'`. |
170
+ | `storage.options` | `object` | No | - | Provider options (e.g. path for `'local'`, region/bucket/credentials for `'s3'`). |
171
+ | `compression` | `boolean` | No | `true` | Apply streaming Gzip compression. |
172
+ | `encryption.enabled`| `boolean` | No | `false` | Enable streaming encryption. |
173
+ | `encryption.key` | `string` | No | - | **32-character** secure key for AES-256-GCM encryption. |
174
+ | `retention.keepLast`| `number` | No | - | Keep only the specified number of backup files (rotates out older files). |
175
+ | `log_enable` | `boolean` | No | `false` | Enable backup event logging. If `false`, the SDK executes completely silently. |
176
+ | `log` | `boolean` | No | `false` | Toggle verbosity. If `true`, logs all actions "as it is". If `false`, outputs only a success summary line: `[$dateTime] Backup done for $db database.` |
177
+
178
+ ---
179
+
180
+ ## 📢 Smart Logging Controls
181
+
182
+ NowBackup features an intelligent logger designed to keep your server console quiet, clean, and perfectly aligned with your preferences:
183
+
184
+ ### 1. Default (Perfect Silence)
185
+ By default, the SDK runs completely silently. No initialization notices, scheduler details, or retry logs will clutter your process.
186
+ ```javascript
187
+ await NowBackup.init({
188
+ database: 'auto',
189
+ storage: { provider: 'local', options: { path: './backups' } }
190
+ // log_enable defaults to false
191
+ // log defaults to false
192
+ });
193
+ ```
194
+
195
+ ### 2. Success Summary Only (Log Enable: `true`, Log: `false`)
196
+ Enable logs but keep them non-verbose. Ideal for production servers where you want a clean audit trail without driver execution noise:
197
+ ```javascript
198
+ await NowBackup.init({
199
+ database: 'auto',
200
+ storage: { provider: 'local', options: { path: './backups' } },
201
+ log_enable: true,
202
+ log: false // 👈 Show ONLY a clean summary line
203
+ });
204
+ ```
205
+ *Console output when a backup runs:*
206
+ ```text
207
+ [18/05/2026, 16:44:01] Backup done for sqlite database.
208
+ [18/05/2026, 16:44:02] Backup done for mysql database.
209
+ ```
210
+
211
+ ### 3. Full Verbose Logging (Log Enable: `true`, Log: `true`)
212
+ Log every detailed lifecycle event "as it is". Ideal for debugging or development environments:
213
+ ```javascript
214
+ await NowBackup.init({
215
+ database: 'auto',
216
+ storage: { provider: 'local', options: { path: './backups' } },
217
+ log_enable: true,
218
+ log: true // 👈 Verbose logging active
219
+ });
220
+ ```
221
+ *Console output when a backup runs:*
222
+ ```text
223
+ ⚡ NowBackup - Powered by NowMail (https://nowmail.in)
224
+ [NowBackup] Running multi-database auto-detection...
225
+ [NowBackup] Auto-detected databases: mysql, sqlite
226
+ [NowBackup] Initializing instances for 2 detected databases.
227
+ [NowBackup] Scheduling backup: */10 * * * * * for sqlite
228
+ [NowBackup] [2026-05-18T11-15-40-165Z] Starting backup sequence for sqlite...
229
+ [SqliteDriver] Starting backup: ./database.sqlite
230
+ [NowBackup] Applying Gzip compression...
231
+ [NowBackup] Uploading to local...
232
+ [NowBackup] SUCCESS: Backup stored at backups\backup-sqlite-2026-05-18T11-15-40-165Z.sql.gz
233
+ [18/05/2026, 16:45:40] Backup done for sqlite database.
234
+ ```
235
+
236
+ ---
237
+
238
+ ## 🗄️ Database-Specific Setups
239
+
240
+ For each database, you can pass the connection string programmatically via the `databaseUrl` key, or let the SDK resolve it from environment variables:
241
+
242
+ ### 1. PostgreSQL
243
+ * **Programmatic URL**: `postgres://user:pass@localhost:5432/mydb`
244
+ * **Auto-Detect Env**: `DATABASE_URL`, `POSTGRES_URL`, `POSTGRES_DATABASE_URL`, `PGHOST` (with `pg` in dependencies).
245
+ * **Backup Output**: Standard plain SQL dump file (`.sql`). Uses `pg_dump` if installed on host, or falls back to our robust internal JS table exporter.
246
+
247
+ ### 2. MySQL
248
+ * **Programmatic URL**: `mysql://user:pass@localhost:3306/mydb`
249
+ * **Auto-Detect Env**: `MYSQL_URL`, `MYSQL_DATABASE_URL`, `MYSQL_HOST` (with `mysql` or `mysql2` in dependencies).
250
+ * **Backup Output**: Standard SQL dump file (`.sql`). Uses `mysqldump` if installed on host, or falls back to our robust internal JS table exporter.
251
+
252
+ ### 3. SQLite
253
+ * **Programmatic URL**: `file://relative/path/to/database.sqlite` (or absolute path)
254
+ * **Auto-Detect Env**: `SQLITE_URL`, `SQLITE_FILE`. Defaults to `./database.sqlite` if no environment variable is provided.
255
+ * **Backup Output**: Binary database copy file (`.sqlite`).
256
+
257
+ ### 4. MongoDB
258
+ * **Programmatic URL**: `mongodb://user:pass@localhost:27017/mydb` or `mongodb+srv://...`
259
+ * **Auto-Detect Env**: `MONGO_URI`, `MONGODB_URL`.
260
+ * **Backup Output**: BSON archive dump file. Uses native `mongodump` tool.
261
+
262
+ ### 5. Redis
263
+ * **Programmatic URL**: `redis://user:pass@localhost:6379`
264
+ * **Auto-Detect Env**: `REDIS_URL`.
265
+ * **Backup Output**: Standard Redis dump dataset.
266
+
267
+ ### 6. MS SQL Server
268
+ * **Programmatic URL**: `mssql://username:password@localhost:1433/database_name` or `sqlserver://...`
269
+ * **Auto-Detect Env**: `MSSQL_URL`, `SQLSERVER_URL`, `MSSQL_CONNECTION_STRING`, `MSSQL_HOST`.
270
+ * **Backup Output**: Transact-SQL schema and insert statements script. Automatically detects **identity columns** and injects `SET IDENTITY_INSERT ... ON/OFF` rules to ensure clean restores.
271
+
272
+ ### 7. Apache Cassandra
273
+ * **Programmatic URL**: `cassandra://username:password@localhost:9042/keyspace_name`
274
+ * **Auto-Detect Env**: `CASSANDRA_URL`, `CASSANDRA_HOST`, `CASSANDRA_CONTACT_POINTS`.
275
+ * **Backup Output**: Cassandra Query Language (CQL) dump script (`.sql`). Resolves complete column family configurations and exports all row datasets.
276
+
277
+ ### 8. Neo4j Graph Database
278
+ * **Programmatic URL**: `neo4j://username:password@localhost:7687` or `bolt://...`
279
+ * **Auto-Detect Env**: `NEO4J_URL`, `NEO4J_URI`, `NEO4J_HOST`.
280
+ * **Backup Output**: Standard Cypher script file (`.cypher`). Streams all graph elements (nodes, properties, and relationships) and binds them dynamically via temporary internal identifiers (`_nowbackup_id`).
281
+
282
+ ---
283
+
284
+ ## 💾 Storage Providers
285
+
286
+ ### 1. Local Storage
287
+ Stores files locally in the specified path:
288
+ ```javascript
289
+ storage: {
290
+ provider: 'local',
291
+ options: {
292
+ path: './backups' // Folder where backups will be stored
293
+ }
294
+ }
295
+ ```
296
+
297
+ ### 2. AWS S3 (and S3-Compatible providers like MinIO or Cloudflare R2)
298
+ Uploads streams directly into an S3 bucket:
299
+ ```javascript
300
+ storage: {
301
+ provider: 's3',
302
+ options: {
303
+ bucket: 'my-production-backups',
304
+ region: 'us-east-1',
305
+ credentials: {
306
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID,
307
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
308
+ },
309
+ // Optional endpoint for S3 compatibles (e.g. MinIO, Cloudflare R2)
310
+ // endpoint: 'https://<accountid>.r2.cloudflarestorage.com'
311
+ }
312
+ }
313
+ ```
314
+
315
+ ---
316
+
317
+ ## 🔒 Built-in Encryption & Compression
318
+
319
+ ### Streaming Gzip Compression
320
+ To compress backups on-the-fly and save up to **80% storage space**, enable compression:
321
+ ```javascript
322
+ compression: true // Appends '.gz' to the output filename
323
+ ```
324
+
325
+ ### Streaming AES-256-GCM Encryption
326
+ To protect your production backups, you can enable military-grade streaming encryption. Make sure to specify a **32-character** secret key:
327
+ ```javascript
328
+ encryption: {
329
+ enabled: true,
330
+ algorithm: 'aes-256-gcm',
331
+ key: 'my-super-secret-secure-32-char-key!!' // 👈 MUST be exactly 32 characters
332
+ } // Appends '.enc' to the output filename
333
+ ```
334
+
335
+ ---
336
+
337
+ ## 💻 CLI Tool Usage
338
+
339
+ NowBackup includes a command-line interface allowing you to run one-off backups instantly from your terminal without writing any code.
340
+
341
+ ### Command Syntax:
342
+ ```bash
343
+ npx nowbackup run --database <type> --url <connection-string> --storage <local|s3> [options]
344
+ ```
345
+
346
+ ### Available Parameter Flags:
347
+ * `-d, --database <type>`: Database type (`postgres`, `mysql`, `mongodb`, `redis`, `sqlite`, `mssql`, `cassandra`, `neo4j`, `auto`)
348
+ * `-u, --url <url>`: Database connection string URL (falls back to environmental variables if not set)
349
+ * `-s, --storage <provider>`: Storage provider (`local` or `s3`)
350
+ * `-p, --path <path>`: Local storage target directory path (for local storage, defaults to `./backups`)
351
+ * `-b, --bucket <bucket>`: AWS S3 bucket name
352
+ * `-c, --compress`: Apply Gzip compression (enabled by default)
353
+ * `-e, --encrypt <key>`: Enable AES-256-GCM encryption with the provided 32-character key
354
+
355
+ ### Example CLI Backup Command:
356
+ ```bash
357
+ npx nowbackup run -d mysql -u "mysql://root:password@localhost:3306/db" -s local -p "./backups" --encrypt "my-32-character-secret-key-123"
358
+ ```
359
+
360
+ ---
361
+
362
+ ## 📦 Local Distribution & Tarball Installation
363
+
364
+ The monorepo contains a dedicated, cross-platform build and package utility. You can generate a single unified, self-contained NPM package tarball that includes the programmatic SDK and the terminal CLI runner with **zero internal monorepo package dependencies** at runtime:
365
+
366
+ ### 1. Build and Generate Tarball
367
+ From your `nodejs` root monorepo folder, run:
368
+ ```bash
369
+ npm run pack
370
+ ```
371
+ This generates exactly **one** unified tarball file inside the `packs` directory:
372
+ * `packs/nowbackup-1.0.0.tgz`
373
+
374
+ ### 2. Install and Use locally
375
+ Copy the `.tgz` file to any project and install it:
376
+ ```bash
377
+ npm install /path/to/packs/nowbackup-1.0.0.tgz
378
+ ```
379
+ You can now import and use it instantly in your project:
380
+ ```javascript
381
+ import { NowBackup } from 'nowbackup';
382
+ ```
383
+
384
+ ---
385
+
386
+ ## 📄 License
387
+
388
+ MIT © Nowmail Team
389
+
390
+ ---
391
+
392
+ ⚡ Powered by [NowMail](https://nowmail.in)
package/package.json CHANGED
@@ -1,27 +1,38 @@
1
1
  {
2
- "name": "@nowbackup/shared",
3
- "version": "1.0.0",
4
- "type": "module",
5
- "main": "./dist/index.cjs",
6
- "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "require": "./dist/index.cjs"
13
- }
14
- },
15
- "files": [
16
- "dist"
17
- ],
18
- "scripts": {
19
- "build": "tsup src/index.ts --format esm,cjs --clean",
20
- "dev": "tsup src/index.ts --format esm,cjs --watch ",
21
- "prepublishOnly": "npm run build"
22
- },
23
- "devDependencies": {
24
- "@types/node": "^25.8.0",
25
- "tsup": "^8.5.1"
26
- }
2
+ "name": "@nowbackup/shared",
3
+ "version": "1.0.3",
4
+ "description": "Shared utilities and helpers for NowBackup monorepo packages",
5
+ "type": "module",
6
+ "author": "Nowmail Team",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/jd-ashish/nowbackup.git"
11
+ },
12
+ "keywords": [
13
+ "nowbackup",
14
+ "shared-utilities"
15
+ ],
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "require": "./dist/index.cjs"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "scripts": {
30
+ "build": "tsup src/index.ts --format esm,cjs --clean",
31
+ "dev": "tsup src/index.ts --format esm,cjs --watch ",
32
+ "prepublishOnly": "npm run build"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^25.8.0",
36
+ "tsup": "^8.5.1"
37
+ }
27
38
  }