tero 0.0.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.
package/dist/backup.js ADDED
@@ -0,0 +1,411 @@
1
+ import { createReadStream, existsSync, readdirSync, statSync } from "fs";
2
+ import { join, basename } from "path";
3
+ import tar from "tar";
4
+ import { S3Client, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
+ import { Upload } from "@aws-sdk/lib-storage";
6
+ export class BackupManager {
7
+ s3Client;
8
+ scheduledBackups = new Map();
9
+ config;
10
+ dbPath;
11
+ constructor(dbPath, config) {
12
+ this.dbPath = dbPath;
13
+ this.config = config;
14
+ if (config.cloudStorage) {
15
+ this.initializeCloudStorage(config.cloudStorage);
16
+ }
17
+ }
18
+ initializeCloudStorage(cloudConfig) {
19
+ try {
20
+ const clientConfig = {
21
+ region: cloudConfig.region,
22
+ credentials: {
23
+ accessKeyId: cloudConfig.accessKeyId,
24
+ secretAccessKey: cloudConfig.secretAccessKey,
25
+ },
26
+ };
27
+ // Configure for Cloudflare R2 or custom endpoints
28
+ if (cloudConfig.endpoint) {
29
+ clientConfig.endpoint = cloudConfig.endpoint;
30
+ clientConfig.forcePathStyle = true; // Required for R2
31
+ }
32
+ this.s3Client = new S3Client(clientConfig);
33
+ }
34
+ catch (error) {
35
+ throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`);
36
+ }
37
+ }
38
+ parseInterval(interval) {
39
+ const match = interval.match(/^(\d+)([hdw])$/);
40
+ if (!match)
41
+ throw new Error(`Invalid interval format: ${interval}`);
42
+ const [, num, unit] = match;
43
+ const value = parseInt(num);
44
+ switch (unit) {
45
+ case 'h': return value * 60 * 60 * 1000; // hours to ms
46
+ case 'd': return value * 24 * 60 * 60 * 1000; // days to ms
47
+ case 'w': return value * 7 * 24 * 60 * 60 * 1000; // weeks to ms
48
+ default: throw new Error(`Unsupported time unit: ${unit}`);
49
+ }
50
+ }
51
+ parseRetention(retention) {
52
+ const match = retention.match(/^(\d+)([dwy])$/);
53
+ if (!match)
54
+ throw new Error(`Invalid retention format: ${retention}`);
55
+ const [, num, unit] = match;
56
+ const value = parseInt(num);
57
+ switch (unit) {
58
+ case 'd': return value * 24 * 60 * 60 * 1000; // days to ms
59
+ case 'w': return value * 7 * 24 * 60 * 60 * 1000; // weeks to ms
60
+ case 'y': return value * 365 * 24 * 60 * 60 * 1000; // years to ms
61
+ default: throw new Error(`Unsupported retention unit: ${unit}`);
62
+ }
63
+ }
64
+ async calculateChecksum(filePath) {
65
+ const crypto = await import('crypto');
66
+ const hash = crypto.createHash('sha256');
67
+ const stream = createReadStream(filePath);
68
+ return new Promise((resolve, reject) => {
69
+ stream.on('data', (data) => hash.update(data));
70
+ stream.on('end', () => resolve(hash.digest('hex')));
71
+ stream.on('error', reject);
72
+ });
73
+ }
74
+ async getJsonFiles() {
75
+ try {
76
+ if (!existsSync(this.dbPath)) {
77
+ return [];
78
+ }
79
+ const files = readdirSync(this.dbPath)
80
+ .filter(file => file.endsWith('.json'))
81
+ .map(file => {
82
+ const filePath = join(this.dbPath, file);
83
+ const stats = statSync(filePath);
84
+ return {
85
+ path: filePath,
86
+ name: file,
87
+ size: stats.size,
88
+ mtime: stats.mtime
89
+ };
90
+ });
91
+ return files;
92
+ }
93
+ catch (error) {
94
+ throw new Error(`Failed to get JSON files: ${error instanceof Error ? error.message : 'Unknown error'}`);
95
+ }
96
+ }
97
+ async createArchiveBackup() {
98
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
99
+ const backupFileName = `tero-backup-${timestamp}.tar.gz`;
100
+ const backupPath = this.config.localPath
101
+ ? join(this.config.localPath, backupFileName)
102
+ : join(this.dbPath, backupFileName);
103
+ try {
104
+ const jsonFiles = await this.getJsonFiles();
105
+ if (jsonFiles.length === 0) {
106
+ throw new Error('No JSON files found to backup');
107
+ }
108
+ // Ensure backup directory exists
109
+ if (this.config.localPath) {
110
+ const fs = await import('fs/promises');
111
+ await fs.mkdir(this.config.localPath, { recursive: true });
112
+ }
113
+ // Create tar.gz archive
114
+ await tar.create({
115
+ file: backupPath,
116
+ cwd: this.dbPath,
117
+ gzip: true,
118
+ prefix: 'tero-data/'
119
+ }, jsonFiles.map(f => f.name));
120
+ const stats = statSync(backupPath);
121
+ const checksum = await this.calculateChecksum(backupPath);
122
+ const metadata = {
123
+ timestamp: new Date().toISOString(),
124
+ format: 'archive',
125
+ fileCount: jsonFiles.length,
126
+ totalSize: stats.size,
127
+ checksum,
128
+ retention: this.config.retention || '30d'
129
+ };
130
+ return { filePath: backupPath, metadata };
131
+ }
132
+ catch (error) {
133
+ throw new Error(`Failed to create archive backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
134
+ }
135
+ }
136
+ async createIndividualBackup() {
137
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
138
+ const backupDir = this.config.localPath
139
+ ? join(this.config.localPath, `tero-backup-${timestamp}`)
140
+ : join(this.dbPath, `.backup-${timestamp}`);
141
+ try {
142
+ const jsonFiles = await this.getJsonFiles();
143
+ if (jsonFiles.length === 0) {
144
+ throw new Error('No JSON files found to backup');
145
+ }
146
+ // Create backup directory
147
+ const fs = await import('fs/promises');
148
+ await fs.mkdir(backupDir, { recursive: true });
149
+ const backedUpFiles = [];
150
+ let totalSize = 0;
151
+ // Copy each JSON file
152
+ for (const file of jsonFiles) {
153
+ const destPath = join(backupDir, file.name);
154
+ await fs.copyFile(file.path, destPath);
155
+ backedUpFiles.push(destPath);
156
+ totalSize += file.size;
157
+ // Add metadata file only if specifically requested and useful
158
+ if (this.config.includeMetadata && this.config.metadataUse !== 'none') {
159
+ const metadataPath = join(backupDir, `${file.name}.meta`);
160
+ // Only include metadata that's actually useful
161
+ const fileMetadata = {
162
+ backupTime: new Date().toISOString(),
163
+ originalSize: file.size,
164
+ lastModified: file.mtime.toISOString()
165
+ };
166
+ // Add specific metadata based on intended use
167
+ switch (this.config.metadataUse) {
168
+ case 'verification':
169
+ // Add checksum for integrity verification
170
+ const crypto = await import('crypto');
171
+ const hash = crypto.createHash('sha256');
172
+ const fileContent = await fs.readFile(file.path);
173
+ hash.update(fileContent);
174
+ fileMetadata.checksum = hash.digest('hex');
175
+ break;
176
+ case 'audit':
177
+ // Add audit trail information
178
+ fileMetadata.originalPath = file.path;
179
+ fileMetadata.backupVersion = '1.4.0';
180
+ break;
181
+ case 'recovery':
182
+ // Add recovery-specific information
183
+ fileMetadata.recoveryPriority = file.name.includes('user') ? 'high' : 'normal';
184
+ break;
185
+ }
186
+ await fs.writeFile(metadataPath, JSON.stringify(fileMetadata, null, 2));
187
+ backedUpFiles.push(metadataPath);
188
+ }
189
+ }
190
+ const metadata = {
191
+ timestamp: new Date().toISOString(),
192
+ format: 'individual',
193
+ fileCount: jsonFiles.length,
194
+ totalSize,
195
+ checksum: '', // Individual files don't have a single checksum
196
+ retention: this.config.retention || '30d'
197
+ };
198
+ // Save backup metadata
199
+ const metadataPath = join(backupDir, 'backup-metadata.json');
200
+ await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2));
201
+ backedUpFiles.push(metadataPath);
202
+ return { files: backedUpFiles, metadata };
203
+ }
204
+ catch (error) {
205
+ throw new Error(`Failed to create individual backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
206
+ }
207
+ }
208
+ async uploadToCloud(localPath, cloudKey) {
209
+ if (!this.s3Client || !this.config.cloudStorage) {
210
+ throw new Error('Cloud storage not configured');
211
+ }
212
+ try {
213
+ const fileStream = createReadStream(localPath);
214
+ const stats = statSync(localPath);
215
+ const upload = new Upload({
216
+ client: this.s3Client,
217
+ params: {
218
+ Bucket: this.config.cloudStorage.bucket,
219
+ Key: cloudKey,
220
+ Body: fileStream,
221
+ ContentLength: stats.size,
222
+ Metadata: {
223
+ 'backup-timestamp': new Date().toISOString(),
224
+ 'source-db': basename(this.dbPath),
225
+ 'backup-format': this.config.format
226
+ }
227
+ }
228
+ });
229
+ await upload.done();
230
+ }
231
+ catch (error) {
232
+ throw new Error(`Failed to upload to cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`);
233
+ }
234
+ }
235
+ async uploadDirectoryToCloud(localDir, cloudPrefix) {
236
+ if (!this.s3Client || !this.config.cloudStorage) {
237
+ throw new Error('Cloud storage not configured');
238
+ }
239
+ try {
240
+ const fs = await import('fs/promises');
241
+ const files = await fs.readdir(localDir);
242
+ const uploadPromises = files.map(async (file) => {
243
+ const localFilePath = join(localDir, file);
244
+ const cloudKey = `${cloudPrefix}/${file}`;
245
+ await this.uploadToCloud(localFilePath, cloudKey);
246
+ });
247
+ await Promise.all(uploadPromises);
248
+ }
249
+ catch (error) {
250
+ throw new Error(`Failed to upload directory to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`);
251
+ }
252
+ }
253
+ getCloudKey(filename) {
254
+ const prefix = this.config.cloudStorage?.pathPrefix || 'tero-backups';
255
+ const dbName = basename(this.dbPath);
256
+ return `${prefix}/${dbName}/${filename}`;
257
+ }
258
+ async performBackup() {
259
+ try {
260
+ console.log(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
261
+ let metadata;
262
+ let cloudUploaded = false;
263
+ if (this.config.format === 'archive') {
264
+ const { filePath, metadata: backupMetadata } = await this.createArchiveBackup();
265
+ metadata = backupMetadata;
266
+ // Upload to cloud if configured
267
+ if (this.config.cloudStorage && this.s3Client) {
268
+ const cloudKey = this.getCloudKey(basename(filePath));
269
+ await this.uploadToCloud(filePath, cloudKey);
270
+ cloudUploaded = true;
271
+ console.log(`☁️ Uploaded archive backup to cloud: ${cloudKey}`);
272
+ }
273
+ console.log(`✅ Archive backup completed: ${filePath}`);
274
+ }
275
+ else {
276
+ const { files, metadata: backupMetadata } = await this.createIndividualBackup();
277
+ metadata = backupMetadata;
278
+ // Upload to cloud if configured
279
+ if (this.config.cloudStorage && this.s3Client) {
280
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
281
+ const cloudPrefix = this.getCloudKey(`individual-${timestamp}`);
282
+ await this.uploadDirectoryToCloud(files[0].split('/').slice(0, -1).join('/'), cloudPrefix);
283
+ cloudUploaded = true;
284
+ console.log(`☁️ Uploaded individual backup to cloud: ${cloudPrefix}`);
285
+ }
286
+ console.log(`✅ Individual backup completed: ${files.length} files`);
287
+ }
288
+ // Clean up old backups based on retention policy
289
+ if (this.config.retention) {
290
+ await this.cleanupOldBackups();
291
+ }
292
+ return { success: true, metadata, cloudUploaded };
293
+ }
294
+ catch (error) {
295
+ console.error(`❌ Backup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
296
+ return {
297
+ success: false,
298
+ metadata: {
299
+ timestamp: new Date().toISOString(),
300
+ format: this.config.format,
301
+ fileCount: 0,
302
+ totalSize: 0,
303
+ checksum: '',
304
+ retention: this.config.retention || '30d'
305
+ }
306
+ };
307
+ }
308
+ }
309
+ async cleanupOldBackups() {
310
+ if (!this.config.retention || !this.config.cloudStorage || !this.s3Client) {
311
+ return;
312
+ }
313
+ try {
314
+ const retentionMs = this.parseRetention(this.config.retention);
315
+ const cutoffDate = new Date(Date.now() - retentionMs);
316
+ const prefix = this.getCloudKey('');
317
+ const listCommand = new ListObjectsV2Command({
318
+ Bucket: this.config.cloudStorage.bucket,
319
+ Prefix: prefix
320
+ });
321
+ const response = await this.s3Client.send(listCommand);
322
+ if (response.Contents) {
323
+ const oldObjects = response.Contents.filter((obj) => obj.LastModified && obj.LastModified < cutoffDate);
324
+ const deletePromises = oldObjects.map((obj) => {
325
+ if (obj.Key) {
326
+ return this.s3Client.send(new DeleteObjectCommand({
327
+ Bucket: this.config.cloudStorage.bucket,
328
+ Key: obj.Key
329
+ }));
330
+ }
331
+ return null;
332
+ }).filter(Boolean);
333
+ await Promise.all(deletePromises);
334
+ if (oldObjects.length > 0) {
335
+ console.log(`🗑️ Cleaned up ${oldObjects.length} old backup(s) from cloud storage`);
336
+ }
337
+ }
338
+ }
339
+ catch (error) {
340
+ console.warn(`⚠️ Failed to cleanup old backups: ${error instanceof Error ? error.message : 'Unknown error'}`);
341
+ }
342
+ }
343
+ scheduleBackup(config) {
344
+ const scheduleId = `backup-${Date.now()}`;
345
+ try {
346
+ const intervalMs = this.parseInterval(config.interval);
347
+ // Update config with new retention if provided
348
+ if (config.retention) {
349
+ this.config.retention = config.retention;
350
+ }
351
+ const performScheduledBackup = async () => {
352
+ console.log(`⏰ Scheduled backup triggered (${config.interval} interval)`);
353
+ await this.performBackup();
354
+ };
355
+ // Perform initial backup
356
+ performScheduledBackup();
357
+ // Schedule recurring backups
358
+ const timer = setInterval(performScheduledBackup, intervalMs);
359
+ this.scheduledBackups.set(scheduleId, timer);
360
+ console.log(`📅 Backup scheduled: ${config.interval} interval, ${config.retention || this.config.retention} retention`);
361
+ return scheduleId;
362
+ }
363
+ catch (error) {
364
+ throw new Error(`Failed to schedule backup: ${error instanceof Error ? error.message : 'Unknown error'}`);
365
+ }
366
+ }
367
+ cancelScheduledBackup(scheduleId) {
368
+ const timer = this.scheduledBackups.get(scheduleId);
369
+ if (timer) {
370
+ clearInterval(timer);
371
+ this.scheduledBackups.delete(scheduleId);
372
+ console.log(`❌ Cancelled scheduled backup: ${scheduleId}`);
373
+ return true;
374
+ }
375
+ return false;
376
+ }
377
+ getScheduledBackups() {
378
+ return Array.from(this.scheduledBackups.keys()).map(id => ({
379
+ id,
380
+ active: true
381
+ }));
382
+ }
383
+ async testCloudConnection() {
384
+ if (!this.s3Client || !this.config.cloudStorage) {
385
+ return { success: false, message: 'Cloud storage not configured' };
386
+ }
387
+ try {
388
+ // Test by listing objects in the bucket
389
+ const listCommand = new ListObjectsV2Command({
390
+ Bucket: this.config.cloudStorage.bucket,
391
+ MaxKeys: 1
392
+ });
393
+ await this.s3Client.send(listCommand);
394
+ return { success: true, message: 'Cloud storage connection successful' };
395
+ }
396
+ catch (error) {
397
+ return {
398
+ success: false,
399
+ message: `Cloud storage connection failed: ${error instanceof Error ? error.message : 'Unknown error'}`
400
+ };
401
+ }
402
+ }
403
+ destroy() {
404
+ // Cancel all scheduled backups
405
+ for (const [id, timer] of this.scheduledBackups) {
406
+ clearInterval(timer);
407
+ }
408
+ this.scheduledBackups.clear();
409
+ console.log('🛑 BackupManager destroyed, all scheduled backups cancelled');
410
+ }
411
+ }
package/dist/fn.js ADDED
@@ -0,0 +1,192 @@
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
+ }