@onurege3467/zerohelper 10.2.5 → 10.2.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/README.md +432 -54
- package/dist/bin/commands/cache.d.ts +2 -0
- package/dist/bin/commands/cache.js +92 -0
- package/dist/bin/commands/db-backup.d.ts +3 -0
- package/dist/bin/commands/db-backup.js +118 -0
- package/dist/bin/commands/db.d.ts +2 -0
- package/dist/bin/commands/db.js +334 -0
- package/dist/bin/commands/import-export.d.ts +3 -0
- package/dist/bin/commands/import-export.js +123 -0
- package/dist/bin/commands/init.d.ts +2 -0
- package/dist/bin/commands/init.js +85 -0
- package/dist/bin/commands/migrate.d.ts +3 -0
- package/dist/bin/commands/migrate.js +167 -0
- package/dist/bin/commands/repl.d.ts +2 -0
- package/dist/bin/commands/repl.js +96 -0
- package/dist/bin/commands/seed.d.ts +2 -0
- package/dist/bin/commands/seed.js +76 -0
- package/dist/bin/commands/zpack.d.ts +2 -0
- package/dist/bin/commands/zpack.js +36 -0
- package/dist/bin/index.d.ts +2 -0
- package/dist/bin/index.js +28 -0
- package/dist/bin/types.d.ts +22 -0
- package/dist/bin/types.js +2 -0
- package/dist/bin/utils/config.d.ts +3 -0
- package/dist/bin/utils/config.js +78 -0
- package/dist/bin/utils/prompts.d.ts +3 -0
- package/dist/bin/utils/prompts.js +115 -0
- package/dist/bin/zero.js +789 -81
- package/dist/migrations/1767521950635_test_migration.d.ts +3 -0
- package/dist/migrations/1767521950635_test_migration.js +11 -0
- package/dist/migrations/1767522158826_create_users_table.d.ts +2 -0
- package/dist/migrations/1767522158826_create_users_table.js +11 -0
- package/dist/package.json +79 -0
- package/dist/zero.config.d.ts +10 -0
- package/dist/zero.config.js +13 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://www.typescriptlang.org/)
|
|
5
5
|
[](https://opensource.org/licenses/ISC)
|
|
6
6
|
|
|
7
|
-
**ZeroHelper** is an elite-level, high-performance, and fully TypeScript-native utility ecosystem. Rebuilt from the ground up for version
|
|
7
|
+
**ZeroHelper** is an elite-level, high-performance, and fully TypeScript-native utility ecosystem. Rebuilt from the ground up for version 10.2.6, it offers a unified abstraction layer over multiple database engines, advanced caching strategies, and a massive collection of "battle-tested" utility functions.
|
|
8
8
|
|
|
9
9
|
---
|
|
10
10
|
|
|
@@ -38,6 +38,12 @@ We have now decided to open the vault. By open-sourcing this battle-hardened fra
|
|
|
38
38
|
7. [Database Migration System](#-database-migration-system)
|
|
39
39
|
8. [ZeroWorker (Worker Threads)](#-zeroworker-worker-threads)
|
|
40
40
|
9. [Zero-CLI Management Tool](#-zero-cli)
|
|
41
|
+
- [Project Initialization](#project-initialization)
|
|
42
|
+
- [Database Management](#database-management)
|
|
43
|
+
- [Migration Management](#migration-management)
|
|
44
|
+
- [Cache Management](#cache-management)
|
|
45
|
+
- [Data Export/Import](#data-exportimport)
|
|
46
|
+
- [Interactive REPL](#interactive-repl)
|
|
41
47
|
10. [Data Seeder](#-data-seeder)
|
|
42
48
|
11. [Function Modules in Depth](#-function-modules-in-depth)
|
|
43
49
|
- [TOON Module](#toon-module)
|
|
@@ -48,10 +54,12 @@ We have now decided to open the vault. By open-sourcing this battle-hardened fra
|
|
|
48
54
|
12. [Validation & Sanitization Engine](#-validation--sanitization-engine)
|
|
49
55
|
13. [Professional Logger Pro](#-professional-logger-pro)
|
|
50
56
|
14. [HTTP & Networking](#-http--networking)
|
|
51
|
-
15. [
|
|
52
|
-
16. [
|
|
53
|
-
17. [
|
|
54
|
-
18. [
|
|
57
|
+
15. [Real-World Use Cases](#-real-world-use-cases)
|
|
58
|
+
16. [Frequently Asked Questions](#-frequently-asked-questions)
|
|
59
|
+
17. [Architecture & Performance Benchmarks](#-architecture--performance)
|
|
60
|
+
18. [Best Practices](#-best-practices)
|
|
61
|
+
19. [Troubleshooting](#-troubleshooting)
|
|
62
|
+
20. [License](#-license)
|
|
55
63
|
|
|
56
64
|
---
|
|
57
65
|
|
|
@@ -65,18 +73,17 @@ npm install @onurege3467/zerohelper
|
|
|
65
73
|
|
|
66
74
|
## 🛡️ TypeScript Excellence
|
|
67
75
|
|
|
68
|
-
ZeroHelper
|
|
76
|
+
ZeroHelper 10.2.6 leverages **Discriminated Unions** to ensure that your configuration object perfectly matches your selected adapter. This eliminates the "configuration guesswork" that plagues most multi-database libraries.
|
|
69
77
|
|
|
70
78
|
### Example: Config Autocomplete
|
|
71
79
|
```typescript
|
|
72
80
|
import { database } from '@onurege3467/zerohelper';
|
|
73
81
|
|
|
74
|
-
// Type-Safe Factory
|
|
75
82
|
const db = database.createDatabase({
|
|
76
83
|
adapter: 'zpack',
|
|
77
84
|
config: {
|
|
78
85
|
path: './data.zpack',
|
|
79
|
-
indexFields: { 'users': ['email'] },
|
|
86
|
+
indexFields: { 'users': ['email'] },
|
|
80
87
|
autoFlush: true
|
|
81
88
|
}
|
|
82
89
|
});
|
|
@@ -92,14 +99,12 @@ All adapters implement the `IDatabase` interface, allowing you to swap database
|
|
|
92
99
|
|
|
93
100
|
#### 1. Inserting Data
|
|
94
101
|
```typescript
|
|
95
|
-
// Simple insert
|
|
96
102
|
const newId = await db.insert('users', {
|
|
97
103
|
username: 'onurege',
|
|
98
104
|
email: 'contact@onurege.com',
|
|
99
105
|
created_at: new Date()
|
|
100
106
|
});
|
|
101
107
|
|
|
102
|
-
// Bulk insert (Highly optimized)
|
|
103
108
|
const count = await db.bulkInsert('logs', [
|
|
104
109
|
{ message: 'System Start', level: 'info' },
|
|
105
110
|
{ message: 'Database Connected', level: 'info' }
|
|
@@ -108,60 +113,121 @@ const count = await db.bulkInsert('logs', [
|
|
|
108
113
|
|
|
109
114
|
#### 2. Advanced Selection
|
|
110
115
|
```typescript
|
|
111
|
-
// Fetch a single record with generic types
|
|
112
116
|
interface User { _id: number; username: string; email: string; }
|
|
113
117
|
const user = await db.selectOne<User>('users', { username: 'onurege' });
|
|
114
118
|
```
|
|
115
119
|
|
|
116
120
|
#### 3. Atomic Counters
|
|
117
|
-
Avoid race conditions by using atomic operations instead of manual fetching and saving.
|
|
118
121
|
```typescript
|
|
119
|
-
// Safely incrementing balance
|
|
120
122
|
await db.increment('wallets', { balance: 100 }, { user_id: 1 });
|
|
121
|
-
|
|
122
|
-
// Safely decrementing stock
|
|
123
123
|
await db.decrement('inventory', { stock: 1 }, { sku: 'PRO-123' });
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
+
#### 4. Upsert Operations
|
|
127
|
+
```typescript
|
|
128
|
+
await db.set('settings', { value: 'dark' }, { key: 'theme' });
|
|
129
|
+
```
|
|
130
|
+
|
|
126
131
|
---
|
|
127
132
|
|
|
128
133
|
## 🚀 Specialized Database Adapters
|
|
129
134
|
|
|
130
135
|
### 🏎️ ZPack (The Binary Powerhouse)
|
|
131
|
-
**ZPack** is ZeroHelper's proprietary binary format designed for high-throughput logging and data archival.
|
|
132
|
-
- **Vacuum:** `await db.vacuum()` - Rebuilds the file to eliminate fragmented space from deleted records.
|
|
133
|
-
- **Indexing:** Instant lookups on non-ID fields using secondary indexing.
|
|
134
|
-
- **Compression:** Built-in `zlib` compression for minimal disk footprint.
|
|
135
136
|
|
|
137
|
+
ZPack is ZeroHelper's proprietary binary format engineered for **maximum write performance** and **minimum storage footprint**.
|
|
138
|
+
|
|
139
|
+
#### Key Features
|
|
140
|
+
- **Ultra-Fast Writes**: 0.08ms average write latency
|
|
141
|
+
- **zlib Compression**: 40-60% smaller file sizes
|
|
142
|
+
- **Vacuum Operation**: Eliminate fragmentation from deleted records
|
|
143
|
+
- **Secondary Indexing**: Instant lookups on indexed fields
|
|
144
|
+
- **Auto-Flush**: Configurable write-through behavior
|
|
145
|
+
|
|
146
|
+
#### When to Use ZPack
|
|
147
|
+
- High-volume event logging
|
|
148
|
+
- Audit trail storage
|
|
149
|
+
- Data archival and backup
|
|
150
|
+
- Time-series data (with vacuum maintenance)
|
|
151
|
+
|
|
152
|
+
#### Example
|
|
136
153
|
```typescript
|
|
137
154
|
const zpack = database.createDatabase({
|
|
138
155
|
adapter: 'zpack',
|
|
139
|
-
config: {
|
|
156
|
+
config: {
|
|
157
|
+
path: './storage/events.zpack',
|
|
158
|
+
indexFields: { 'events': ['event_type', 'user_id'] },
|
|
159
|
+
autoFlush: true
|
|
160
|
+
}
|
|
140
161
|
});
|
|
162
|
+
|
|
163
|
+
await zpack.insert('logs', { timestamp: new Date(), level: 'info', message: 'Event' });
|
|
164
|
+
|
|
165
|
+
await zpack.vacuum();
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### 📊 TOON (World's First Native TOON Database)
|
|
169
|
+
|
|
170
|
+
ZeroHelper introduces the **world's first native TOON (Token-Oriented Object Notation) database** - a revolutionary format optimized for both humans and AI.
|
|
171
|
+
|
|
172
|
+
#### Why TOON?
|
|
173
|
+
|
|
174
|
+
| Feature | JSON | YAML | TOON |
|
|
175
|
+
|---------|------|------|------|
|
|
176
|
+
| Human Readable | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
|
|
177
|
+
| Parse Speed | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
|
|
178
|
+
| Token Efficiency | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
|
|
179
|
+
| AI-Optimized | ❌ | ❌ | ⭐⭐⭐⭐⭐ |
|
|
180
|
+
| File Size | Medium | Large | Small |
|
|
181
|
+
|
|
182
|
+
#### TOON Syntax Example
|
|
183
|
+
```toon
|
|
184
|
+
users:
|
|
185
|
+
name: John
|
|
186
|
+
age: 25
|
|
187
|
+
active: true
|
|
188
|
+
|
|
189
|
+
products:
|
|
190
|
+
[3]{name,price,stock}:
|
|
191
|
+
Laptop,1500,10
|
|
192
|
+
Mouse,25,100
|
|
193
|
+
Keyboard,75,50
|
|
141
194
|
```
|
|
142
195
|
|
|
143
|
-
|
|
144
|
-
|
|
196
|
+
#### LLM Token Savings
|
|
197
|
+
```
|
|
198
|
+
JSON: {"users":[{"name":"John","age":25,"active":true}]} = 47 tokens
|
|
199
|
+
TOON: users: name: John age: 25 active: true = 12 tokens
|
|
145
200
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
- **Readable Alternative:** As fast as binary but as readable as YAML.
|
|
201
|
+
Savings: ~75% reduction in token usage!
|
|
202
|
+
```
|
|
149
203
|
|
|
204
|
+
#### Use Cases
|
|
205
|
+
- AI/LLM application data storage
|
|
206
|
+
- Configuration files
|
|
207
|
+
- Prompt engineering templates
|
|
208
|
+
- Agent memory and context
|
|
209
|
+
|
|
210
|
+
#### Example
|
|
150
211
|
```typescript
|
|
151
212
|
const toonDb = database.createDatabase({
|
|
152
213
|
adapter: 'toon',
|
|
153
214
|
config: {
|
|
154
|
-
path: './data.toon',
|
|
155
|
-
saveInterval: 1000
|
|
215
|
+
path: './ai-data.toon',
|
|
216
|
+
saveInterval: 1000
|
|
156
217
|
}
|
|
157
218
|
});
|
|
158
219
|
|
|
159
|
-
await toonDb.insert('
|
|
220
|
+
await toonDb.insert('prompts', { system: 'You are helpful...', temperature: 0.7 });
|
|
160
221
|
```
|
|
161
222
|
|
|
162
223
|
### 🐘 PostgreSQL & 🐬 MySQL
|
|
224
|
+
|
|
163
225
|
Enterprise-grade SQL adapters with automatic schema evolution.
|
|
164
|
-
- **Auto-Table/Column Creation
|
|
226
|
+
- **Auto-Table/Column Creation**: ZeroHelper creates missing tables and performs `ALTER TABLE` automatically when new keys are detected in your data.
|
|
227
|
+
|
|
228
|
+
### 🍃 MongoDB & 💚 Redis
|
|
229
|
+
|
|
230
|
+
Flexible NoSQL adapters for document storage and caching.
|
|
165
231
|
|
|
166
232
|
---
|
|
167
233
|
|
|
@@ -177,7 +243,7 @@ const db = database.createDatabase({
|
|
|
177
243
|
cache: {
|
|
178
244
|
type: 'redis',
|
|
179
245
|
host: '127.0.0.1',
|
|
180
|
-
ttl: 300000
|
|
246
|
+
ttl: 300000
|
|
181
247
|
}
|
|
182
248
|
}
|
|
183
249
|
});
|
|
@@ -195,7 +261,7 @@ db.on('beforeInsert', (table, data) => {
|
|
|
195
261
|
});
|
|
196
262
|
|
|
197
263
|
db.on('afterUpdate', (table, result) => {
|
|
198
|
-
|
|
264
|
+
console.log(`Table ${table} updated. Rows affected: ${result.affected}`);
|
|
199
265
|
});
|
|
200
266
|
```
|
|
201
267
|
|
|
@@ -239,26 +305,77 @@ const result = await functions.worker_module.runAsyncTask(
|
|
|
239
305
|
|
|
240
306
|
## 🛠️ Zero-CLI
|
|
241
307
|
|
|
242
|
-
A professional command-line interface to manage your framework.
|
|
308
|
+
A professional command-line interface to manage your database and ZeroHelper framework.
|
|
309
|
+
|
|
310
|
+
### 📋 Available Commands
|
|
311
|
+
|
|
312
|
+
#### **Project Initialization**
|
|
243
313
|
```bash
|
|
244
|
-
# Initialize project interactively
|
|
245
314
|
npx zero init
|
|
315
|
+
```
|
|
246
316
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
# View real-time DB dashboard
|
|
317
|
+
#### **Database Management**
|
|
318
|
+
```bash
|
|
319
|
+
npx zero db:test
|
|
251
320
|
npx zero db:stats
|
|
321
|
+
npx zero db:seed --table users --count 100
|
|
322
|
+
npx zero db:backup
|
|
323
|
+
npx zero db:backup --output ./custom-backups
|
|
324
|
+
npx zero db:restore ./backups/backup_2024-01-01.zerohelper.json
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
#### **Migration Management**
|
|
328
|
+
```bash
|
|
329
|
+
npx zero migrate
|
|
330
|
+
npx zero migration:rollback --steps 1
|
|
331
|
+
npx zero migration:status
|
|
332
|
+
npx zero make:migration create_users_table
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
#### **Cache Management**
|
|
336
|
+
```bash
|
|
337
|
+
npx zero cache:clear
|
|
338
|
+
npx zero cache:stats
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
#### **Data Export/Import**
|
|
342
|
+
```bash
|
|
343
|
+
npx zero db:export --table users --format json
|
|
344
|
+
npx zero db:export --table users --format csv --output ./exports/users.csv
|
|
345
|
+
npx zero db:import ./exports/users.csv --table users --format csv
|
|
346
|
+
npx zero db:import ./exports/users.json --table users --format json
|
|
347
|
+
```
|
|
252
348
|
|
|
253
|
-
|
|
254
|
-
|
|
349
|
+
#### **ZPack Maintenance**
|
|
350
|
+
```bash
|
|
351
|
+
npx zero zpack:vacuum ./data.zpack
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
#### **Interactive REPL**
|
|
355
|
+
```bash
|
|
356
|
+
npx zero repl
|
|
255
357
|
```
|
|
358
|
+
**Available REPL commands:**
|
|
359
|
+
- `.exit` - Exit REPL
|
|
360
|
+
- `.help` - Show available commands
|
|
361
|
+
- `.stats` - Show database stats
|
|
362
|
+
- `.metrics` - Show performance metrics
|
|
363
|
+
- `.clear` - Clear screen
|
|
364
|
+
- `select <table>` - Select all from table
|
|
365
|
+
- `count <table>` - Count records in table
|
|
366
|
+
|
|
367
|
+
#### **Global Options**
|
|
368
|
+
- `-c, --config <path>` - Path to config file (default: `zero.config.ts`)
|
|
369
|
+
- `-h, --help` - Show help for command
|
|
370
|
+
- `-V, --version` - Output version number
|
|
256
371
|
|
|
257
372
|
---
|
|
258
373
|
|
|
259
374
|
## 📥 Data Seeder
|
|
260
375
|
|
|
261
376
|
Populate your database with realistic mock data in seconds.
|
|
377
|
+
|
|
378
|
+
### Programmatic Usage
|
|
262
379
|
```typescript
|
|
263
380
|
const seeder = new database.DataSeeder(db);
|
|
264
381
|
await seeder.seed('users', 100, {
|
|
@@ -268,6 +385,20 @@ await seeder.seed('users', 100, {
|
|
|
268
385
|
});
|
|
269
386
|
```
|
|
270
387
|
|
|
388
|
+
### CLI Usage
|
|
389
|
+
```bash
|
|
390
|
+
npx zero db:seed --table users --count 100
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
### Supported Field Types
|
|
394
|
+
- `string` - Random string with configurable length
|
|
395
|
+
- `number` - Random number within min/max range
|
|
396
|
+
- `email` - Random email address with various domains
|
|
397
|
+
- `boolean` - Random true/false value
|
|
398
|
+
- `date` - Random date within the last decade
|
|
399
|
+
- `id` - Unique ID string
|
|
400
|
+
- `pick` - Random value from provided array
|
|
401
|
+
|
|
271
402
|
---
|
|
272
403
|
|
|
273
404
|
## 🛠️ Function Modules in Depth
|
|
@@ -284,38 +415,164 @@ const obj = functions.toon_module.parse(str);
|
|
|
284
415
|
### 🔢 Math & Statistics (`math_module`)
|
|
285
416
|
```typescript
|
|
286
417
|
const data = [10, 2, 38, 23, 21];
|
|
287
|
-
functions.math_module.mean(data);
|
|
288
|
-
functions.math_module.standardDeviation(data);
|
|
289
|
-
functions.math_module.isPrime(13);
|
|
418
|
+
functions.math_module.mean(data);
|
|
419
|
+
functions.math_module.standardDeviation(data);
|
|
420
|
+
functions.math_module.isPrime(13);
|
|
290
421
|
```
|
|
291
422
|
|
|
292
423
|
### 🔤 String & Slug Module (`string_module`)
|
|
293
424
|
```typescript
|
|
294
|
-
functions.string_module.generateSlug("ZeroHelper: The Best!");
|
|
295
|
-
functions.string_module.titleCase("hello world");
|
|
425
|
+
functions.string_module.generateSlug("ZeroHelper: The Best!");
|
|
426
|
+
functions.string_module.titleCase("hello world");
|
|
296
427
|
```
|
|
297
428
|
|
|
298
429
|
### 🎲 Random Module (`random_module`)
|
|
299
430
|
```typescript
|
|
300
|
-
functions.random_module.makeUniqueId();
|
|
301
|
-
functions.random_module.randomHex();
|
|
302
|
-
functions.random_module.randomEmoji();
|
|
431
|
+
functions.random_module.makeUniqueId();
|
|
432
|
+
functions.random_module.randomHex();
|
|
433
|
+
functions.random_module.randomEmoji();
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
### 🌐 HTTP Module (`http_module`)
|
|
437
|
+
```typescript
|
|
438
|
+
const data = await functions.http_module.fetchData('https://api.example.com/data');
|
|
439
|
+
const response = await functions.http_module.postData('https://api.example.com/post', { key: 'value' });
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
### 📅 Date Module (`date_module`)
|
|
443
|
+
```typescript
|
|
444
|
+
functions.date_module.formatDate(new Date(), 'YYYY-MM-DD');
|
|
445
|
+
functions.date_module.addDays(new Date(), 5);
|
|
446
|
+
functions.date_module.dateDifference(date1, date2);
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
### 🛠️ Array Module (`array_module`)
|
|
450
|
+
```typescript
|
|
451
|
+
functions.array_module.shuffleArray([1, 2, 3, 4, 5]);
|
|
452
|
+
functions.array_module.groupBy(users, 'role');
|
|
453
|
+
functions.array_module.pluck(users, 'email');
|
|
454
|
+
functions.array_module.sortBy(users, 'name');
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
### 🔧 Object Module (`object_module`)
|
|
458
|
+
```typescript
|
|
459
|
+
functions.object_module.deepMerge(obj1, obj2);
|
|
460
|
+
functions.object_module.filterObjectByKey(obj, ['name', 'email']);
|
|
303
461
|
```
|
|
304
462
|
|
|
305
463
|
---
|
|
306
464
|
|
|
307
465
|
## 🔐 Security & Cryptography
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
466
|
+
|
|
467
|
+
### Password Handling
|
|
468
|
+
```typescript
|
|
469
|
+
const hash = functions.crypto_module.hashPassword('securePassword123');
|
|
470
|
+
const isValid = functions.crypto_module.verifyPassword('securePassword123', hash);
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
### Text Encryption (AES-256-CBC)
|
|
474
|
+
```typescript
|
|
475
|
+
const { encryptedText, iv } = functions.crypto_module.encryptText('secret', 'mySecretKey');
|
|
476
|
+
const original = functions.crypto_module.decryptText(encryptedText, 'mySecretKey', iv);
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
### JWT Tokens
|
|
480
|
+
```typescript
|
|
481
|
+
const token = functions.crypto_module.generateJWT({ userId: 1 }, 'jwtSecret');
|
|
482
|
+
const payload = functions.crypto_module.verifyJWT(token, 'jwtSecret');
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
### Rate Limiting
|
|
486
|
+
|
|
487
|
+
#### Memory-based (Single Instance)
|
|
488
|
+
```typescript
|
|
489
|
+
const result = await functions.security_module.checkRateLimit('user:1', {
|
|
490
|
+
limit: 10,
|
|
491
|
+
window: 60,
|
|
492
|
+
storage: 'memory'
|
|
493
|
+
});
|
|
494
|
+
console.log(result.allowed); // true or false
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
#### Redis-based (Distributed Systems)
|
|
498
|
+
```typescript
|
|
499
|
+
const result = await functions.security_module.checkRateLimit('api:192.168.1.1', {
|
|
500
|
+
limit: 100,
|
|
501
|
+
window: 60,
|
|
502
|
+
storage: 'redis',
|
|
503
|
+
redisClient: redisDb
|
|
504
|
+
});
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
### Additional Security Functions
|
|
508
|
+
```typescript
|
|
509
|
+
functions.crypto_module.isPasswordStrong('MySecureP@ss123');
|
|
510
|
+
functions.crypto_module.validateUUID('550e8400-e29b-41d4-a716-446655440000');
|
|
511
|
+
functions.crypto_module.generateSalt();
|
|
512
|
+
```
|
|
312
513
|
|
|
313
514
|
---
|
|
314
515
|
|
|
315
516
|
## 🛡️ Validation & Sanitization Engine
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
517
|
+
|
|
518
|
+
### Schema Validation
|
|
519
|
+
```typescript
|
|
520
|
+
const schema = {
|
|
521
|
+
email: { required: true, type: 'string', pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
|
|
522
|
+
age: { required: false, type: 'number', min: 18, max: 120 },
|
|
523
|
+
password: { required: true, type: 'string', minLength: 8 }
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
const result = functions.validation_module.validateSchema(data, schema);
|
|
527
|
+
console.log(result.isValid);
|
|
528
|
+
console.log(result.errors);
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
### Input Sanitization
|
|
532
|
+
```typescript
|
|
533
|
+
const clean = functions.validation_module.sanitizeInput(userInput, {
|
|
534
|
+
trim: true,
|
|
535
|
+
removeHTML: true,
|
|
536
|
+
escape: true
|
|
537
|
+
});
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
### Utilities
|
|
541
|
+
```typescript
|
|
542
|
+
functions.validation_module.isEmail('test@example.com');
|
|
543
|
+
functions.validation_module.isPhone('+1234567890');
|
|
544
|
+
functions.validation_module.isURL('https://example.com');
|
|
545
|
+
functions.validation_module.sanitizeHTML('<script>alert("xss")</script>');
|
|
546
|
+
functions.validation_module.validateCreditCard('4111111111111111');
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
---
|
|
550
|
+
|
|
551
|
+
## 📝 Professional Logger Pro
|
|
552
|
+
|
|
553
|
+
```typescript
|
|
554
|
+
import { functions } from '@onurege3467/zerohelper';
|
|
555
|
+
|
|
556
|
+
const logger = functions.logger_module.createLogger({
|
|
557
|
+
level: 'info',
|
|
558
|
+
enableColors: true,
|
|
559
|
+
enableTimestamp: true,
|
|
560
|
+
logFile: './app.log'
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
logger.info('User logged in', { userId: 123 });
|
|
564
|
+
logger.warn('Rate limit approaching', { remaining: 10 });
|
|
565
|
+
logger.error('Database connection failed', { error: err.message });
|
|
566
|
+
logger.debug('Cache hit', { key: 'user:123' });
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
### Quick Logging Functions
|
|
570
|
+
```typescript
|
|
571
|
+
functions.logger_module.info('Message');
|
|
572
|
+
functions.logger_module.warn('Message');
|
|
573
|
+
functions.logger_module.error('Message');
|
|
574
|
+
functions.logger_module.debug('Message');
|
|
575
|
+
```
|
|
319
576
|
|
|
320
577
|
---
|
|
321
578
|
|
|
@@ -327,6 +584,127 @@ functions.random_module.randomEmoji(); // "🚀"
|
|
|
327
584
|
|
|
328
585
|
---
|
|
329
586
|
|
|
587
|
+
## 🎯 Real-World Use Cases
|
|
588
|
+
|
|
589
|
+
### E-Commerce Application
|
|
590
|
+
```typescript
|
|
591
|
+
const db = database.createDatabase({
|
|
592
|
+
adapter: 'postgres',
|
|
593
|
+
config: {
|
|
594
|
+
host: 'localhost',
|
|
595
|
+
user: 'admin',
|
|
596
|
+
password: 'secure',
|
|
597
|
+
database: 'shop',
|
|
598
|
+
cache: { type: 'redis', host: '127.0.0.1', ttl: 300000 }
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
await db.insert('products', { name: 'Laptop', price: 1500, stock: 10 });
|
|
603
|
+
await db.decrement('products', { stock: 1 }, { sku: 'PROD-001' });
|
|
604
|
+
await db.increment('orders', { total: 1500 }, { orderId: 1001 });
|
|
605
|
+
|
|
606
|
+
const hash = functions.crypto_module.hashPassword(userPassword);
|
|
607
|
+
await db.insert('users', { email, password: hash });
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
### AI/LLM Applications with TOON
|
|
611
|
+
```typescript
|
|
612
|
+
const toonDb = database.createDatabase({
|
|
613
|
+
adapter: 'toon',
|
|
614
|
+
config: { path: './ai-data.toon' }
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
await toonDb.insert('prompts', {
|
|
618
|
+
system: 'You are a helpful assistant designed for customer support.',
|
|
619
|
+
examples: [...],
|
|
620
|
+
temperature: 0.7,
|
|
621
|
+
maxTokens: 1000
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
const prompts = toonDb.select('prompts', { category: 'support' });
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
### High-Performance Logging with ZPack
|
|
628
|
+
```typescript
|
|
629
|
+
const zpack = database.createDatabase({
|
|
630
|
+
adapter: 'zpack',
|
|
631
|
+
config: { path: './logs.zpack', autoFlush: true }
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
await zpack.insert('events', {
|
|
635
|
+
timestamp: new Date(),
|
|
636
|
+
level: 'info',
|
|
637
|
+
message: 'User action recorded',
|
|
638
|
+
userId: 123,
|
|
639
|
+
action: 'purchase',
|
|
640
|
+
amount: 99.99
|
|
641
|
+
});
|
|
642
|
+
|
|
643
|
+
await zpack.vacuum();
|
|
644
|
+
```
|
|
645
|
+
|
|
646
|
+
### Distributed API Protection
|
|
647
|
+
```typescript
|
|
648
|
+
import { database } from '@onurege3467/zerohelper';
|
|
649
|
+
|
|
650
|
+
const redisDb = database.createDatabase({
|
|
651
|
+
adapter: 'redis',
|
|
652
|
+
config: { host: '127.0.0.1', port: 6379 }
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
async function handleApiRequest(ip: string) {
|
|
656
|
+
const rateLimit = await functions.security_module.checkRateLimit(`api:${ip}`, {
|
|
657
|
+
limit: 1000,
|
|
658
|
+
window: 3600,
|
|
659
|
+
storage: 'redis',
|
|
660
|
+
redisClient: redisDb
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
if (!rateLimit.allowed) {
|
|
664
|
+
throw new Error('Rate limit exceeded');
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
return processRequest();
|
|
668
|
+
}
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
---
|
|
672
|
+
|
|
673
|
+
## ❓ Frequently Asked Questions
|
|
674
|
+
|
|
675
|
+
### Q: Which adapter should I choose?
|
|
676
|
+
|
|
677
|
+
**A:**
|
|
678
|
+
- **ZPack**: High-volume logging, archival, audit trails
|
|
679
|
+
- **TOON**: AI/LLM applications, configs, human-readable needs
|
|
680
|
+
- **JSON**: Development, small projects, prototyping
|
|
681
|
+
- **SQLite**: Desktop apps, single-user applications
|
|
682
|
+
- **PostgreSQL/MySQL**: Web applications, enterprise systems
|
|
683
|
+
- **MongoDB**: Flexible document schemas, content management
|
|
684
|
+
- **Redis**: Caching, sessions, real-time features
|
|
685
|
+
|
|
686
|
+
### Q: How does TOON save tokens for LLMs?
|
|
687
|
+
|
|
688
|
+
**A:** TOON uses compact syntax like `[3]{name,age}: John,25 Jane,30 Bob,28` instead of verbose JSON arrays. This reduces token count by 30-60% while maintaining full data fidelity and human readability.
|
|
689
|
+
|
|
690
|
+
### Q: Is ZPack suitable for concurrent access?
|
|
691
|
+
|
|
692
|
+
**A:** ZPack is optimized for single-writer scenarios. For multi-threaded logging, consider using SQLite or a dedicated logging service with ZPack for archival.
|
|
693
|
+
|
|
694
|
+
### Q: Can I migrate between adapters?
|
|
695
|
+
|
|
696
|
+
**A:** Yes! All adapters implement the IDatabase interface. Export data using `db:export` CLI command and import to any other adapter.
|
|
697
|
+
|
|
698
|
+
### Q: What's the difference between memory and Redis rate limiting?
|
|
699
|
+
|
|
700
|
+
**A:** Memory storage is fast and suitable for single-instance applications. Redis storage enables distributed rate limiting across multiple server instances.
|
|
701
|
+
|
|
702
|
+
### Q: Does ZeroHelper support transactions?
|
|
703
|
+
|
|
704
|
+
**A:** SQL adapters (PostgreSQL, MySQL, SQLite) support transactions. NoSQL and file-based adapters have atomic operations but not full ACID transactions.
|
|
705
|
+
|
|
706
|
+
---
|
|
707
|
+
|
|
330
708
|
## 🏁 Final Words
|
|
331
709
|
|
|
332
710
|
**ZeroHelper** is the result of years of private commercial development, now open for the community to build the next generation of high-performance Node.js applications.
|