tero 0.0.0 → 0.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.
- package/README.md +50 -24
- package/dist/acid-engine.d.ts +63 -0
- package/dist/acid-engine.js +76 -10
- package/dist/backup.d.ts +66 -0
- package/dist/backup.js +75 -22
- package/dist/index.d.ts +115 -0
- package/dist/index.js +55 -24
- package/dist/recovery.d.ts +46 -0
- package/dist/schema.d.ts +61 -0
- package/package.json +14 -11
- package/dist/fn.js +0 -192
- package/dist/transaction.js +0 -476
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { DocumentSchema, ValidationResult } from "./schema.js";
|
|
2
|
+
import { BackupConfig, BackupMetadata } from "./backup.js";
|
|
3
|
+
import { RecoveryConfig, RecoveryResult, FileRecoveryInfo } from "./recovery.js";
|
|
4
|
+
interface TeroConfig {
|
|
5
|
+
directory?: string;
|
|
6
|
+
cacheSize?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class Tero {
|
|
9
|
+
private teroDirectory;
|
|
10
|
+
private cacheSize;
|
|
11
|
+
private cache;
|
|
12
|
+
private cacheHits;
|
|
13
|
+
private cacheRequests;
|
|
14
|
+
private acidEngine;
|
|
15
|
+
private schemaValidator;
|
|
16
|
+
private backupManager?;
|
|
17
|
+
private dataRecovery?;
|
|
18
|
+
constructor(config?: TeroConfig);
|
|
19
|
+
private initializeDirectories;
|
|
20
|
+
private validateKey;
|
|
21
|
+
private invalidateCacheKeys;
|
|
22
|
+
private updateCache;
|
|
23
|
+
beginTransaction(): string;
|
|
24
|
+
write(transactionId: string, key: string, data: any, options?: {
|
|
25
|
+
validate?: boolean;
|
|
26
|
+
schemaName?: string;
|
|
27
|
+
strict?: boolean;
|
|
28
|
+
}): Promise<ValidationResult | void>;
|
|
29
|
+
read(transactionId: string, key: string): Promise<any>;
|
|
30
|
+
delete(transactionId: string, key: string): Promise<void>;
|
|
31
|
+
commit(transactionId: string): Promise<void>;
|
|
32
|
+
rollback(transactionId: string): Promise<void>;
|
|
33
|
+
create(key: string, initialData?: any, options?: {
|
|
34
|
+
validate?: boolean;
|
|
35
|
+
schemaName?: string;
|
|
36
|
+
strict?: boolean;
|
|
37
|
+
}): Promise<ValidationResult | boolean>;
|
|
38
|
+
update(key: string, data: any, options?: {
|
|
39
|
+
validate?: boolean;
|
|
40
|
+
schemaName?: string;
|
|
41
|
+
strict?: boolean;
|
|
42
|
+
}): Promise<ValidationResult | void>;
|
|
43
|
+
get(key: string): Promise<any>;
|
|
44
|
+
remove(key: string): Promise<void>;
|
|
45
|
+
exists(key: string): boolean;
|
|
46
|
+
batchWrite(operations: Array<{
|
|
47
|
+
key: string;
|
|
48
|
+
data: any;
|
|
49
|
+
}>, options?: {
|
|
50
|
+
validate?: boolean;
|
|
51
|
+
schemaName?: string;
|
|
52
|
+
strict?: boolean;
|
|
53
|
+
}): Promise<void>;
|
|
54
|
+
batchRead(keys: string[]): Promise<{
|
|
55
|
+
[key: string]: any;
|
|
56
|
+
}>;
|
|
57
|
+
transferMoney(fromKey: string, toKey: string, amount: number): Promise<void>;
|
|
58
|
+
setSchema(collectionName: string, schema: DocumentSchema): void;
|
|
59
|
+
getSchema(collectionName: string): DocumentSchema | undefined;
|
|
60
|
+
removeSchema(collectionName: string): boolean;
|
|
61
|
+
validateData(collectionName: string, data: any): ValidationResult;
|
|
62
|
+
configureBackup(config: BackupConfig): void;
|
|
63
|
+
performBackup(): Promise<{
|
|
64
|
+
success: boolean;
|
|
65
|
+
metadata: BackupMetadata;
|
|
66
|
+
cloudUploaded?: boolean;
|
|
67
|
+
}>;
|
|
68
|
+
configureDataRecovery(config: RecoveryConfig): void;
|
|
69
|
+
recoverFromCloud(key: string): Promise<boolean>;
|
|
70
|
+
recoverAllFromCloud(): Promise<RecoveryResult>;
|
|
71
|
+
getCacheStats(): {
|
|
72
|
+
size: number;
|
|
73
|
+
maxSize: number;
|
|
74
|
+
hitRate: number;
|
|
75
|
+
};
|
|
76
|
+
getActiveTransactions(): string[];
|
|
77
|
+
forceCheckpoint(): void;
|
|
78
|
+
verifyDataIntegrity(): Promise<{
|
|
79
|
+
totalFiles: number;
|
|
80
|
+
corruptedFiles: string[];
|
|
81
|
+
missingFiles: string[];
|
|
82
|
+
healthy: boolean;
|
|
83
|
+
}>;
|
|
84
|
+
clearCache(): void;
|
|
85
|
+
destroy(): void;
|
|
86
|
+
/**
|
|
87
|
+
* Generates a unique identifier with a custom prefix.
|
|
88
|
+
*
|
|
89
|
+
* This method creates MongoDB ObjectId-like unique identifiers that consist of:
|
|
90
|
+
* - 4-byte timestamp (seconds since Unix epoch)
|
|
91
|
+
* - 5-byte process-unique random value
|
|
92
|
+
* - 3-byte incrementing counter
|
|
93
|
+
*
|
|
94
|
+
* The generated ID is guaranteed to be unique across processes and time,
|
|
95
|
+
* making it suitable for distributed systems and concurrent operations.
|
|
96
|
+
*
|
|
97
|
+
* @param prefix - A string prefix to prepend to the generated ID
|
|
98
|
+
* @returns A unique identifier string in the format: `${prefix}-${hexString}`
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* const db = new Tero();
|
|
103
|
+
*
|
|
104
|
+
* // Generate unique IDs for different purposes
|
|
105
|
+
* const userId = db.getNewId('user'); // e.g., "user-507f1f77bcf86cd799439011"
|
|
106
|
+
* const sessionId = db.getNewId('session'); // e.g., "session-507f1f77bcf86cd799439012"
|
|
107
|
+
* const logId = db.getNewId('log'); // e.g., "log-507f1f77bcf86cd799439013"
|
|
108
|
+
*
|
|
109
|
+
* // Use as document keys
|
|
110
|
+
* await db.create(userId, { name: 'Alice', email: 'alice@example.com' });
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
getNewId(prefix: string): string;
|
|
114
|
+
}
|
|
115
|
+
export { DocumentSchema, ValidationResult, BackupConfig, BackupMetadata, RecoveryConfig, RecoveryResult, FileRecoveryInfo };
|
package/dist/index.js
CHANGED
|
@@ -3,10 +3,12 @@ import { ACIDStorageEngine } from "./acid-engine.js";
|
|
|
3
3
|
import { SchemaValidator } from "./schema.js";
|
|
4
4
|
import { BackupManager } from "./backup.js";
|
|
5
5
|
import { DataRecovery } from "./recovery.js";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import QuickLRU from "quick-lru";
|
|
6
8
|
export class Tero {
|
|
7
9
|
teroDirectory = "TeroDB";
|
|
8
10
|
cacheSize = 100;
|
|
9
|
-
cache
|
|
11
|
+
cache;
|
|
10
12
|
cacheHits = 0;
|
|
11
13
|
cacheRequests = 0;
|
|
12
14
|
acidEngine;
|
|
@@ -21,10 +23,14 @@ export class Tero {
|
|
|
21
23
|
this.teroDirectory = directory.replace(/[^a-zA-Z0-9_\-\/]/g, '');
|
|
22
24
|
}
|
|
23
25
|
if (typeof cacheSize === "number" && cacheSize > 0) {
|
|
24
|
-
this.cacheSize = Math.min(cacheSize,
|
|
26
|
+
this.cacheSize = Math.min(cacheSize, 1000); // Cap at 1k entries
|
|
25
27
|
}
|
|
26
28
|
// Create directories with proper error handling
|
|
27
29
|
this.initializeDirectories();
|
|
30
|
+
// Initialize QuickLRU cache
|
|
31
|
+
this.cache = new QuickLRU({
|
|
32
|
+
maxSize: this.cacheSize
|
|
33
|
+
});
|
|
28
34
|
// Initialize ACID storage engine (primary system)
|
|
29
35
|
this.acidEngine = new ACIDStorageEngine(this.teroDirectory);
|
|
30
36
|
// Initialize schema validator
|
|
@@ -57,32 +63,14 @@ export class Tero {
|
|
|
57
63
|
throw new Error('Key contains invalid characters');
|
|
58
64
|
}
|
|
59
65
|
}
|
|
60
|
-
evictOldestCacheEntry() {
|
|
61
|
-
if (this.cache.size === 0)
|
|
62
|
-
return;
|
|
63
|
-
let oldestKey = '';
|
|
64
|
-
let oldestTime = Date.now();
|
|
65
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
66
|
-
if (entry.lastAccessed < oldestTime) {
|
|
67
|
-
oldestTime = entry.lastAccessed;
|
|
68
|
-
oldestKey = key;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
if (oldestKey) {
|
|
72
|
-
this.cache.delete(oldestKey);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
66
|
invalidateCacheKeys(keys) {
|
|
76
67
|
for (const key of keys) {
|
|
77
68
|
this.cache.delete(key);
|
|
78
69
|
}
|
|
79
70
|
}
|
|
80
71
|
updateCache(key, data, transactionId) {
|
|
81
|
-
if (this.cache.size >= this.cacheSize) {
|
|
82
|
-
this.evictOldestCacheEntry();
|
|
83
|
-
}
|
|
84
72
|
this.cache.set(key, {
|
|
85
|
-
data:
|
|
73
|
+
data: data,
|
|
86
74
|
lastAccessed: Date.now(),
|
|
87
75
|
transactionId
|
|
88
76
|
});
|
|
@@ -170,13 +158,14 @@ export class Tero {
|
|
|
170
158
|
throw new Error(`Transaction ${transactionId} not found or not active`);
|
|
171
159
|
}
|
|
172
160
|
await this.acidEngine.commitTransaction(transactionId);
|
|
173
|
-
//
|
|
161
|
+
// Invalidate cache entries for this transaction to force fresh reads
|
|
162
|
+
const keysToInvalidate = [];
|
|
174
163
|
for (const [key, entry] of this.cache.entries()) {
|
|
175
164
|
if (entry.transactionId === transactionId) {
|
|
176
|
-
|
|
177
|
-
entry.transactionId = undefined;
|
|
165
|
+
keysToInvalidate.push(key);
|
|
178
166
|
}
|
|
179
167
|
}
|
|
168
|
+
this.invalidateCacheKeys(keysToInvalidate);
|
|
180
169
|
}
|
|
181
170
|
catch (error) {
|
|
182
171
|
throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
@@ -447,4 +436,46 @@ export class Tero {
|
|
|
447
436
|
}
|
|
448
437
|
this.clearCache();
|
|
449
438
|
}
|
|
439
|
+
/**
|
|
440
|
+
* Generates a unique identifier with a custom prefix.
|
|
441
|
+
*
|
|
442
|
+
* This method creates MongoDB ObjectId-like unique identifiers that consist of:
|
|
443
|
+
* - 4-byte timestamp (seconds since Unix epoch)
|
|
444
|
+
* - 5-byte process-unique random value
|
|
445
|
+
* - 3-byte incrementing counter
|
|
446
|
+
*
|
|
447
|
+
* The generated ID is guaranteed to be unique across processes and time,
|
|
448
|
+
* making it suitable for distributed systems and concurrent operations.
|
|
449
|
+
*
|
|
450
|
+
* @param prefix - A string prefix to prepend to the generated ID
|
|
451
|
+
* @returns A unique identifier string in the format: `${prefix}-${hexString}`
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* ```typescript
|
|
455
|
+
* const db = new Tero();
|
|
456
|
+
*
|
|
457
|
+
* // Generate unique IDs for different purposes
|
|
458
|
+
* const userId = db.getNewId('user'); // e.g., "user-507f1f77bcf86cd799439011"
|
|
459
|
+
* const sessionId = db.getNewId('session'); // e.g., "session-507f1f77bcf86cd799439012"
|
|
460
|
+
* const logId = db.getNewId('log'); // e.g., "log-507f1f77bcf86cd799439013"
|
|
461
|
+
*
|
|
462
|
+
* // Use as document keys
|
|
463
|
+
* await db.create(userId, { name: 'Alice', email: 'alice@example.com' });
|
|
464
|
+
* ```
|
|
465
|
+
*/
|
|
466
|
+
getNewId(prefix) {
|
|
467
|
+
const PROCESS_UNIQUE = randomBytes(5);
|
|
468
|
+
const buffer = Buffer.allocUnsafe(12);
|
|
469
|
+
let index = ~~(Math.random() * 0xffffff);
|
|
470
|
+
const time = ~~(Date.now() / 1000);
|
|
471
|
+
const inc = (index = (index + 1) % 0xffffff);
|
|
472
|
+
// 4-byte timestamp (seconds since Unix epoch)
|
|
473
|
+
buffer.writeUInt32BE(time, 0);
|
|
474
|
+
// 5-byte process unique identifier
|
|
475
|
+
buffer.set(PROCESS_UNIQUE, 4);
|
|
476
|
+
// 3-byte incrementing counter
|
|
477
|
+
buffer.writeUIntBE(inc, 9, 3);
|
|
478
|
+
// Convert to hexadecimal string and prepend prefix
|
|
479
|
+
return prefix + "-" + buffer.toString("hex");
|
|
480
|
+
}
|
|
450
481
|
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { CloudStorageConfig } from "./backup.js";
|
|
2
|
+
export interface RecoveryConfig {
|
|
3
|
+
cloudStorage: CloudStorageConfig;
|
|
4
|
+
localPath: string;
|
|
5
|
+
autoRecover?: boolean;
|
|
6
|
+
recoveryTimeout?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface RecoveryResult {
|
|
9
|
+
success: boolean;
|
|
10
|
+
recovered: string[];
|
|
11
|
+
failed: string[];
|
|
12
|
+
totalFiles: number;
|
|
13
|
+
duration: number;
|
|
14
|
+
}
|
|
15
|
+
export interface FileRecoveryInfo {
|
|
16
|
+
key: string;
|
|
17
|
+
exists: boolean;
|
|
18
|
+
size?: number;
|
|
19
|
+
lastModified?: Date;
|
|
20
|
+
recovered?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export declare class DataRecovery {
|
|
23
|
+
private s3Client;
|
|
24
|
+
private config;
|
|
25
|
+
constructor(config: RecoveryConfig);
|
|
26
|
+
private initializeCloudStorage;
|
|
27
|
+
private getCloudKey;
|
|
28
|
+
checkFileInCloud(key: string): Promise<FileRecoveryInfo>;
|
|
29
|
+
recoverSingleFile(key: string): Promise<boolean>;
|
|
30
|
+
recoverFromArchive(archiveName?: string): Promise<RecoveryResult>;
|
|
31
|
+
recoverIndividualFiles(keys?: string[]): Promise<RecoveryResult>;
|
|
32
|
+
listAvailableArchives(): Promise<string[]>;
|
|
33
|
+
listAvailableFiles(): Promise<string[]>;
|
|
34
|
+
private downloadFile;
|
|
35
|
+
private extractArchive;
|
|
36
|
+
testCloudConnection(): Promise<{
|
|
37
|
+
success: boolean;
|
|
38
|
+
message: string;
|
|
39
|
+
}>;
|
|
40
|
+
getRecoveryInfo(): Promise<{
|
|
41
|
+
cloudFiles: number;
|
|
42
|
+
localFiles: number;
|
|
43
|
+
missingLocally: string[];
|
|
44
|
+
availableForRecovery: string[];
|
|
45
|
+
}>;
|
|
46
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export interface SchemaField {
|
|
2
|
+
type: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'date' | 'any';
|
|
3
|
+
required?: boolean;
|
|
4
|
+
min?: number;
|
|
5
|
+
max?: number;
|
|
6
|
+
format?: 'email' | 'url' | 'uuid' | 'date' | 'time' | 'datetime' | 'phone' | 'ip';
|
|
7
|
+
pattern?: string;
|
|
8
|
+
enum?: any[];
|
|
9
|
+
default?: any;
|
|
10
|
+
properties?: {
|
|
11
|
+
[key: string]: SchemaField;
|
|
12
|
+
};
|
|
13
|
+
items?: SchemaField;
|
|
14
|
+
custom?: (value: any) => boolean | string;
|
|
15
|
+
}
|
|
16
|
+
export interface DocumentSchema {
|
|
17
|
+
[fieldName: string]: SchemaField;
|
|
18
|
+
}
|
|
19
|
+
export interface ValidationError {
|
|
20
|
+
field: string;
|
|
21
|
+
message: string;
|
|
22
|
+
value?: any;
|
|
23
|
+
expected?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface ValidationResult {
|
|
26
|
+
valid: boolean;
|
|
27
|
+
errors: ValidationError[];
|
|
28
|
+
data?: any;
|
|
29
|
+
}
|
|
30
|
+
export declare class SchemaValidator {
|
|
31
|
+
private schemas;
|
|
32
|
+
setSchema(collectionName: string, schema: DocumentSchema): void;
|
|
33
|
+
getSchema(collectionName: string): DocumentSchema | undefined;
|
|
34
|
+
removeSchema(collectionName: string): boolean;
|
|
35
|
+
hasSchema(collectionName: string): boolean;
|
|
36
|
+
listSchemas(): string[];
|
|
37
|
+
private validateSchemaDefinition;
|
|
38
|
+
validate(collectionName: string, data: any): ValidationResult;
|
|
39
|
+
private validateAndSanitizeData;
|
|
40
|
+
private validateField;
|
|
41
|
+
private validateType;
|
|
42
|
+
private validateString;
|
|
43
|
+
private validateNumber;
|
|
44
|
+
private validateBoolean;
|
|
45
|
+
private validateDate;
|
|
46
|
+
private validateArray;
|
|
47
|
+
private validateObject;
|
|
48
|
+
private validateFormat;
|
|
49
|
+
getSchemaStats(): {
|
|
50
|
+
totalSchemas: number;
|
|
51
|
+
schemaNames: string[];
|
|
52
|
+
totalFields: number;
|
|
53
|
+
};
|
|
54
|
+
exportSchemas(): {
|
|
55
|
+
[collectionName: string]: DocumentSchema;
|
|
56
|
+
};
|
|
57
|
+
importSchemas(schemas: {
|
|
58
|
+
[collectionName: string]: DocumentSchema;
|
|
59
|
+
}): void;
|
|
60
|
+
clearAllSchemas(): void;
|
|
61
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tero",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.0.3",
|
|
4
|
+
"description": "Tero is a JSON database that provides ACID transactions, schema validation, automated cloud backup, and automatic cloud recovery",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -15,20 +15,19 @@
|
|
|
15
15
|
},
|
|
16
16
|
"homepage": "https://github.com/codedynasty-dev/tero.git",
|
|
17
17
|
"scripts": {
|
|
18
|
-
"build": "tsc",
|
|
18
|
+
"build": "npm run test && tsc",
|
|
19
19
|
"dev": "tsc --watch",
|
|
20
20
|
"test": "node run-tests.js",
|
|
21
|
-
"test:production": "node
|
|
22
|
-
"test:legacy": "node
|
|
23
|
-
"test:backup": "node
|
|
24
|
-
"test:schema": "node
|
|
21
|
+
"test:production": "node local_tests/production-test.js",
|
|
22
|
+
"test:legacy": "node local_tests/test.js",
|
|
23
|
+
"test:backup": "node local_tests/backup-test.js",
|
|
24
|
+
"test:schema": "node local_tests/schema-test.js",
|
|
25
25
|
"test:all": "npm run test",
|
|
26
26
|
"test:watch": "npm run test",
|
|
27
27
|
"prebuild": "echo 'Building Tero...'",
|
|
28
28
|
"postbuild": "echo 'Build completed successfully!'",
|
|
29
29
|
"pretest": "echo 'Running Tero test suite...'",
|
|
30
30
|
"posttest": "echo 'Test suite completed!'",
|
|
31
|
-
"prepublishOnly": "npm run test",
|
|
32
31
|
"verify": "node verify-build.js && npm run test",
|
|
33
32
|
"ci": "npm run verify"
|
|
34
33
|
},
|
|
@@ -42,16 +41,20 @@
|
|
|
42
41
|
],
|
|
43
42
|
"license": "MIT",
|
|
44
43
|
"dependencies": {
|
|
44
|
+
"@aws-sdk/client-s3": "^3.0.0",
|
|
45
|
+
"@aws-sdk/lib-storage": "^3.0.0",
|
|
46
|
+
"cron": "^4.3.2",
|
|
45
47
|
"fs-ext": "^2.0.0",
|
|
46
48
|
"glob": "^9.3.4",
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"@aws-sdk/lib-storage": "^3.0.0"
|
|
49
|
+
"quick-lru": "^7.0.1",
|
|
50
|
+
"tar": "^6.1.13"
|
|
50
51
|
},
|
|
51
52
|
"devDependencies": {
|
|
53
|
+
"@types/cron": "^2.0.1",
|
|
52
54
|
"@types/fs-ext": "^2.0.3",
|
|
53
55
|
"@types/glob": "^8.1.0",
|
|
54
56
|
"@types/node": "^24.0.14",
|
|
57
|
+
"@types/quick-lru": "^2.0.0",
|
|
55
58
|
"@types/tar": "^6.1.13",
|
|
56
59
|
"typescript": "^5.8.3"
|
|
57
60
|
}
|
package/dist/fn.js
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import tar from "tar";
|
|
2
|
-
import glob from "glob";
|
|
3
|
-
import { openSync, readFileSync, writeFileSync, unlinkSync, closeSync, ftruncateSync, readdirSync, copyFileSync, mkdirSync, rmSync, existsSync, } from "fs";
|
|
4
|
-
import pkg from "fs-ext";
|
|
5
|
-
const { flockSync } = pkg;
|
|
6
|
-
export async function createFile(file) {
|
|
7
|
-
try {
|
|
8
|
-
if (!file || typeof file !== 'string') {
|
|
9
|
-
throw new Error('File path must be a non-empty string');
|
|
10
|
-
}
|
|
11
|
-
if (!existsSync(file)) {
|
|
12
|
-
writeFileSync(file, "{}", { flag: "w", encoding: "utf8" });
|
|
13
|
-
return true;
|
|
14
|
-
}
|
|
15
|
-
return false;
|
|
16
|
-
}
|
|
17
|
-
catch (error) {
|
|
18
|
-
throw new Error(`Failed to create file '${file}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
export async function backupFiles(source) {
|
|
22
|
-
try {
|
|
23
|
-
if (!source || typeof source !== 'string') {
|
|
24
|
-
throw new Error('Source path must be a non-empty string');
|
|
25
|
-
}
|
|
26
|
-
if (!existsSync(source)) {
|
|
27
|
-
throw new Error(`Source directory '${source}' does not exist`);
|
|
28
|
-
}
|
|
29
|
-
const backup = source + "/.backup";
|
|
30
|
-
// Ensure backup directory exists
|
|
31
|
-
if (!existsSync(backup)) {
|
|
32
|
-
mkdirSync(backup, { recursive: true });
|
|
33
|
-
}
|
|
34
|
-
// Copy files to backup directory
|
|
35
|
-
const files = readdirSync(source);
|
|
36
|
-
for (const file of files) {
|
|
37
|
-
if (file !== ".backup") {
|
|
38
|
-
try {
|
|
39
|
-
copyFileSync(`${source}/${file}`, `${backup}/${file}`);
|
|
40
|
-
}
|
|
41
|
-
catch (copyError) {
|
|
42
|
-
console.warn(`Warning: Could not backup file '${file}': ${copyError instanceof Error ? copyError.message : 'Unknown error'}`);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
// Create tar.gz backup
|
|
47
|
-
const filePattern = `${source}/*.json`;
|
|
48
|
-
const backupFile = `${source}/backup.tar.gz`;
|
|
49
|
-
try {
|
|
50
|
-
const matchedFiles = await glob(filePattern);
|
|
51
|
-
if (matchedFiles.length > 0) {
|
|
52
|
-
await tar.create({
|
|
53
|
-
file: backupFile,
|
|
54
|
-
cwd: source,
|
|
55
|
-
gzip: true
|
|
56
|
-
}, matchedFiles.map(f => f.replace(`${source}/`, '')));
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
catch (tarError) {
|
|
60
|
-
console.warn(`Warning: Could not create tar backup: ${tarError instanceof Error ? tarError.message : 'Unknown error'}`);
|
|
61
|
-
}
|
|
62
|
-
// Clean up copied files in backup directory
|
|
63
|
-
try {
|
|
64
|
-
rmSync(backup, { recursive: true, force: true });
|
|
65
|
-
mkdirSync(backup, { recursive: true });
|
|
66
|
-
}
|
|
67
|
-
catch (cleanupError) {
|
|
68
|
-
console.warn(`Warning: Could not clean backup directory: ${cleanupError instanceof Error ? cleanupError.message : 'Unknown error'}`);
|
|
69
|
-
}
|
|
70
|
-
return true;
|
|
71
|
-
}
|
|
72
|
-
catch (error) {
|
|
73
|
-
throw new Error(`Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
export async function getFile(filename) {
|
|
77
|
-
try {
|
|
78
|
-
if (!filename || typeof filename !== 'string') {
|
|
79
|
-
throw new Error('Filename must be a non-empty string');
|
|
80
|
-
}
|
|
81
|
-
if (!existsSync(filename)) {
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
|
-
const fileContents = readFileSync(filename, "utf-8");
|
|
85
|
-
if (!fileContents.trim()) {
|
|
86
|
-
return {};
|
|
87
|
-
}
|
|
88
|
-
return JSON.parse(fileContents);
|
|
89
|
-
}
|
|
90
|
-
catch (error) {
|
|
91
|
-
if (error instanceof SyntaxError) {
|
|
92
|
-
throw new Error(`Invalid JSON in file '${filename}': ${error.message}`);
|
|
93
|
-
}
|
|
94
|
-
throw new Error(`Failed to read file '${filename}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
export async function updateFile(filename, data) {
|
|
98
|
-
let fd = null;
|
|
99
|
-
try {
|
|
100
|
-
if (!filename || typeof filename !== 'string') {
|
|
101
|
-
throw new Error('Filename must be a non-empty string');
|
|
102
|
-
}
|
|
103
|
-
if (data === undefined || data === null) {
|
|
104
|
-
throw new Error('Data cannot be null or undefined');
|
|
105
|
-
}
|
|
106
|
-
// Ensure file exists
|
|
107
|
-
if (!existsSync(filename)) {
|
|
108
|
-
writeFileSync(filename, "{}", { encoding: "utf8" });
|
|
109
|
-
}
|
|
110
|
-
// Acquire an exclusive lock on the file
|
|
111
|
-
fd = openSync(filename, "r+");
|
|
112
|
-
flockSync(fd, "ex");
|
|
113
|
-
// Read existing data with better error handling
|
|
114
|
-
let existingData = {};
|
|
115
|
-
try {
|
|
116
|
-
const fileContents = readFileSync(filename, "utf-8");
|
|
117
|
-
if (fileContents.trim()) {
|
|
118
|
-
// Validate JSON before parsing
|
|
119
|
-
const trimmedContent = fileContents.trim();
|
|
120
|
-
if (!trimmedContent.startsWith('{') && !trimmedContent.startsWith('[')) {
|
|
121
|
-
throw new Error('Invalid JSON format');
|
|
122
|
-
}
|
|
123
|
-
existingData = JSON.parse(trimmedContent);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
catch (parseError) {
|
|
127
|
-
console.warn(`Warning: Could not parse existing data in '${filename}', starting with empty object`);
|
|
128
|
-
existingData = {};
|
|
129
|
-
}
|
|
130
|
-
// Deep merge data instead of shallow merge
|
|
131
|
-
const updatedData = deepMerge(existingData, data);
|
|
132
|
-
// Validate the merged data
|
|
133
|
-
const jsonString = JSON.stringify(updatedData, null, 2);
|
|
134
|
-
if (!jsonString || jsonString === 'undefined') {
|
|
135
|
-
throw new Error('Failed to serialize updated data');
|
|
136
|
-
}
|
|
137
|
-
// Write to temporary file first with atomic rename
|
|
138
|
-
const tmpFilename = `${filename}.tmp.${Date.now()}.${Math.random().toString(36).substr(2, 9)}`;
|
|
139
|
-
writeFileSync(tmpFilename, jsonString, { encoding: "utf8" });
|
|
140
|
-
// Verify the temporary file was written correctly
|
|
141
|
-
const verifyContent = readFileSync(tmpFilename, "utf-8");
|
|
142
|
-
if (verifyContent !== jsonString) {
|
|
143
|
-
unlinkSync(tmpFilename);
|
|
144
|
-
throw new Error('Temporary file verification failed');
|
|
145
|
-
}
|
|
146
|
-
// Atomic replace: truncate and write to original file
|
|
147
|
-
ftruncateSync(fd, 0);
|
|
148
|
-
writeFileSync(fd, jsonString, { encoding: "utf8" });
|
|
149
|
-
// Clean up temporary file
|
|
150
|
-
unlinkSync(tmpFilename);
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
throw new Error(`Failed to update file '${filename}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
154
|
-
}
|
|
155
|
-
finally {
|
|
156
|
-
// Always release the file lock and close file descriptor
|
|
157
|
-
if (fd !== null) {
|
|
158
|
-
try {
|
|
159
|
-
flockSync(fd, "un");
|
|
160
|
-
closeSync(fd);
|
|
161
|
-
}
|
|
162
|
-
catch (closeError) {
|
|
163
|
-
console.warn(`Warning: Could not properly close file descriptor: ${closeError instanceof Error ? closeError.message : 'Unknown error'}`);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
// Deep merge function to properly handle nested objects
|
|
169
|
-
function deepMerge(target, source) {
|
|
170
|
-
if (source === null || source === undefined) {
|
|
171
|
-
return target;
|
|
172
|
-
}
|
|
173
|
-
if (typeof source !== 'object' || Array.isArray(source)) {
|
|
174
|
-
return source;
|
|
175
|
-
}
|
|
176
|
-
if (typeof target !== 'object' || target === null || Array.isArray(target)) {
|
|
177
|
-
return source;
|
|
178
|
-
}
|
|
179
|
-
const result = { ...target };
|
|
180
|
-
for (const key in source) {
|
|
181
|
-
if (source.hasOwnProperty(key)) {
|
|
182
|
-
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
|
|
183
|
-
typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
|
|
184
|
-
result[key] = deepMerge(target[key], source[key]);
|
|
185
|
-
}
|
|
186
|
-
else {
|
|
187
|
-
result[key] = source[key];
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
return result;
|
|
192
|
-
}
|