@dbcube/core 1.0.26 → 1.0.30

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/index.js CHANGED
@@ -6,7 +6,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  });
7
7
 
8
8
  // src/lib/Engine.ts
9
- import path from "path";
9
+ import path3 from "path";
10
10
 
11
11
  // src/lib/Arquitecture.ts
12
12
  import * as os from "os";
@@ -130,18 +130,359 @@ var Arquitecture = class {
130
130
  }
131
131
  };
132
132
 
133
+ // src/lib/Donwloader.ts
134
+ import * as fs from "fs";
135
+ import * as path from "path";
136
+ import * as os2 from "os";
137
+ import { https } from "follow-redirects";
138
+ import * as unzipper from "unzipper";
139
+ import ora from "ora";
140
+ import chalk from "chalk";
141
+ var Downloader = class {
142
+ static mainSpinner = null;
143
+ static currentSpinner = null;
144
+ static get(prefix) {
145
+ const arch2 = new Arquitecture();
146
+ const platform2 = arch2.getPlatform();
147
+ const architecture = arch2.getArchitecture();
148
+ const platformMap = {
149
+ windows: "windows",
150
+ linux: "linux",
151
+ darwin: "macos"
152
+ };
153
+ const archMap = {
154
+ x86_64: "x64",
155
+ aarch64: "arm64"
156
+ };
157
+ const plat = platformMap[platform2];
158
+ const archSuffix = archMap[architecture];
159
+ if (plat && archSuffix) {
160
+ const baseName = `${prefix}-engine-${plat}-${archSuffix}`;
161
+ const binaryName = platform2 === "windows" ? `${baseName}.exe` : baseName;
162
+ const url = `https://github.com/Dbcube/binaries/releases/download/${prefix}-engine/${prefix}-engine-latest-${plat}-${archSuffix}.zip`;
163
+ return {
164
+ name: binaryName,
165
+ url,
166
+ query_engine: binaryName,
167
+ schema_engine: `${prefix}-engine-${plat}-${archSuffix}${platform2 === "windows" ? ".exe" : ""}`
168
+ };
169
+ }
170
+ return {
171
+ name: "",
172
+ url: "",
173
+ query_engine: "",
174
+ schema_engine: ""
175
+ };
176
+ }
177
+ static async download(targetDir) {
178
+ const binaries = ["schema", "query", "sqlite"];
179
+ const binDir = targetDir || this.getDefaultBinDir();
180
+ fs.mkdirSync(binDir, { recursive: true });
181
+ this.mainSpinner = ora({
182
+ text: chalk.blue("Descargando binarios necesarios..."),
183
+ spinner: "dots12"
184
+ }).start();
185
+ for (let i = 0; i < binaries.length; i++) {
186
+ const prefix = binaries[i];
187
+ const maxRetries = 3;
188
+ let attempt = 0;
189
+ while (attempt <= maxRetries) {
190
+ try {
191
+ const binaryInfo = this.get(prefix);
192
+ if (!binaryInfo.name || !binaryInfo.url) {
193
+ throw new Error("Plataforma o arquitectura no soportada");
194
+ }
195
+ const tempZipPath = path.join(os2.tmpdir(), `dbcube-${prefix}-${Date.now()}.zip`);
196
+ const finalBinaryPath = path.join(binDir, binaryInfo.name);
197
+ if (fs.existsSync(finalBinaryPath)) {
198
+ this.updateMainProgress(prefix, i + 1, binaries.length, "exists");
199
+ break;
200
+ }
201
+ this.updateMainProgress(prefix, i + 1, binaries.length, "downloading");
202
+ await this.downloadFileWithProgress(binaryInfo.url, tempZipPath, prefix);
203
+ this.updateMainProgress(prefix, i + 1, binaries.length, "extracting");
204
+ await this.extractBinary(tempZipPath, finalBinaryPath, prefix);
205
+ this.updateMainProgress(prefix, i + 1, binaries.length, "completed");
206
+ break;
207
+ } catch (error) {
208
+ const errorMessage = error instanceof Error ? error.message : "Error desconocido";
209
+ if (attempt < maxRetries && (errorMessage.includes("ECONNRESET") || errorMessage.includes("timeout") || errorMessage.includes("ETIMEDOUT") || errorMessage.includes("ENOTFOUND"))) {
210
+ attempt++;
211
+ this.updateMainProgress(prefix, i + 1, binaries.length, "retrying", attempt);
212
+ await new Promise((resolve5) => setTimeout(resolve5, 2e3));
213
+ } else {
214
+ this.mainSpinner.fail(chalk.red(`Error descargando ${prefix}: ${errorMessage}`));
215
+ throw error;
216
+ }
217
+ }
218
+ }
219
+ }
220
+ this.mainSpinner.succeed(chalk.green("Binarios descargados correctamente"));
221
+ }
222
+ static updateMainProgress(binary, current, total, status, attempt) {
223
+ const progressBar = this.createProgressBar(current, total);
224
+ const statusEmojis = {
225
+ downloading: "\u{1F4E5}",
226
+ extracting: "\u{1F4E6}",
227
+ completed: "\u2705",
228
+ exists: "\u2705",
229
+ retrying: "\u{1F504}"
230
+ };
231
+ const statusMessages = {
232
+ downloading: chalk.blue("descargando"),
233
+ extracting: chalk.yellow("extrayendo"),
234
+ completed: chalk.green("completado"),
235
+ exists: chalk.gray("existe"),
236
+ retrying: chalk.orange(`reintentando (${attempt}/${3})`)
237
+ };
238
+ const emoji = statusEmojis[status] || "\u{1F4E5}";
239
+ const message = statusMessages[status] || status;
240
+ this.mainSpinner.text = `${progressBar} ${emoji} ${chalk.bold(binary)} - ${message}`;
241
+ }
242
+ static createProgressBar(current, total, width = 20) {
243
+ const filled = Math.round(current / total * width);
244
+ const empty = width - filled;
245
+ const filledBar = chalk.green("\u2588".repeat(filled));
246
+ const emptyBar = chalk.gray("\u2591".repeat(empty));
247
+ const percentage = chalk.bold(`${current}/${total}`);
248
+ return `[${filledBar}${emptyBar}] ${percentage}`;
249
+ }
250
+ static downloadFileWithProgress(url, outputPath, prefix) {
251
+ return new Promise((resolve5, reject) => {
252
+ const request = https.get(url, { timeout: 6e4 }, (response) => {
253
+ if (response.statusCode === 302 || response.statusCode === 301) {
254
+ const redirectUrl = response.headers.location;
255
+ if (redirectUrl) {
256
+ return this.downloadFileWithProgress(redirectUrl, outputPath, prefix).then(resolve5).catch(reject);
257
+ }
258
+ }
259
+ if (response.statusCode !== 200) {
260
+ reject(new Error(`HTTP ${response.statusCode} para ${prefix}`));
261
+ return;
262
+ }
263
+ const file = fs.createWriteStream(outputPath);
264
+ const totalBytes = parseInt(response.headers["content-length"] || "0", 10);
265
+ let downloadedBytes = 0;
266
+ response.on("data", (chunk) => {
267
+ downloadedBytes += chunk.length;
268
+ file.write(chunk);
269
+ if (totalBytes > 0) {
270
+ const progress = {
271
+ downloaded: downloadedBytes,
272
+ total: totalBytes,
273
+ percentage: downloadedBytes / totalBytes * 100
274
+ };
275
+ this.updateDownloadProgress(prefix, progress);
276
+ }
277
+ });
278
+ response.on("end", () => {
279
+ file.end();
280
+ resolve5();
281
+ });
282
+ response.on("error", (err) => {
283
+ file.close();
284
+ this.cleanupFile(outputPath);
285
+ reject(err);
286
+ });
287
+ file.on("error", (err) => {
288
+ file.close();
289
+ this.cleanupFile(outputPath);
290
+ reject(err);
291
+ });
292
+ });
293
+ request.on("error", reject);
294
+ request.on("timeout", () => {
295
+ request.destroy();
296
+ reject(new Error(`Timeout descargando ${prefix}`));
297
+ });
298
+ });
299
+ }
300
+ static updateDownloadProgress(binary, progress) {
301
+ const percentage = progress.percentage.toFixed(1);
302
+ const downloaded = (progress.downloaded / 1024 / 1024).toFixed(1);
303
+ const total = (progress.total / 1024 / 1024).toFixed(1);
304
+ const barWidth = 15;
305
+ const filled = Math.round(progress.percentage / 100 * barWidth);
306
+ const empty = barWidth - filled;
307
+ const progressBar = chalk.green("\u2588".repeat(filled)) + chalk.gray("\u2591".repeat(empty));
308
+ const progressText = `[${progressBar}] ${percentage}% (${downloaded}/${total}MB)`;
309
+ this.mainSpinner.text = `\u{1F4E5} ${chalk.bold(binary)} - ${progressText}`;
310
+ }
311
+ static extractBinary(zipPath, outputPath, prefix) {
312
+ return new Promise((resolve5, reject) => {
313
+ let extracted = false;
314
+ fs.createReadStream(zipPath).pipe(unzipper.Parse()).on("entry", (entry) => {
315
+ if (entry.type === "File" && !extracted) {
316
+ extracted = true;
317
+ const writeStream = fs.createWriteStream(outputPath);
318
+ entry.pipe(writeStream);
319
+ writeStream.on("finish", () => {
320
+ if (process.platform !== "win32") {
321
+ fs.chmodSync(outputPath, 493);
322
+ }
323
+ this.cleanupFile(zipPath);
324
+ resolve5();
325
+ });
326
+ writeStream.on("error", (err) => {
327
+ this.cleanupFile(zipPath);
328
+ reject(err);
329
+ });
330
+ } else {
331
+ entry.autodrain();
332
+ }
333
+ }).on("error", (err) => {
334
+ this.cleanupFile(zipPath);
335
+ reject(err);
336
+ }).on("close", () => {
337
+ if (!extracted) {
338
+ this.cleanupFile(zipPath);
339
+ reject(new Error(`No se encontr\xF3 archivo v\xE1lido en el ZIP para ${prefix}`));
340
+ }
341
+ });
342
+ });
343
+ }
344
+ static cleanupFile(filePath) {
345
+ try {
346
+ if (fs.existsSync(filePath)) {
347
+ fs.unlinkSync(filePath);
348
+ }
349
+ } catch {
350
+ }
351
+ }
352
+ static getDefaultBinDir() {
353
+ const possibleDirs = [
354
+ path.resolve(process.cwd(), "bin"),
355
+ path.resolve(process.cwd(), "node_modules", ".dbcube", "bin"),
356
+ path.resolve(__dirname, "..", "bin")
357
+ ];
358
+ for (const dir of possibleDirs) {
359
+ try {
360
+ if (!fs.existsSync(dir)) {
361
+ fs.mkdirSync(dir, { recursive: true });
362
+ }
363
+ const testFile = path.join(dir, ".test");
364
+ fs.writeFileSync(testFile, "test");
365
+ fs.unlinkSync(testFile);
366
+ return dir;
367
+ } catch {
368
+ continue;
369
+ }
370
+ }
371
+ const tempDir = path.join(os2.tmpdir(), "dbcube-bin");
372
+ fs.mkdirSync(tempDir, { recursive: true });
373
+ return tempDir;
374
+ }
375
+ };
376
+
133
377
  // src/lib/Binary.ts
378
+ import * as fs2 from "fs";
379
+ import * as path2 from "path";
134
380
  var Binary = class {
135
- static get() {
381
+ static isDownloading = false;
382
+ static downloadPromise = null;
383
+ static async ensureBinariesExist() {
384
+ if (this.isDownloading && this.downloadPromise) {
385
+ await this.downloadPromise;
386
+ return;
387
+ }
388
+ const binDir = this.getBinDir();
389
+ const binaries = ["schema", "query", "sqlite"];
390
+ const allExist = binaries.every((prefix) => {
391
+ const binaryInfo = Downloader.get(prefix);
392
+ if (!binaryInfo.name) return false;
393
+ const binaryPath = path2.join(binDir, binaryInfo.name);
394
+ return fs2.existsSync(binaryPath);
395
+ });
396
+ if (allExist) {
397
+ return;
398
+ }
399
+ if (!this.isDownloading) {
400
+ this.isDownloading = true;
401
+ this.downloadPromise = this.downloadBinaries();
402
+ try {
403
+ await this.downloadPromise;
404
+ } finally {
405
+ this.isDownloading = false;
406
+ this.downloadPromise = null;
407
+ }
408
+ }
409
+ }
410
+ static async downloadBinaries() {
411
+ try {
412
+ const binDir = this.getBinDir();
413
+ await Downloader.download(binDir);
414
+ } catch (error) {
415
+ console.warn("\u26A0\uFE0F DBCube: Error descargando binarios:", error.message);
416
+ console.log("\u{1F527} Los binarios se intentar\xE1n descargar en la pr\xF3xima ejecuci\xF3n");
417
+ }
418
+ }
419
+ static getBinDir() {
420
+ const possibleDirs = [
421
+ path2.resolve(process.cwd(), "bin"),
422
+ path2.resolve(process.cwd(), "node_modules", ".dbcube", "bin"),
423
+ path2.resolve(__dirname, "..", "bin")
424
+ ];
425
+ for (const dir of possibleDirs) {
426
+ try {
427
+ if (!fs2.existsSync(dir)) {
428
+ fs2.mkdirSync(dir, { recursive: true });
429
+ }
430
+ return dir;
431
+ } catch {
432
+ continue;
433
+ }
434
+ }
435
+ return process.cwd();
436
+ }
437
+ static async get() {
438
+ await this.ensureBinariesExist();
136
439
  const arch2 = new Arquitecture();
137
440
  const platform2 = arch2.getPlatform();
138
441
  const architecture = arch2.getArchitecture();
442
+ const binDir = this.getBinDir();
443
+ const getFullPath = (binaryName) => {
444
+ return path2.join(binDir, binaryName);
445
+ };
139
446
  switch (platform2) {
140
447
  case "windows":
141
448
  if (architecture == "x86_64") {
142
449
  return {
143
- query_engine: "query-engine-windows-x64.exe",
144
- schema_engine: "schema-engine-windows-x64.exe"
450
+ query_engine: getFullPath("query-engine-windows-x64.exe"),
451
+ schema_engine: getFullPath("schema-engine-windows-x64.exe")
452
+ };
453
+ }
454
+ if (architecture == "aarch64") {
455
+ return {
456
+ query_engine: getFullPath("query-engine-windows-arm64.exe"),
457
+ schema_engine: getFullPath("schema-engine-windows-arm64.exe")
458
+ };
459
+ }
460
+ break;
461
+ case "linux":
462
+ if (architecture == "x86_64") {
463
+ return {
464
+ query_engine: getFullPath("query-engine-linux-x64"),
465
+ schema_engine: getFullPath("schema-engine-linux-x64")
466
+ };
467
+ }
468
+ if (architecture == "aarch64") {
469
+ return {
470
+ query_engine: getFullPath("query-engine-linux-arm64"),
471
+ schema_engine: getFullPath("schema-engine-linux-arm64")
472
+ };
473
+ }
474
+ break;
475
+ case "macos":
476
+ if (architecture == "x86_64") {
477
+ return {
478
+ query_engine: getFullPath("query-engine-macos-x64"),
479
+ schema_engine: getFullPath("schema-engine-macos-x64")
480
+ };
481
+ }
482
+ if (architecture == "aarch64") {
483
+ return {
484
+ query_engine: getFullPath("query-engine-macos-arm64"),
485
+ schema_engine: getFullPath("schema-engine-macos-arm64")
145
486
  };
146
487
  }
147
488
  break;
@@ -198,19 +539,19 @@ var Engine = class {
198
539
  name;
199
540
  config;
200
541
  arguments;
201
- binary;
542
+ binary = null;
202
543
  timeout;
203
544
  constructor(name, timeout = 3e4) {
204
545
  this.name = name;
205
546
  this.config = this.setConfig(name);
206
- const binary = Binary.get();
207
- this.binary = {
208
- query_engine: path.resolve(__dirname, "../bin", binary.query_engine),
209
- schema_engine: path.resolve(__dirname, "../bin", binary.schema_engine)
210
- };
211
547
  this.arguments = this.setArguments();
212
548
  this.timeout = timeout;
213
549
  }
550
+ async initializeBinary() {
551
+ if (!this.binary) {
552
+ this.binary = await Binary.get();
553
+ }
554
+ }
214
555
  setArguments() {
215
556
  let args = [];
216
557
  if (this.config.type == "sqlite") {
@@ -248,7 +589,7 @@ var Engine = class {
248
589
  }
249
590
  setConfig(name) {
250
591
  const configInstance = new Config();
251
- const configFilePath = path.resolve(process.cwd(), "dbcube.config.js");
592
+ const configFilePath = path3.resolve(process.cwd(), "dbcube.config.js");
252
593
  const configFn = __require(configFilePath);
253
594
  if (typeof configFn === "function") {
254
595
  configFn(configInstance);
@@ -261,7 +602,11 @@ var Engine = class {
261
602
  return this.config;
262
603
  }
263
604
  async run(binary, args) {
264
- return new Promise((resolve3, reject) => {
605
+ await this.initializeBinary();
606
+ if (!this.binary) {
607
+ throw new Error("Binary not initialized");
608
+ }
609
+ return new Promise((resolve5, reject) => {
265
610
  const child = spawn(this.binary[binary], [...this.arguments, ...args]);
266
611
  let stdoutBuffer = "";
267
612
  let stderrBuffer = "";
@@ -277,7 +622,7 @@ var Engine = class {
277
622
  if (!isResolved) {
278
623
  isResolved = true;
279
624
  clearTimeout(timeoutId);
280
- resolve3(response);
625
+ resolve5(response);
281
626
  }
282
627
  };
283
628
  child.stdout.on("data", (data) => {
@@ -347,7 +692,7 @@ var Engine = class {
347
692
 
348
693
  // src/lib/SqliteExecutor.ts
349
694
  import { exec } from "child_process";
350
- import * as path2 from "path";
695
+ import * as path4 from "path";
351
696
  import { promisify } from "util";
352
697
  var execAsync = promisify(exec);
353
698
  var SqliteExecutor = class {
@@ -358,11 +703,11 @@ var SqliteExecutor = class {
358
703
  this.binaryPath = this.getBinaryPath();
359
704
  }
360
705
  getBinaryPath() {
361
- const binDir = path2.resolve(__dirname, "..", "bin");
706
+ const binDir = path4.resolve(__dirname, "..", "bin");
362
707
  const platform2 = process.platform;
363
708
  const extension = platform2 === "win32" ? ".exe" : "";
364
709
  const binaryName = `sqlite-engine${extension}`;
365
- return path2.join(binDir, binaryName);
710
+ return path4.join(binDir, binaryName);
366
711
  }
367
712
  async executeBinary(args) {
368
713
  const command = `"${this.binaryPath}" ${args.map((arg) => `"${arg}"`).join(" ")}`;
@@ -504,9 +849,9 @@ var SqliteExecutor = class {
504
849
  };
505
850
 
506
851
  // src/lib/DbConfig.ts
507
- import * as path3 from "path";
508
- import fs from "fs";
509
- var rootPath = path3.resolve(process.cwd(), ".dbcube");
852
+ import * as path5 from "path";
853
+ import fs3 from "fs";
854
+ var rootPath = path5.resolve(process.cwd(), ".dbcube");
510
855
  var SQLite = class {
511
856
  executor = null;
512
857
  database;
@@ -516,11 +861,11 @@ var SQLite = class {
516
861
  async ifExist() {
517
862
  if (this.database) {
518
863
  const dbPath = this.database || ":memory:";
519
- const configPath = path3.join(rootPath, dbPath + ".db");
520
- if (!fs.existsSync(rootPath)) {
521
- fs.mkdirSync(rootPath, { recursive: true });
864
+ const configPath = path5.join(rootPath, dbPath + ".db");
865
+ if (!fs3.existsSync(rootPath)) {
866
+ fs3.mkdirSync(rootPath, { recursive: true });
522
867
  }
523
- if (fs.existsSync(configPath)) {
868
+ if (fs3.existsSync(configPath)) {
524
869
  return true;
525
870
  }
526
871
  if (!this.executor) {
@@ -531,13 +876,13 @@ var SQLite = class {
531
876
  return false;
532
877
  }
533
878
  async connect() {
534
- return new Promise(async (resolve3, reject) => {
879
+ return new Promise(async (resolve5, reject) => {
535
880
  try {
536
881
  if (!this.executor) {
537
882
  const dbPath = this.database || ":memory:";
538
- const configPath = path3.join(rootPath, dbPath + ".db");
539
- if (!fs.existsSync(rootPath)) {
540
- fs.mkdirSync(rootPath, { recursive: true });
883
+ const configPath = path5.join(rootPath, dbPath + ".db");
884
+ if (!fs3.existsSync(rootPath)) {
885
+ fs3.mkdirSync(rootPath, { recursive: true });
541
886
  }
542
887
  this.executor = new SqliteExecutor(configPath);
543
888
  const connected = await this.executor.connect();
@@ -545,22 +890,22 @@ var SQLite = class {
545
890
  throw new Error("Failed to connect to SQLite database");
546
891
  }
547
892
  }
548
- resolve3(this.executor);
893
+ resolve5(this.executor);
549
894
  } catch (error) {
550
895
  reject(error);
551
896
  }
552
897
  });
553
898
  }
554
899
  async disconnect() {
555
- return new Promise((resolve3) => {
900
+ return new Promise((resolve5) => {
556
901
  if (this.executor) {
557
902
  this.executor = null;
558
903
  }
559
- resolve3();
904
+ resolve5();
560
905
  });
561
906
  }
562
907
  async query(sqlQuery) {
563
- return new Promise(async (resolve3) => {
908
+ return new Promise(async (resolve5) => {
564
909
  try {
565
910
  if (typeof sqlQuery !== "string") {
566
911
  throw new Error("The SQL query must be a string.");
@@ -573,20 +918,20 @@ var SQLite = class {
573
918
  }
574
919
  const result = await this.executor.queryMultiple(sqlQuery);
575
920
  if (result.status === "error") {
576
- resolve3({
921
+ resolve5({
577
922
  status: "error",
578
923
  message: result.message,
579
924
  data: null
580
925
  });
581
926
  } else {
582
- resolve3({
927
+ resolve5({
583
928
  status: "success",
584
929
  message: "Query executed successfully",
585
930
  data: result.data
586
931
  });
587
932
  }
588
933
  } catch (error) {
589
- resolve3({
934
+ resolve5({
590
935
  status: "error",
591
936
  message: error.message || "An error occurred while executing the query.",
592
937
  data: null
@@ -595,7 +940,7 @@ var SQLite = class {
595
940
  });
596
941
  }
597
942
  async queryWithParameters(sqlQuery, params = []) {
598
- return new Promise(async (resolve3) => {
943
+ return new Promise(async (resolve5) => {
599
944
  try {
600
945
  if (typeof sqlQuery !== "string") {
601
946
  throw new Error("The SQL query must be a string.");
@@ -611,13 +956,13 @@ var SQLite = class {
611
956
  }
612
957
  const result = await this.executor.query(sqlQuery, params);
613
958
  if (result.status === "error") {
614
- resolve3({
959
+ resolve5({
615
960
  status: "error",
616
961
  message: result.message,
617
962
  data: null
618
963
  });
619
964
  } else {
620
- resolve3({
965
+ resolve5({
621
966
  status: "success",
622
967
  message: "Query executed successfully",
623
968
  data: result.data
@@ -625,7 +970,7 @@ var SQLite = class {
625
970
  }
626
971
  } catch (error) {
627
972
  console.log(error);
628
- resolve3({
973
+ resolve5({
629
974
  status: "error",
630
975
  message: error.message || "An error occurred while executing the query.",
631
976
  data: null
@@ -719,8 +1064,8 @@ var DbConfig = new SQLite({ DATABASE: "config" });
719
1064
  var DbConfig_default = DbConfig;
720
1065
 
721
1066
  // src/lib/FileLogger.ts
722
- import * as fs2 from "fs";
723
- import * as path4 from "path";
1067
+ import * as fs4 from "fs";
1068
+ import * as path6 from "path";
724
1069
  import { EventEmitter } from "events";
725
1070
  var FileLogger = class _FileLogger extends EventEmitter {
726
1071
  static watchers = /* @__PURE__ */ new Map();
@@ -735,9 +1080,9 @@ var FileLogger = class _FileLogger extends EventEmitter {
735
1080
  */
736
1081
  static async write(filePath, message, level = "INFO", append = true) {
737
1082
  try {
738
- const dir = path4.dirname(filePath);
739
- if (!fs2.existsSync(dir)) {
740
- fs2.mkdirSync(dir, { recursive: true });
1083
+ const dir = path6.dirname(filePath);
1084
+ if (!fs4.existsSync(dir)) {
1085
+ fs4.mkdirSync(dir, { recursive: true });
741
1086
  }
742
1087
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
743
1088
  const formattedMessage = `[${timestamp}] [${level}] ${message}
@@ -747,9 +1092,9 @@ var FileLogger = class _FileLogger extends EventEmitter {
747
1092
  return true;
748
1093
  }
749
1094
  if (append) {
750
- await fs2.promises.appendFile(filePath, formattedMessage, "utf8");
1095
+ await fs4.promises.appendFile(filePath, formattedMessage, "utf8");
751
1096
  } else {
752
- await fs2.promises.writeFile(filePath, formattedMessage, "utf8");
1097
+ await fs4.promises.writeFile(filePath, formattedMessage, "utf8");
753
1098
  }
754
1099
  return true;
755
1100
  } catch (error) {
@@ -774,12 +1119,12 @@ var FileLogger = class _FileLogger extends EventEmitter {
774
1119
  const buffer = _FileLogger.buffers.get(filePath);
775
1120
  if (buffer && buffer.length > 0) {
776
1121
  try {
777
- const dir = path4.dirname(filePath);
778
- if (!fs2.existsSync(dir)) {
779
- fs2.mkdirSync(dir, { recursive: true });
1122
+ const dir = path6.dirname(filePath);
1123
+ if (!fs4.existsSync(dir)) {
1124
+ fs4.mkdirSync(dir, { recursive: true });
780
1125
  }
781
1126
  const content = buffer.join("");
782
- await fs2.promises.appendFile(filePath, content, "utf8");
1127
+ await fs4.promises.appendFile(filePath, content, "utf8");
783
1128
  _FileLogger.buffers.delete(filePath);
784
1129
  return true;
785
1130
  } catch (error) {
@@ -915,10 +1260,10 @@ var FileLogger = class _FileLogger extends EventEmitter {
915
1260
  // Si debe retornar como array de líneas
916
1261
  } = options;
917
1262
  try {
918
- if (!fs2.existsSync(filePath)) {
1263
+ if (!fs4.existsSync(filePath)) {
919
1264
  return asArray ? [] : "";
920
1265
  }
921
- let content = await fs2.promises.readFile(filePath, "utf8");
1266
+ let content = await fs4.promises.readFile(filePath, "utf8");
922
1267
  if (asArray) {
923
1268
  let linesArray = content.split("\n").filter((line) => line.trim() !== "");
924
1269
  if (lines !== null) {
@@ -961,15 +1306,15 @@ var FileLogger = class _FileLogger extends EventEmitter {
961
1306
  } = options;
962
1307
  let lastSize = 0;
963
1308
  let lastPosition = 0;
964
- if (fs2.existsSync(filePath)) {
965
- const stats = fs2.statSync(filePath);
1309
+ if (fs4.existsSync(filePath)) {
1310
+ const stats = fs4.statSync(filePath);
966
1311
  lastSize = stats.size;
967
1312
  lastPosition = fromEnd ? stats.size : 0;
968
1313
  }
969
1314
  const listener = async (curr, prev) => {
970
1315
  try {
971
1316
  if (curr.size > lastSize) {
972
- const stream = fs2.createReadStream(filePath, {
1317
+ const stream = fs4.createReadStream(filePath, {
973
1318
  start: lastPosition,
974
1319
  end: curr.size - 1,
975
1320
  encoding: "utf8"
@@ -997,7 +1342,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
997
1342
  console.error("Error en watcher:", error);
998
1343
  }
999
1344
  };
1000
- fs2.watchFile(filePath, { persistent, interval }, listener);
1345
+ fs4.watchFile(filePath, { persistent, interval }, listener);
1001
1346
  const watcherId = `${filePath}_${Date.now()}`;
1002
1347
  _FileLogger.watchers.set(watcherId, listener);
1003
1348
  return {
@@ -1005,7 +1350,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
1005
1350
  stop: () => {
1006
1351
  const storedListener = _FileLogger.watchers.get(watcherId);
1007
1352
  if (storedListener) {
1008
- fs2.unwatchFile(filePath, storedListener);
1353
+ fs4.unwatchFile(filePath, storedListener);
1009
1354
  _FileLogger.watchers.delete(watcherId);
1010
1355
  }
1011
1356
  },
@@ -1018,7 +1363,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
1018
1363
  static stopAllWatchers() {
1019
1364
  for (const [watcherId] of _FileLogger.watchers) {
1020
1365
  const filePath = watcherId.split("_")[0];
1021
- fs2.unwatchFile(filePath);
1366
+ fs4.unwatchFile(filePath);
1022
1367
  }
1023
1368
  _FileLogger.watchers.clear();
1024
1369
  }
@@ -1048,7 +1393,7 @@ var FileLogger = class _FileLogger extends EventEmitter {
1048
1393
  if (lines.length > maxLines) {
1049
1394
  const keepLines = lines.slice(-maxLines);
1050
1395
  const content = keepLines.join("\n") + "\n";
1051
- await fs2.promises.writeFile(filePath, content, "utf8");
1396
+ await fs4.promises.writeFile(filePath, content, "utf8");
1052
1397
  return lines.length - maxLines;
1053
1398
  }
1054
1399
  return 0;
@@ -1063,8 +1408,8 @@ var FileLogger = class _FileLogger extends EventEmitter {
1063
1408
  */
1064
1409
  static async deleteLogFile(filePath) {
1065
1410
  try {
1066
- if (fs2.existsSync(filePath)) {
1067
- await fs2.promises.unlink(filePath);
1411
+ if (fs4.existsSync(filePath)) {
1412
+ await fs4.promises.unlink(filePath);
1068
1413
  return true;
1069
1414
  }
1070
1415
  return false;