@nmakarov/cli-toolkit 0.1.3 → 0.2.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.
@@ -0,0 +1,754 @@
1
+ // src/filestore/index.ts
2
+ import fs3 from "fs";
3
+ import path3 from "path";
4
+
5
+ // src/utils/os-utils.ts
6
+ import fs from "fs";
7
+ import path from "path";
8
+ import { execSync } from "child_process";
9
+ function getFreeDiskSpace(targetPath) {
10
+ try {
11
+ let pathToCheck = targetPath;
12
+ if (!fs.existsSync(targetPath)) {
13
+ const parentDir = path.dirname(targetPath);
14
+ if (fs.existsSync(parentDir)) {
15
+ pathToCheck = parentDir;
16
+ } else {
17
+ pathToCheck = process.platform === "win32" ? "C:\\" : "/";
18
+ }
19
+ }
20
+ if (process.platform === "win32") {
21
+ return null;
22
+ } else {
23
+ const stdout = execSync(`df -k "${pathToCheck}"`, { encoding: "utf8" });
24
+ const lines = stdout.trim().split("\n");
25
+ const parts = lines[1].split(/\s+/);
26
+ const freeKb = parseInt(parts[3], 10);
27
+ return freeKb * 1024;
28
+ }
29
+ } catch (error) {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ // src/utils/fs-utils.ts
35
+ import fs2 from "fs";
36
+ import path2 from "path";
37
+ async function ensurePath(...pathParts) {
38
+ const fullPath = path2.resolve(...pathParts);
39
+ if (!fs2.existsSync(fullPath)) {
40
+ await fs2.promises.mkdir(fullPath, { recursive: true });
41
+ }
42
+ return fullPath;
43
+ }
44
+ function getFileExtension(dataType) {
45
+ switch (dataType) {
46
+ case "json-array":
47
+ case "json-object":
48
+ return "json";
49
+ case "text":
50
+ return "txt";
51
+ case "xml":
52
+ return "xml";
53
+ default:
54
+ return "json";
55
+ }
56
+ }
57
+
58
+ // src/utils/format-utils.ts
59
+ function bytesToHumanReadable(bytes) {
60
+ if (bytes === 0) return "0 B";
61
+ const k = 1024;
62
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
63
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
64
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
65
+ }
66
+
67
+ // src/utils/date-utils.ts
68
+ function isTimestampFolder(folderName) {
69
+ const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|\.\d{3}Z)$/;
70
+ if (!isoRegex.test(folderName)) {
71
+ return false;
72
+ }
73
+ const date = new Date(folderName);
74
+ return !isNaN(date.getTime()) && date.getTime() > 0;
75
+ }
76
+
77
+ // src/filestore/serializers.ts
78
+ function detectDataType(data) {
79
+ if (Array.isArray(data)) {
80
+ return "json-array";
81
+ } else if (typeof data === "object" && data !== null) {
82
+ return "json-object";
83
+ } else if (typeof data === "string") {
84
+ const trimmed = data.trim();
85
+ if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
86
+ return "xml";
87
+ }
88
+ return "text";
89
+ } else {
90
+ return "text";
91
+ }
92
+ }
93
+ function serializeData(data) {
94
+ const dataType = detectDataType(data);
95
+ if (dataType === "json-array" || dataType === "json-object") {
96
+ return JSON.stringify(data, null, 4);
97
+ } else {
98
+ return String(data);
99
+ }
100
+ }
101
+ function deserializeData(rawData, dataType) {
102
+ if (dataType === "json-array" || dataType === "json-object") {
103
+ return JSON.parse(rawData);
104
+ } else {
105
+ return rawData;
106
+ }
107
+ }
108
+
109
+ // src/errors.ts
110
+ var FrameworkError = class extends Error {
111
+ constructor(message) {
112
+ super(message);
113
+ this.name = "FrameworkError";
114
+ }
115
+ };
116
+ var ParamError = class extends FrameworkError {
117
+ constructor(message) {
118
+ super(message);
119
+ this.name = "ParamError";
120
+ }
121
+ };
122
+
123
+ // src/filestore/synopsis-functions.ts
124
+ function defaultFileSynopsisFunction(fileEntry, data) {
125
+ if (!Array.isArray(data) || data.length === 0) {
126
+ return { ...fileEntry };
127
+ }
128
+ const timestamps = [];
129
+ const statusCounts = {};
130
+ for (const item of data) {
131
+ let ts = null;
132
+ let status = null;
133
+ for (const [key, value] of Object.entries(item)) {
134
+ const k = key.toLowerCase();
135
+ if (k === "modificationtimestamp") {
136
+ ts = new Date(value).getTime();
137
+ }
138
+ if (k === "standardstatus") {
139
+ status = value;
140
+ }
141
+ }
142
+ if (ts && !isNaN(ts)) {
143
+ timestamps.push(ts);
144
+ }
145
+ if (status !== null && status !== void 0) {
146
+ statusCounts[status] = (statusCounts[status] || 0) + 1;
147
+ }
148
+ }
149
+ const result = { ...fileEntry };
150
+ if (timestamps.length) {
151
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
152
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
153
+ }
154
+ if (Object.keys(statusCounts).length) {
155
+ result.StandardStatuses = statusCounts;
156
+ }
157
+ return result;
158
+ }
159
+ function defaultVersionSynopsisFunction(metadata) {
160
+ if (!metadata?.files || !Array.isArray(metadata.files)) {
161
+ return metadata;
162
+ }
163
+ const timestamps = [];
164
+ const statusCounts = {};
165
+ for (const file of metadata.files) {
166
+ if (file.minModificationTimestamp) {
167
+ const minTs = new Date(file.minModificationTimestamp).getTime();
168
+ if (!isNaN(minTs)) timestamps.push(minTs);
169
+ }
170
+ if (file.maxModificationTimestamp) {
171
+ const maxTs = new Date(file.maxModificationTimestamp).getTime();
172
+ if (!isNaN(maxTs)) timestamps.push(maxTs);
173
+ }
174
+ if (file.StandardStatuses && typeof file.StandardStatuses === "object") {
175
+ for (const [status, count] of Object.entries(file.StandardStatuses)) {
176
+ statusCounts[status] = (statusCounts[status] || 0) + count;
177
+ }
178
+ }
179
+ }
180
+ const result = { ...metadata };
181
+ if (timestamps.length) {
182
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
183
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
184
+ }
185
+ if (Object.keys(statusCounts).length > 0) {
186
+ result.StandardStatuses = statusCounts;
187
+ }
188
+ return result;
189
+ }
190
+
191
+ // src/filestore/index.ts
192
+ var FileDatabaseError = class extends Error {
193
+ constructor(message) {
194
+ super(message);
195
+ this.name = "FileDatabaseError";
196
+ }
197
+ };
198
+ var FileDatabase = class {
199
+ basePath;
200
+ namespace;
201
+ tableName = null;
202
+ maxVersions;
203
+ pageSize;
204
+ useMetadata;
205
+ freeSpaceThreshold;
206
+ logger;
207
+ // Current operation state
208
+ currentVersion = null;
209
+ currentVersionFolder = null;
210
+ currentFileNumber = 0;
211
+ currentRecord = 0;
212
+ hasReadFirstPage = false;
213
+ lastFileData = null;
214
+ metadata;
215
+ // Synopsis calculation functions
216
+ fileSynopsisFunction = null;
217
+ versionSynopsisFunction = null;
218
+ constructor(config) {
219
+ if (!config.basePath) {
220
+ throw new ParamError("[FileDatabase] basePath is required");
221
+ }
222
+ this.basePath = config.basePath;
223
+ this.namespace = config.namespace || "default";
224
+ this.tableName = config.tableName || null;
225
+ this.maxVersions = config.maxVersions || 5;
226
+ this.pageSize = config.pageSize || 5e3;
227
+ this.useMetadata = config.useMetadata !== false;
228
+ this.freeSpaceThreshold = config.freeSpaceThreshold || 100 * 1024 * 1024;
229
+ this.logger = config.logger || console;
230
+ this.metadata = this.getDefaultMetadata();
231
+ }
232
+ /**
233
+ * Get default metadata structure
234
+ */
235
+ getDefaultMetadata() {
236
+ return {
237
+ version: this.currentVersion || null,
238
+ files: [],
239
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
240
+ modifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
241
+ totalRecords: 0,
242
+ synopsis: null,
243
+ dataType: null
244
+ };
245
+ }
246
+ /**
247
+ * Get the destination path (basePath/namespace/tableName)
248
+ */
249
+ getDestinationPath() {
250
+ const errors = ["basePath", "namespace", "tableName"].filter((prop) => !this[prop]).map((prop) => `${prop} is not set`);
251
+ if (errors.length) {
252
+ throw new FileDatabaseError(`[FileDatabase] ${errors.join("; ")}`);
253
+ }
254
+ return path3.resolve(this.basePath, this.namespace, this.tableName);
255
+ }
256
+ /**
257
+ * Set current version and version folder
258
+ */
259
+ async setCurrentVersion(version) {
260
+ this.currentVersion = version;
261
+ this.currentVersionFolder = await ensurePath(this.getDestinationPath(), version);
262
+ }
263
+ /**
264
+ * Create a new version folder with comprehensive timestamp logic
265
+ */
266
+ async makeNewVersion() {
267
+ const existingVersions = await this.getVersions();
268
+ let versionName;
269
+ if (existingVersions.length > 0) {
270
+ const maxTimestamp = existingVersions.reduce((max, version) => {
271
+ const versionDate = new Date(version.replace("Z", ""));
272
+ const maxDate2 = new Date(max.replace("Z", ""));
273
+ return versionDate > maxDate2 ? version : max;
274
+ });
275
+ const maxDate = new Date(maxTimestamp.replace("Z", ""));
276
+ const nextDate = new Date(maxDate.getTime() + 1e3);
277
+ versionName = nextDate.toISOString().split(".")[0] + "Z";
278
+ } else {
279
+ const now = /* @__PURE__ */ new Date();
280
+ versionName = now.toISOString().split(".")[0] + "Z";
281
+ }
282
+ await this.setCurrentVersion(versionName);
283
+ this.currentFileNumber = 0;
284
+ const versions = await this.getVersions();
285
+ while (versions.length > this.maxVersions) {
286
+ const versionToDelete = path3.resolve(this.getDestinationPath(), versions.shift());
287
+ this.logger.debug?.(`[FileDatabase] Deleting old version: ${versionToDelete}`);
288
+ await fs3.promises.rm(versionToDelete, { recursive: true, force: true });
289
+ }
290
+ return versionName;
291
+ }
292
+ /**
293
+ * Get list of all versions (sorted chronologically)
294
+ */
295
+ async getVersions() {
296
+ const destPath = this.getDestinationPath();
297
+ try {
298
+ await ensurePath(destPath);
299
+ const items = await fs3.promises.readdir(destPath);
300
+ const versions = items.filter((item) => {
301
+ const itemPath = path3.join(destPath, item);
302
+ const stat = fs3.statSync(itemPath);
303
+ return stat.isDirectory() && isTimestampFolder(item);
304
+ });
305
+ return versions.sort();
306
+ } catch (error) {
307
+ return [];
308
+ }
309
+ }
310
+ /**
311
+ * Load metadata from JSON file
312
+ */
313
+ async loadMetadataJson(version) {
314
+ const metadataFile = path3.join(this.getDestinationPath(), version, "metadata.json");
315
+ if (fs3.existsSync(metadataFile)) {
316
+ try {
317
+ const rawData = await fs3.promises.readFile(metadataFile, "utf8");
318
+ return JSON.parse(rawData);
319
+ } catch (e) {
320
+ throw new FileDatabaseError(`Failed to read metadata for version "${version}": ${e.message}`);
321
+ }
322
+ }
323
+ return null;
324
+ }
325
+ /**
326
+ * Build metadata by scanning files in a version folder (backward compatibility)
327
+ * Reads all files to get accurate counts - used when synopsis calculation is needed
328
+ */
329
+ async figureMetadataFromVersionFiles(version) {
330
+ const versionPath = path3.join(this.getDestinationPath(), version);
331
+ if (!fs3.existsSync(versionPath)) {
332
+ return this.getDefaultMetadata();
333
+ }
334
+ const files = (await fs3.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
335
+ const metadata = this.getDefaultMetadata();
336
+ metadata.version = version;
337
+ metadata.files = [];
338
+ let totalRecords = 0;
339
+ let detectedDataType = null;
340
+ for (let i = 0; i < files.length; i++) {
341
+ const fileName = files[i];
342
+ const filePath = path3.join(versionPath, fileName);
343
+ try {
344
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
345
+ const extension = path3.extname(fileName).toLowerCase();
346
+ let dataType = "text";
347
+ if (extension === ".json") {
348
+ dataType = "json-array";
349
+ } else if (extension === ".xml") {
350
+ dataType = "xml";
351
+ }
352
+ const fileData = deserializeData(rawData, dataType);
353
+ const recordsCount = Array.isArray(fileData) ? fileData.length : 1;
354
+ if (detectedDataType === null) {
355
+ detectedDataType = detectDataType(fileData);
356
+ }
357
+ const fileInfo = {
358
+ number: i + 1,
359
+ recordsCount,
360
+ fileName
361
+ };
362
+ metadata.files.push(fileInfo);
363
+ totalRecords += recordsCount;
364
+ } catch (error) {
365
+ this.logger.error?.(`[FileDatabase] Failed to read file ${fileName}: ${error.message}`);
366
+ }
367
+ }
368
+ metadata.totalRecords = totalRecords;
369
+ metadata.dataType = detectedDataType;
370
+ return metadata;
371
+ }
372
+ /**
373
+ * Build metadata optimized - only reads first and last files
374
+ * Assumes all middle files have the same record count as the first file
375
+ * Much faster for large datasets with many files
376
+ */
377
+ async buildMetadataOptimized(version) {
378
+ const versionPath = path3.join(this.getDestinationPath(), version);
379
+ if (!fs3.existsSync(versionPath)) {
380
+ return this.getDefaultMetadata();
381
+ }
382
+ const files = (await fs3.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
383
+ if (files.length === 0) {
384
+ return this.getDefaultMetadata();
385
+ }
386
+ const metadata = this.getDefaultMetadata();
387
+ metadata.version = version;
388
+ metadata.files = files.map((fileName, index) => ({
389
+ number: index + 1,
390
+ recordsCount: 0,
391
+ fileName
392
+ }));
393
+ const firstFile = metadata.files[0];
394
+ const firstFilePath = path3.join(versionPath, firstFile.fileName);
395
+ const firstFileRaw = await fs3.promises.readFile(firstFilePath, "utf8");
396
+ let firstFileData;
397
+ try {
398
+ firstFileData = JSON.parse(firstFileRaw);
399
+ } catch (e) {
400
+ firstFileData = firstFileRaw;
401
+ }
402
+ metadata.dataType = detectDataType(firstFileData);
403
+ if (metadata.dataType === "json-array") {
404
+ const firstFileCount = Array.isArray(firstFileData) ? firstFileData.length : 1;
405
+ firstFile.recordsCount = firstFileCount;
406
+ for (let i = 1; i < metadata.files.length - 1; i++) {
407
+ metadata.files[i].recordsCount = firstFileCount;
408
+ }
409
+ if (files.length > 1) {
410
+ const lastFile = metadata.files[metadata.files.length - 1];
411
+ const lastFilePath = path3.join(versionPath, lastFile.fileName);
412
+ const lastFileRaw = await fs3.promises.readFile(lastFilePath, "utf8");
413
+ const lastFileData = deserializeData(lastFileRaw, metadata.dataType);
414
+ lastFile.recordsCount = Array.isArray(lastFileData) ? lastFileData.length : 1;
415
+ }
416
+ metadata.totalRecords = metadata.files.reduce((sum, file) => sum + file.recordsCount, 0);
417
+ } else {
418
+ metadata.files.forEach((file) => {
419
+ file.recordsCount = 1;
420
+ });
421
+ metadata.totalRecords = files.length;
422
+ }
423
+ return metadata;
424
+ }
425
+ /**
426
+ * Figure out metadata - tries JSON first, then builds from files
427
+ * Uses optimized building when no synopsis calculation is needed
428
+ */
429
+ async figureMetadata(version, useOptimized = true) {
430
+ if (this.useMetadata) {
431
+ const metadata = await this.loadMetadataJson(version);
432
+ if (metadata) {
433
+ return metadata;
434
+ }
435
+ }
436
+ if (useOptimized && !this.fileSynopsisFunction && !this.versionSynopsisFunction) {
437
+ return await this.buildMetadataOptimized(version);
438
+ }
439
+ return await this.figureMetadataFromVersionFiles(version);
440
+ }
441
+ /**
442
+ * Load version metadata (main entry point for loading)
443
+ */
444
+ async loadVersionMetadata(version) {
445
+ const metadata = await this.figureMetadata(version);
446
+ this.metadata = metadata;
447
+ return metadata;
448
+ }
449
+ /**
450
+ * Save version metadata to file
451
+ */
452
+ async saveVersionMetadata(metadata) {
453
+ if (!this.useMetadata || !this.currentVersion) {
454
+ return;
455
+ }
456
+ const metadataToSave = metadata || this.metadata;
457
+ const metadataFile = path3.join(this.getDestinationPath(), this.currentVersion, "metadata.json");
458
+ await fs3.promises.writeFile(metadataFile, JSON.stringify(metadataToSave, null, 4), "utf8");
459
+ }
460
+ /**
461
+ * Create a new file entry in metadata
462
+ */
463
+ makeNewFile() {
464
+ this.currentFileNumber = (this.currentFileNumber || 0) + 1;
465
+ const dataType = this.metadata.dataType || "json-array";
466
+ const fileEntry = {
467
+ number: this.currentFileNumber,
468
+ recordsCount: 0,
469
+ fileName: `${this.currentFileNumber.toString().padStart(6, "0")}.${getFileExtension(dataType)}`
470
+ };
471
+ this.metadata.files.push(fileEntry);
472
+ this.lastFileData = null;
473
+ this.logger.debug?.(`[FileDatabase] Created new file: ${fileEntry.fileName}, fileNumber: ${this.currentFileNumber}`);
474
+ }
475
+ /**
476
+ * Figure out what data to write and which file to use (for pagination)
477
+ */
478
+ figureOutDataAndFileToWrite(data) {
479
+ let dataToWrite;
480
+ let dataLeftOver;
481
+ const lastFile = this.metadata.files[this.metadata.files.length - 1];
482
+ const lastFileRecordsCount = lastFile.recordsCount;
483
+ if (Array.isArray(data)) {
484
+ if (lastFileRecordsCount < this.pageSize) {
485
+ dataToWrite = [...this.lastFileData || [], ...data.slice(0, this.pageSize - lastFileRecordsCount)];
486
+ dataLeftOver = data.slice(this.pageSize - lastFileRecordsCount);
487
+ } else {
488
+ this.makeNewFile();
489
+ dataToWrite = data.slice(0, this.pageSize);
490
+ dataLeftOver = data.slice(this.pageSize);
491
+ }
492
+ this.lastFileData = dataToWrite;
493
+ } else {
494
+ dataToWrite = data;
495
+ dataLeftOver = null;
496
+ }
497
+ const fileName = this.metadata.files[this.metadata.files.length - 1].fileName;
498
+ this.logger.debug?.(
499
+ `[FileDatabase] figureOutDataAndFileToWrite: filename=${fileName}, dataToWrite.length=${Array.isArray(dataToWrite) ? dataToWrite.length : "N/A"}, lastFileRecordsCount=${lastFileRecordsCount}`
500
+ );
501
+ return { dataToWrite, dataLeftOver, fileName };
502
+ }
503
+ /**
504
+ * Calculate file-level synopsis if function is set
505
+ */
506
+ calculateFileSynopsis(data, fileIndex = this.metadata.files.length - 1) {
507
+ if (!this.fileSynopsisFunction) {
508
+ return;
509
+ }
510
+ const fileInfo = this.metadata.files[fileIndex];
511
+ const enhancedFileInfo = this.fileSynopsisFunction(fileInfo, data);
512
+ this.metadata.files[fileIndex] = enhancedFileInfo;
513
+ }
514
+ /**
515
+ * Calculate version-level synopsis if function is set
516
+ */
517
+ calculateVersionSynopsis() {
518
+ if (!this.versionSynopsisFunction) {
519
+ return;
520
+ }
521
+ const enhancedMetadata = this.versionSynopsisFunction(this.metadata);
522
+ this.metadata = enhancedMetadata;
523
+ }
524
+ /**
525
+ * Update metadata after writing data
526
+ */
527
+ updateMetadata(dataToWrite, fileName) {
528
+ let currentFile;
529
+ if (fileName) {
530
+ const foundFile = this.metadata.files.find((file) => file.fileName === fileName);
531
+ if (!foundFile) {
532
+ this.logger.warn?.(`[FileDatabase] File ${fileName} not found in metadata, using last file`);
533
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
534
+ } else {
535
+ currentFile = foundFile;
536
+ }
537
+ } else {
538
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
539
+ }
540
+ const recordsCount = Array.isArray(dataToWrite) ? dataToWrite.length : 1;
541
+ currentFile.recordsCount = recordsCount;
542
+ const fileIndex = this.metadata.files.indexOf(currentFile);
543
+ if (fileIndex !== -1) {
544
+ this.calculateFileSynopsis(dataToWrite, fileIndex);
545
+ }
546
+ this.metadata.version = this.currentVersion;
547
+ this.metadata.modifiedAt = (/* @__PURE__ */ new Date()).toISOString();
548
+ this.metadata.dataType = detectDataType(dataToWrite);
549
+ this.metadata.totalRecords = this.metadata.files.reduce((sum, file) => sum + (file.recordsCount || 0), 0);
550
+ this.logger.debug?.(
551
+ `[FileDatabase] Updated metadata for file ${currentFile.fileName}: recordsCount=${recordsCount}, totalRecords=${this.metadata.totalRecords}`
552
+ );
553
+ }
554
+ /**
555
+ * Safe write with disk space check
556
+ */
557
+ async safeWrite(filePath, data) {
558
+ const serializedData = serializeData(data);
559
+ const dir = path3.dirname(filePath);
560
+ const requiredBytes = Buffer.byteLength(serializedData, "utf8");
561
+ const freeBytes = getFreeDiskSpace(dir);
562
+ if (freeBytes !== null) {
563
+ if (freeBytes < requiredBytes) {
564
+ throw new FileDatabaseError(
565
+ `Not enough disk space. Required: ${bytesToHumanReadable(requiredBytes)}, Free: ${bytesToHumanReadable(freeBytes)}`
566
+ );
567
+ }
568
+ if (freeBytes < this.freeSpaceThreshold) {
569
+ this.logger.warn?.(`Low disk space warning: only ${bytesToHumanReadable(freeBytes)} left`);
570
+ }
571
+ }
572
+ try {
573
+ await fs3.promises.writeFile(filePath, serializedData, "utf8");
574
+ this.logger.debug?.(`[FileDatabase] Wrote ${bytesToHumanReadable(requiredBytes)} to ${filePath}`);
575
+ } catch (error) {
576
+ throw new FileDatabaseError(`Failed to write file ${filePath}: ${error.message}`);
577
+ }
578
+ }
579
+ /**
580
+ * Prepare the instance for read or write operations
581
+ * This discovers state and sets up internal members based on mode and current data
582
+ */
583
+ async prepare({ write, read, version }) {
584
+ if (write) {
585
+ if (this.currentVersion === null) {
586
+ await this.makeNewVersion();
587
+ this.metadata = this.getDefaultMetadata();
588
+ this.metadata.version = this.currentVersion;
589
+ this.makeNewFile();
590
+ } else {
591
+ if (!this.metadata.files.length) {
592
+ this.metadata = await this.figureMetadata(this.currentVersion);
593
+ }
594
+ }
595
+ } else if (read) {
596
+ const versions = await this.getVersions();
597
+ if (versions.length === 0) {
598
+ throw new FileDatabaseError("[FileDatabase] No versions found, cannot read");
599
+ }
600
+ if (version) {
601
+ if (!versions.includes(version)) {
602
+ throw new FileDatabaseError(`[FileDatabase] Version "${version}" not found`);
603
+ }
604
+ await this.setCurrentVersion(version);
605
+ } else {
606
+ await this.setCurrentVersion(versions[versions.length - 1]);
607
+ }
608
+ if (!this.metadata.files.length) {
609
+ this.metadata = await this.figureMetadata(this.currentVersion);
610
+ }
611
+ }
612
+ }
613
+ /**
614
+ * Write data to the file database
615
+ */
616
+ async write(data, options = {}) {
617
+ await this.prepare({ write: true });
618
+ if (options.forceNewVersion) {
619
+ await this.makeNewVersion();
620
+ this.metadata = this.getDefaultMetadata();
621
+ this.metadata.version = this.currentVersion;
622
+ this.makeNewFile();
623
+ }
624
+ let { dataToWrite, dataLeftOver, fileName } = this.figureOutDataAndFileToWrite(data);
625
+ await this.safeWrite(path3.join(this.currentVersionFolder, fileName), dataToWrite);
626
+ this.updateMetadata(dataToWrite, fileName);
627
+ while (dataLeftOver && dataLeftOver.length > 0) {
628
+ const writeContext = this.figureOutDataAndFileToWrite(dataLeftOver);
629
+ await this.safeWrite(path3.join(this.currentVersionFolder, writeContext.fileName), writeContext.dataToWrite);
630
+ this.updateMetadata(writeContext.dataToWrite, writeContext.fileName);
631
+ dataLeftOver = writeContext.dataLeftOver;
632
+ }
633
+ this.calculateVersionSynopsis();
634
+ if (this.useMetadata) {
635
+ await this.saveVersionMetadata(this.metadata);
636
+ }
637
+ }
638
+ /**
639
+ * Read data from the file database
640
+ */
641
+ async read(options = {}) {
642
+ const { version, nextPage = false, pageSize } = options;
643
+ await this.prepare({ read: true, version });
644
+ const isNonPaginatedData = this.metadata.dataType === "text" || this.metadata.dataType === "xml" || this.metadata.dataType === "json-object";
645
+ if (isNonPaginatedData) {
646
+ const file = this.metadata.files[0];
647
+ const filePath = path3.join(this.getDestinationPath(), this.currentVersion, file.fileName);
648
+ try {
649
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
650
+ return deserializeData(rawData, this.metadata.dataType);
651
+ } catch (error) {
652
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
653
+ }
654
+ }
655
+ let effectivePageSize;
656
+ if (nextPage && this.hasReadFirstPage) {
657
+ effectivePageSize = pageSize || this.pageSize;
658
+ this.currentRecord += effectivePageSize;
659
+ } else if (!nextPage) {
660
+ effectivePageSize = pageSize !== void 0 ? pageSize : this.metadata.totalRecords;
661
+ this.currentRecord = 0;
662
+ } else {
663
+ effectivePageSize = pageSize || this.pageSize;
664
+ }
665
+ if (this.currentRecord >= this.metadata.totalRecords) {
666
+ return [];
667
+ }
668
+ const result = [];
669
+ let recordsRead = 0;
670
+ let currentFileIndex = 0;
671
+ let currentFileOffset = 0;
672
+ let totalRecords = 0;
673
+ for (let i = 0; i < this.metadata.files.length; i++) {
674
+ const file = this.metadata.files[i];
675
+ if (this.currentRecord < totalRecords + file.recordsCount) {
676
+ currentFileIndex = i;
677
+ currentFileOffset = totalRecords;
678
+ break;
679
+ }
680
+ totalRecords += file.recordsCount;
681
+ }
682
+ let cumulativeRecords = currentFileOffset;
683
+ for (let i = currentFileIndex; i < this.metadata.files.length && recordsRead < effectivePageSize; i++) {
684
+ const file = this.metadata.files[i];
685
+ const filePath = path3.join(this.getDestinationPath(), this.currentVersion, file.fileName);
686
+ try {
687
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
688
+ const fileData = deserializeData(rawData, this.metadata.dataType);
689
+ let startIndex = 0;
690
+ if (i === currentFileIndex) {
691
+ startIndex = this.currentRecord - cumulativeRecords;
692
+ }
693
+ const endIndex = Math.min(startIndex + (effectivePageSize - recordsRead), fileData.length);
694
+ const recordsFromThisFile = fileData.slice(startIndex, endIndex);
695
+ result.push(...recordsFromThisFile);
696
+ recordsRead += recordsFromThisFile.length;
697
+ cumulativeRecords += file.recordsCount;
698
+ } catch (error) {
699
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
700
+ }
701
+ }
702
+ if (result.length > 0) {
703
+ if (nextPage || pageSize !== void 0 && pageSize < this.metadata.totalRecords) {
704
+ this.hasReadFirstPage = true;
705
+ }
706
+ }
707
+ return result;
708
+ }
709
+ /**
710
+ * Set the starting record for pagination (1-based index)
711
+ */
712
+ setStartRecord(startRecord) {
713
+ this.currentRecord = startRecord - 1;
714
+ this.hasReadFirstPage = false;
715
+ }
716
+ /**
717
+ * Reset read pagination state
718
+ */
719
+ resetPagination() {
720
+ this.currentRecord = 0;
721
+ this.hasReadFirstPage = false;
722
+ }
723
+ /**
724
+ * Set file-level synopsis calculation function
725
+ */
726
+ setFileSynopsisFunction(fn) {
727
+ this.fileSynopsisFunction = fn;
728
+ }
729
+ /**
730
+ * Set version-level synopsis calculation function
731
+ */
732
+ setVersionSynopsisFunction(fn) {
733
+ this.versionSynopsisFunction = fn;
734
+ }
735
+ /**
736
+ * Get current version name
737
+ */
738
+ getCurrentVersion() {
739
+ return this.currentVersion;
740
+ }
741
+ /**
742
+ * Get current metadata
743
+ */
744
+ getMetadata() {
745
+ return { ...this.metadata };
746
+ }
747
+ };
748
+ export {
749
+ FileDatabase,
750
+ FileDatabaseError,
751
+ defaultFileSynopsisFunction,
752
+ defaultVersionSynopsisFunction
753
+ };
754
+ //# sourceMappingURL=filestore.js.map