@nmakarov/cli-toolkit 0.1.4 → 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.
package/dist/index.js CHANGED
@@ -390,7 +390,7 @@ var Args = class {
390
390
  command: this.commands[0] || "",
391
391
  flags: { ...this.flags },
392
392
  options: { ...this.options },
393
- usedKeys: new Set(this.usedKeys)
393
+ usedKeys: Array.from(this.usedKeys)
394
394
  };
395
395
  }
396
396
  /**
@@ -606,8 +606,6 @@ var Params = class {
606
606
  } else if (str.match(/^boolean|^bool/i)) {
607
607
  type = Joi.boolean();
608
608
  } else if (str.match(/^date/i)) {
609
- type = Joi.date();
610
- } else if (str.match(/^edate/i)) {
611
609
  type = Joi.custom(joiEdateType);
612
610
  } else if (str.match(/^duration/i)) {
613
611
  type = Joi.string().isoDuration();
@@ -1603,11 +1601,11 @@ function buildBreadcrumb(parts) {
1603
1601
  if (parts.length === 1) return parts[0];
1604
1602
  return parts.slice(1).map((part) => `\u2190 ${part}`).join(" ");
1605
1603
  }
1606
- function buildDetailBreadcrumb(path, suffix = "") {
1607
- if (path.length <= 1) {
1608
- return suffix ? `\u2190 ${suffix}` : path[0] || "";
1604
+ function buildDetailBreadcrumb(path4, suffix = "") {
1605
+ if (path4.length <= 1) {
1606
+ return suffix ? `\u2190 ${suffix}` : path4[0] || "";
1609
1607
  }
1610
- const breadcrumb = buildBreadcrumb(path);
1608
+ const breadcrumb = buildBreadcrumb(path4);
1611
1609
  return suffix ? `${breadcrumb} ${suffix}` : breadcrumb;
1612
1610
  }
1613
1611
 
@@ -1715,9 +1713,745 @@ function organizeFooterMessages(messages) {
1715
1713
  lines.push(...others);
1716
1714
  return lines;
1717
1715
  }
1716
+
1717
+ // src/filestore/index.ts
1718
+ import fs3 from "fs";
1719
+ import path3 from "path";
1720
+
1721
+ // src/utils/os-utils.ts
1722
+ import fs from "fs";
1723
+ import path from "path";
1724
+ import { execSync } from "child_process";
1725
+ function getFreeDiskSpace(targetPath) {
1726
+ try {
1727
+ let pathToCheck = targetPath;
1728
+ if (!fs.existsSync(targetPath)) {
1729
+ const parentDir = path.dirname(targetPath);
1730
+ if (fs.existsSync(parentDir)) {
1731
+ pathToCheck = parentDir;
1732
+ } else {
1733
+ pathToCheck = process.platform === "win32" ? "C:\\" : "/";
1734
+ }
1735
+ }
1736
+ if (process.platform === "win32") {
1737
+ return null;
1738
+ } else {
1739
+ const stdout = execSync(`df -k "${pathToCheck}"`, { encoding: "utf8" });
1740
+ const lines = stdout.trim().split("\n");
1741
+ const parts = lines[1].split(/\s+/);
1742
+ const freeKb = parseInt(parts[3], 10);
1743
+ return freeKb * 1024;
1744
+ }
1745
+ } catch (error) {
1746
+ return null;
1747
+ }
1748
+ }
1749
+
1750
+ // src/utils/fs-utils.ts
1751
+ import fs2 from "fs";
1752
+ import path2 from "path";
1753
+ async function ensurePath(...pathParts) {
1754
+ const fullPath = path2.resolve(...pathParts);
1755
+ if (!fs2.existsSync(fullPath)) {
1756
+ await fs2.promises.mkdir(fullPath, { recursive: true });
1757
+ }
1758
+ return fullPath;
1759
+ }
1760
+ function getFileExtension(dataType) {
1761
+ switch (dataType) {
1762
+ case "json-array":
1763
+ case "json-object":
1764
+ return "json";
1765
+ case "text":
1766
+ return "txt";
1767
+ case "xml":
1768
+ return "xml";
1769
+ default:
1770
+ return "json";
1771
+ }
1772
+ }
1773
+
1774
+ // src/utils/format-utils.ts
1775
+ function bytesToHumanReadable(bytes) {
1776
+ if (bytes === 0) return "0 B";
1777
+ const k = 1024;
1778
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
1779
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1780
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
1781
+ }
1782
+
1783
+ // src/utils/date-utils.ts
1784
+ function isTimestampFolder(folderName) {
1785
+ const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|\.\d{3}Z)$/;
1786
+ if (!isoRegex.test(folderName)) {
1787
+ return false;
1788
+ }
1789
+ const date = new Date(folderName);
1790
+ return !isNaN(date.getTime()) && date.getTime() > 0;
1791
+ }
1792
+
1793
+ // src/filestore/serializers.ts
1794
+ function detectDataType(data) {
1795
+ if (Array.isArray(data)) {
1796
+ return "json-array";
1797
+ } else if (typeof data === "object" && data !== null) {
1798
+ return "json-object";
1799
+ } else if (typeof data === "string") {
1800
+ const trimmed = data.trim();
1801
+ if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
1802
+ return "xml";
1803
+ }
1804
+ return "text";
1805
+ } else {
1806
+ return "text";
1807
+ }
1808
+ }
1809
+ function serializeData(data) {
1810
+ const dataType = detectDataType(data);
1811
+ if (dataType === "json-array" || dataType === "json-object") {
1812
+ return JSON.stringify(data, null, 4);
1813
+ } else {
1814
+ return String(data);
1815
+ }
1816
+ }
1817
+ function deserializeData(rawData, dataType) {
1818
+ if (dataType === "json-array" || dataType === "json-object") {
1819
+ return JSON.parse(rawData);
1820
+ } else {
1821
+ return rawData;
1822
+ }
1823
+ }
1824
+
1825
+ // src/filestore/synopsis-functions.ts
1826
+ function defaultFileSynopsisFunction(fileEntry, data) {
1827
+ if (!Array.isArray(data) || data.length === 0) {
1828
+ return { ...fileEntry };
1829
+ }
1830
+ const timestamps = [];
1831
+ const statusCounts = {};
1832
+ for (const item of data) {
1833
+ let ts = null;
1834
+ let status = null;
1835
+ for (const [key, value] of Object.entries(item)) {
1836
+ const k = key.toLowerCase();
1837
+ if (k === "modificationtimestamp") {
1838
+ ts = new Date(value).getTime();
1839
+ }
1840
+ if (k === "standardstatus") {
1841
+ status = value;
1842
+ }
1843
+ }
1844
+ if (ts && !isNaN(ts)) {
1845
+ timestamps.push(ts);
1846
+ }
1847
+ if (status !== null && status !== void 0) {
1848
+ statusCounts[status] = (statusCounts[status] || 0) + 1;
1849
+ }
1850
+ }
1851
+ const result = { ...fileEntry };
1852
+ if (timestamps.length) {
1853
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
1854
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
1855
+ }
1856
+ if (Object.keys(statusCounts).length) {
1857
+ result.StandardStatuses = statusCounts;
1858
+ }
1859
+ return result;
1860
+ }
1861
+ function defaultVersionSynopsisFunction(metadata) {
1862
+ if (!metadata?.files || !Array.isArray(metadata.files)) {
1863
+ return metadata;
1864
+ }
1865
+ const timestamps = [];
1866
+ const statusCounts = {};
1867
+ for (const file of metadata.files) {
1868
+ if (file.minModificationTimestamp) {
1869
+ const minTs = new Date(file.minModificationTimestamp).getTime();
1870
+ if (!isNaN(minTs)) timestamps.push(minTs);
1871
+ }
1872
+ if (file.maxModificationTimestamp) {
1873
+ const maxTs = new Date(file.maxModificationTimestamp).getTime();
1874
+ if (!isNaN(maxTs)) timestamps.push(maxTs);
1875
+ }
1876
+ if (file.StandardStatuses && typeof file.StandardStatuses === "object") {
1877
+ for (const [status, count] of Object.entries(file.StandardStatuses)) {
1878
+ statusCounts[status] = (statusCounts[status] || 0) + count;
1879
+ }
1880
+ }
1881
+ }
1882
+ const result = { ...metadata };
1883
+ if (timestamps.length) {
1884
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
1885
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
1886
+ }
1887
+ if (Object.keys(statusCounts).length > 0) {
1888
+ result.StandardStatuses = statusCounts;
1889
+ }
1890
+ return result;
1891
+ }
1892
+
1893
+ // src/filestore/index.ts
1894
+ var FileDatabaseError = class extends Error {
1895
+ constructor(message) {
1896
+ super(message);
1897
+ this.name = "FileDatabaseError";
1898
+ }
1899
+ };
1900
+ var FileDatabase = class {
1901
+ basePath;
1902
+ namespace;
1903
+ tableName = null;
1904
+ maxVersions;
1905
+ pageSize;
1906
+ useMetadata;
1907
+ freeSpaceThreshold;
1908
+ logger;
1909
+ // Current operation state
1910
+ currentVersion = null;
1911
+ currentVersionFolder = null;
1912
+ currentFileNumber = 0;
1913
+ currentRecord = 0;
1914
+ hasReadFirstPage = false;
1915
+ lastFileData = null;
1916
+ metadata;
1917
+ // Synopsis calculation functions
1918
+ fileSynopsisFunction = null;
1919
+ versionSynopsisFunction = null;
1920
+ constructor(config2) {
1921
+ if (!config2.basePath) {
1922
+ throw new ParamError("[FileDatabase] basePath is required");
1923
+ }
1924
+ this.basePath = config2.basePath;
1925
+ this.namespace = config2.namespace || "default";
1926
+ this.tableName = config2.tableName || null;
1927
+ this.maxVersions = config2.maxVersions || 5;
1928
+ this.pageSize = config2.pageSize || 5e3;
1929
+ this.useMetadata = config2.useMetadata !== false;
1930
+ this.freeSpaceThreshold = config2.freeSpaceThreshold || 100 * 1024 * 1024;
1931
+ this.logger = config2.logger || console;
1932
+ this.metadata = this.getDefaultMetadata();
1933
+ }
1934
+ /**
1935
+ * Get default metadata structure
1936
+ */
1937
+ getDefaultMetadata() {
1938
+ return {
1939
+ version: this.currentVersion || null,
1940
+ files: [],
1941
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1942
+ modifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
1943
+ totalRecords: 0,
1944
+ synopsis: null,
1945
+ dataType: null
1946
+ };
1947
+ }
1948
+ /**
1949
+ * Get the destination path (basePath/namespace/tableName)
1950
+ */
1951
+ getDestinationPath() {
1952
+ const errors = ["basePath", "namespace", "tableName"].filter((prop) => !this[prop]).map((prop) => `${prop} is not set`);
1953
+ if (errors.length) {
1954
+ throw new FileDatabaseError(`[FileDatabase] ${errors.join("; ")}`);
1955
+ }
1956
+ return path3.resolve(this.basePath, this.namespace, this.tableName);
1957
+ }
1958
+ /**
1959
+ * Set current version and version folder
1960
+ */
1961
+ async setCurrentVersion(version) {
1962
+ this.currentVersion = version;
1963
+ this.currentVersionFolder = await ensurePath(this.getDestinationPath(), version);
1964
+ }
1965
+ /**
1966
+ * Create a new version folder with comprehensive timestamp logic
1967
+ */
1968
+ async makeNewVersion() {
1969
+ const existingVersions = await this.getVersions();
1970
+ let versionName;
1971
+ if (existingVersions.length > 0) {
1972
+ const maxTimestamp = existingVersions.reduce((max, version) => {
1973
+ const versionDate = new Date(version.replace("Z", ""));
1974
+ const maxDate2 = new Date(max.replace("Z", ""));
1975
+ return versionDate > maxDate2 ? version : max;
1976
+ });
1977
+ const maxDate = new Date(maxTimestamp.replace("Z", ""));
1978
+ const nextDate = new Date(maxDate.getTime() + 1e3);
1979
+ versionName = nextDate.toISOString().split(".")[0] + "Z";
1980
+ } else {
1981
+ const now = /* @__PURE__ */ new Date();
1982
+ versionName = now.toISOString().split(".")[0] + "Z";
1983
+ }
1984
+ await this.setCurrentVersion(versionName);
1985
+ this.currentFileNumber = 0;
1986
+ const versions = await this.getVersions();
1987
+ while (versions.length > this.maxVersions) {
1988
+ const versionToDelete = path3.resolve(this.getDestinationPath(), versions.shift());
1989
+ this.logger.debug?.(`[FileDatabase] Deleting old version: ${versionToDelete}`);
1990
+ await fs3.promises.rm(versionToDelete, { recursive: true, force: true });
1991
+ }
1992
+ return versionName;
1993
+ }
1994
+ /**
1995
+ * Get list of all versions (sorted chronologically)
1996
+ */
1997
+ async getVersions() {
1998
+ const destPath = this.getDestinationPath();
1999
+ try {
2000
+ await ensurePath(destPath);
2001
+ const items = await fs3.promises.readdir(destPath);
2002
+ const versions = items.filter((item) => {
2003
+ const itemPath = path3.join(destPath, item);
2004
+ const stat = fs3.statSync(itemPath);
2005
+ return stat.isDirectory() && isTimestampFolder(item);
2006
+ });
2007
+ return versions.sort();
2008
+ } catch (error) {
2009
+ return [];
2010
+ }
2011
+ }
2012
+ /**
2013
+ * Load metadata from JSON file
2014
+ */
2015
+ async loadMetadataJson(version) {
2016
+ const metadataFile = path3.join(this.getDestinationPath(), version, "metadata.json");
2017
+ if (fs3.existsSync(metadataFile)) {
2018
+ try {
2019
+ const rawData = await fs3.promises.readFile(metadataFile, "utf8");
2020
+ return JSON.parse(rawData);
2021
+ } catch (e) {
2022
+ throw new FileDatabaseError(`Failed to read metadata for version "${version}": ${e.message}`);
2023
+ }
2024
+ }
2025
+ return null;
2026
+ }
2027
+ /**
2028
+ * Build metadata by scanning files in a version folder (backward compatibility)
2029
+ * Reads all files to get accurate counts - used when synopsis calculation is needed
2030
+ */
2031
+ async figureMetadataFromVersionFiles(version) {
2032
+ const versionPath = path3.join(this.getDestinationPath(), version);
2033
+ if (!fs3.existsSync(versionPath)) {
2034
+ return this.getDefaultMetadata();
2035
+ }
2036
+ const files = (await fs3.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
2037
+ const metadata = this.getDefaultMetadata();
2038
+ metadata.version = version;
2039
+ metadata.files = [];
2040
+ let totalRecords = 0;
2041
+ let detectedDataType = null;
2042
+ for (let i = 0; i < files.length; i++) {
2043
+ const fileName = files[i];
2044
+ const filePath = path3.join(versionPath, fileName);
2045
+ try {
2046
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
2047
+ const extension = path3.extname(fileName).toLowerCase();
2048
+ let dataType = "text";
2049
+ if (extension === ".json") {
2050
+ dataType = "json-array";
2051
+ } else if (extension === ".xml") {
2052
+ dataType = "xml";
2053
+ }
2054
+ const fileData = deserializeData(rawData, dataType);
2055
+ const recordsCount = Array.isArray(fileData) ? fileData.length : 1;
2056
+ if (detectedDataType === null) {
2057
+ detectedDataType = detectDataType(fileData);
2058
+ }
2059
+ const fileInfo = {
2060
+ number: i + 1,
2061
+ recordsCount,
2062
+ fileName
2063
+ };
2064
+ metadata.files.push(fileInfo);
2065
+ totalRecords += recordsCount;
2066
+ } catch (error) {
2067
+ this.logger.error?.(`[FileDatabase] Failed to read file ${fileName}: ${error.message}`);
2068
+ }
2069
+ }
2070
+ metadata.totalRecords = totalRecords;
2071
+ metadata.dataType = detectedDataType;
2072
+ return metadata;
2073
+ }
2074
+ /**
2075
+ * Build metadata optimized - only reads first and last files
2076
+ * Assumes all middle files have the same record count as the first file
2077
+ * Much faster for large datasets with many files
2078
+ */
2079
+ async buildMetadataOptimized(version) {
2080
+ const versionPath = path3.join(this.getDestinationPath(), version);
2081
+ if (!fs3.existsSync(versionPath)) {
2082
+ return this.getDefaultMetadata();
2083
+ }
2084
+ const files = (await fs3.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
2085
+ if (files.length === 0) {
2086
+ return this.getDefaultMetadata();
2087
+ }
2088
+ const metadata = this.getDefaultMetadata();
2089
+ metadata.version = version;
2090
+ metadata.files = files.map((fileName, index) => ({
2091
+ number: index + 1,
2092
+ recordsCount: 0,
2093
+ fileName
2094
+ }));
2095
+ const firstFile = metadata.files[0];
2096
+ const firstFilePath = path3.join(versionPath, firstFile.fileName);
2097
+ const firstFileRaw = await fs3.promises.readFile(firstFilePath, "utf8");
2098
+ let firstFileData;
2099
+ try {
2100
+ firstFileData = JSON.parse(firstFileRaw);
2101
+ } catch (e) {
2102
+ firstFileData = firstFileRaw;
2103
+ }
2104
+ metadata.dataType = detectDataType(firstFileData);
2105
+ if (metadata.dataType === "json-array") {
2106
+ const firstFileCount = Array.isArray(firstFileData) ? firstFileData.length : 1;
2107
+ firstFile.recordsCount = firstFileCount;
2108
+ for (let i = 1; i < metadata.files.length - 1; i++) {
2109
+ metadata.files[i].recordsCount = firstFileCount;
2110
+ }
2111
+ if (files.length > 1) {
2112
+ const lastFile = metadata.files[metadata.files.length - 1];
2113
+ const lastFilePath = path3.join(versionPath, lastFile.fileName);
2114
+ const lastFileRaw = await fs3.promises.readFile(lastFilePath, "utf8");
2115
+ const lastFileData = deserializeData(lastFileRaw, metadata.dataType);
2116
+ lastFile.recordsCount = Array.isArray(lastFileData) ? lastFileData.length : 1;
2117
+ }
2118
+ metadata.totalRecords = metadata.files.reduce((sum, file) => sum + file.recordsCount, 0);
2119
+ } else {
2120
+ metadata.files.forEach((file) => {
2121
+ file.recordsCount = 1;
2122
+ });
2123
+ metadata.totalRecords = files.length;
2124
+ }
2125
+ return metadata;
2126
+ }
2127
+ /**
2128
+ * Figure out metadata - tries JSON first, then builds from files
2129
+ * Uses optimized building when no synopsis calculation is needed
2130
+ */
2131
+ async figureMetadata(version, useOptimized = true) {
2132
+ if (this.useMetadata) {
2133
+ const metadata = await this.loadMetadataJson(version);
2134
+ if (metadata) {
2135
+ return metadata;
2136
+ }
2137
+ }
2138
+ if (useOptimized && !this.fileSynopsisFunction && !this.versionSynopsisFunction) {
2139
+ return await this.buildMetadataOptimized(version);
2140
+ }
2141
+ return await this.figureMetadataFromVersionFiles(version);
2142
+ }
2143
+ /**
2144
+ * Load version metadata (main entry point for loading)
2145
+ */
2146
+ async loadVersionMetadata(version) {
2147
+ const metadata = await this.figureMetadata(version);
2148
+ this.metadata = metadata;
2149
+ return metadata;
2150
+ }
2151
+ /**
2152
+ * Save version metadata to file
2153
+ */
2154
+ async saveVersionMetadata(metadata) {
2155
+ if (!this.useMetadata || !this.currentVersion) {
2156
+ return;
2157
+ }
2158
+ const metadataToSave = metadata || this.metadata;
2159
+ const metadataFile = path3.join(this.getDestinationPath(), this.currentVersion, "metadata.json");
2160
+ await fs3.promises.writeFile(metadataFile, JSON.stringify(metadataToSave, null, 4), "utf8");
2161
+ }
2162
+ /**
2163
+ * Create a new file entry in metadata
2164
+ */
2165
+ makeNewFile() {
2166
+ this.currentFileNumber = (this.currentFileNumber || 0) + 1;
2167
+ const dataType = this.metadata.dataType || "json-array";
2168
+ const fileEntry = {
2169
+ number: this.currentFileNumber,
2170
+ recordsCount: 0,
2171
+ fileName: `${this.currentFileNumber.toString().padStart(6, "0")}.${getFileExtension(dataType)}`
2172
+ };
2173
+ this.metadata.files.push(fileEntry);
2174
+ this.lastFileData = null;
2175
+ this.logger.debug?.(`[FileDatabase] Created new file: ${fileEntry.fileName}, fileNumber: ${this.currentFileNumber}`);
2176
+ }
2177
+ /**
2178
+ * Figure out what data to write and which file to use (for pagination)
2179
+ */
2180
+ figureOutDataAndFileToWrite(data) {
2181
+ let dataToWrite;
2182
+ let dataLeftOver;
2183
+ const lastFile = this.metadata.files[this.metadata.files.length - 1];
2184
+ const lastFileRecordsCount = lastFile.recordsCount;
2185
+ if (Array.isArray(data)) {
2186
+ if (lastFileRecordsCount < this.pageSize) {
2187
+ dataToWrite = [...this.lastFileData || [], ...data.slice(0, this.pageSize - lastFileRecordsCount)];
2188
+ dataLeftOver = data.slice(this.pageSize - lastFileRecordsCount);
2189
+ } else {
2190
+ this.makeNewFile();
2191
+ dataToWrite = data.slice(0, this.pageSize);
2192
+ dataLeftOver = data.slice(this.pageSize);
2193
+ }
2194
+ this.lastFileData = dataToWrite;
2195
+ } else {
2196
+ dataToWrite = data;
2197
+ dataLeftOver = null;
2198
+ }
2199
+ const fileName = this.metadata.files[this.metadata.files.length - 1].fileName;
2200
+ this.logger.debug?.(
2201
+ `[FileDatabase] figureOutDataAndFileToWrite: filename=${fileName}, dataToWrite.length=${Array.isArray(dataToWrite) ? dataToWrite.length : "N/A"}, lastFileRecordsCount=${lastFileRecordsCount}`
2202
+ );
2203
+ return { dataToWrite, dataLeftOver, fileName };
2204
+ }
2205
+ /**
2206
+ * Calculate file-level synopsis if function is set
2207
+ */
2208
+ calculateFileSynopsis(data, fileIndex = this.metadata.files.length - 1) {
2209
+ if (!this.fileSynopsisFunction) {
2210
+ return;
2211
+ }
2212
+ const fileInfo = this.metadata.files[fileIndex];
2213
+ const enhancedFileInfo = this.fileSynopsisFunction(fileInfo, data);
2214
+ this.metadata.files[fileIndex] = enhancedFileInfo;
2215
+ }
2216
+ /**
2217
+ * Calculate version-level synopsis if function is set
2218
+ */
2219
+ calculateVersionSynopsis() {
2220
+ if (!this.versionSynopsisFunction) {
2221
+ return;
2222
+ }
2223
+ const enhancedMetadata = this.versionSynopsisFunction(this.metadata);
2224
+ this.metadata = enhancedMetadata;
2225
+ }
2226
+ /**
2227
+ * Update metadata after writing data
2228
+ */
2229
+ updateMetadata(dataToWrite, fileName) {
2230
+ let currentFile;
2231
+ if (fileName) {
2232
+ const foundFile = this.metadata.files.find((file) => file.fileName === fileName);
2233
+ if (!foundFile) {
2234
+ this.logger.warn?.(`[FileDatabase] File ${fileName} not found in metadata, using last file`);
2235
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
2236
+ } else {
2237
+ currentFile = foundFile;
2238
+ }
2239
+ } else {
2240
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
2241
+ }
2242
+ const recordsCount = Array.isArray(dataToWrite) ? dataToWrite.length : 1;
2243
+ currentFile.recordsCount = recordsCount;
2244
+ const fileIndex = this.metadata.files.indexOf(currentFile);
2245
+ if (fileIndex !== -1) {
2246
+ this.calculateFileSynopsis(dataToWrite, fileIndex);
2247
+ }
2248
+ this.metadata.version = this.currentVersion;
2249
+ this.metadata.modifiedAt = (/* @__PURE__ */ new Date()).toISOString();
2250
+ this.metadata.dataType = detectDataType(dataToWrite);
2251
+ this.metadata.totalRecords = this.metadata.files.reduce((sum, file) => sum + (file.recordsCount || 0), 0);
2252
+ this.logger.debug?.(
2253
+ `[FileDatabase] Updated metadata for file ${currentFile.fileName}: recordsCount=${recordsCount}, totalRecords=${this.metadata.totalRecords}`
2254
+ );
2255
+ }
2256
+ /**
2257
+ * Safe write with disk space check
2258
+ */
2259
+ async safeWrite(filePath, data) {
2260
+ const serializedData = serializeData(data);
2261
+ const dir = path3.dirname(filePath);
2262
+ const requiredBytes = Buffer.byteLength(serializedData, "utf8");
2263
+ const freeBytes = getFreeDiskSpace(dir);
2264
+ if (freeBytes !== null) {
2265
+ if (freeBytes < requiredBytes) {
2266
+ throw new FileDatabaseError(
2267
+ `Not enough disk space. Required: ${bytesToHumanReadable(requiredBytes)}, Free: ${bytesToHumanReadable(freeBytes)}`
2268
+ );
2269
+ }
2270
+ if (freeBytes < this.freeSpaceThreshold) {
2271
+ this.logger.warn?.(`Low disk space warning: only ${bytesToHumanReadable(freeBytes)} left`);
2272
+ }
2273
+ }
2274
+ try {
2275
+ await fs3.promises.writeFile(filePath, serializedData, "utf8");
2276
+ this.logger.debug?.(`[FileDatabase] Wrote ${bytesToHumanReadable(requiredBytes)} to ${filePath}`);
2277
+ } catch (error) {
2278
+ throw new FileDatabaseError(`Failed to write file ${filePath}: ${error.message}`);
2279
+ }
2280
+ }
2281
+ /**
2282
+ * Prepare the instance for read or write operations
2283
+ * This discovers state and sets up internal members based on mode and current data
2284
+ */
2285
+ async prepare({ write, read, version }) {
2286
+ if (write) {
2287
+ if (this.currentVersion === null) {
2288
+ await this.makeNewVersion();
2289
+ this.metadata = this.getDefaultMetadata();
2290
+ this.metadata.version = this.currentVersion;
2291
+ this.makeNewFile();
2292
+ } else {
2293
+ if (!this.metadata.files.length) {
2294
+ this.metadata = await this.figureMetadata(this.currentVersion);
2295
+ }
2296
+ }
2297
+ } else if (read) {
2298
+ const versions = await this.getVersions();
2299
+ if (versions.length === 0) {
2300
+ throw new FileDatabaseError("[FileDatabase] No versions found, cannot read");
2301
+ }
2302
+ if (version) {
2303
+ if (!versions.includes(version)) {
2304
+ throw new FileDatabaseError(`[FileDatabase] Version "${version}" not found`);
2305
+ }
2306
+ await this.setCurrentVersion(version);
2307
+ } else {
2308
+ await this.setCurrentVersion(versions[versions.length - 1]);
2309
+ }
2310
+ if (!this.metadata.files.length) {
2311
+ this.metadata = await this.figureMetadata(this.currentVersion);
2312
+ }
2313
+ }
2314
+ }
2315
+ /**
2316
+ * Write data to the file database
2317
+ */
2318
+ async write(data, options = {}) {
2319
+ await this.prepare({ write: true });
2320
+ if (options.forceNewVersion) {
2321
+ await this.makeNewVersion();
2322
+ this.metadata = this.getDefaultMetadata();
2323
+ this.metadata.version = this.currentVersion;
2324
+ this.makeNewFile();
2325
+ }
2326
+ let { dataToWrite, dataLeftOver, fileName } = this.figureOutDataAndFileToWrite(data);
2327
+ await this.safeWrite(path3.join(this.currentVersionFolder, fileName), dataToWrite);
2328
+ this.updateMetadata(dataToWrite, fileName);
2329
+ while (dataLeftOver && dataLeftOver.length > 0) {
2330
+ const writeContext = this.figureOutDataAndFileToWrite(dataLeftOver);
2331
+ await this.safeWrite(path3.join(this.currentVersionFolder, writeContext.fileName), writeContext.dataToWrite);
2332
+ this.updateMetadata(writeContext.dataToWrite, writeContext.fileName);
2333
+ dataLeftOver = writeContext.dataLeftOver;
2334
+ }
2335
+ this.calculateVersionSynopsis();
2336
+ if (this.useMetadata) {
2337
+ await this.saveVersionMetadata(this.metadata);
2338
+ }
2339
+ }
2340
+ /**
2341
+ * Read data from the file database
2342
+ */
2343
+ async read(options = {}) {
2344
+ const { version, nextPage = false, pageSize } = options;
2345
+ await this.prepare({ read: true, version });
2346
+ const isNonPaginatedData = this.metadata.dataType === "text" || this.metadata.dataType === "xml" || this.metadata.dataType === "json-object";
2347
+ if (isNonPaginatedData) {
2348
+ const file = this.metadata.files[0];
2349
+ const filePath = path3.join(this.getDestinationPath(), this.currentVersion, file.fileName);
2350
+ try {
2351
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
2352
+ return deserializeData(rawData, this.metadata.dataType);
2353
+ } catch (error) {
2354
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
2355
+ }
2356
+ }
2357
+ let effectivePageSize;
2358
+ if (nextPage && this.hasReadFirstPage) {
2359
+ effectivePageSize = pageSize || this.pageSize;
2360
+ this.currentRecord += effectivePageSize;
2361
+ } else if (!nextPage) {
2362
+ effectivePageSize = pageSize !== void 0 ? pageSize : this.metadata.totalRecords;
2363
+ this.currentRecord = 0;
2364
+ } else {
2365
+ effectivePageSize = pageSize || this.pageSize;
2366
+ }
2367
+ if (this.currentRecord >= this.metadata.totalRecords) {
2368
+ return [];
2369
+ }
2370
+ const result = [];
2371
+ let recordsRead = 0;
2372
+ let currentFileIndex = 0;
2373
+ let currentFileOffset = 0;
2374
+ let totalRecords = 0;
2375
+ for (let i = 0; i < this.metadata.files.length; i++) {
2376
+ const file = this.metadata.files[i];
2377
+ if (this.currentRecord < totalRecords + file.recordsCount) {
2378
+ currentFileIndex = i;
2379
+ currentFileOffset = totalRecords;
2380
+ break;
2381
+ }
2382
+ totalRecords += file.recordsCount;
2383
+ }
2384
+ let cumulativeRecords = currentFileOffset;
2385
+ for (let i = currentFileIndex; i < this.metadata.files.length && recordsRead < effectivePageSize; i++) {
2386
+ const file = this.metadata.files[i];
2387
+ const filePath = path3.join(this.getDestinationPath(), this.currentVersion, file.fileName);
2388
+ try {
2389
+ const rawData = await fs3.promises.readFile(filePath, "utf8");
2390
+ const fileData = deserializeData(rawData, this.metadata.dataType);
2391
+ let startIndex = 0;
2392
+ if (i === currentFileIndex) {
2393
+ startIndex = this.currentRecord - cumulativeRecords;
2394
+ }
2395
+ const endIndex = Math.min(startIndex + (effectivePageSize - recordsRead), fileData.length);
2396
+ const recordsFromThisFile = fileData.slice(startIndex, endIndex);
2397
+ result.push(...recordsFromThisFile);
2398
+ recordsRead += recordsFromThisFile.length;
2399
+ cumulativeRecords += file.recordsCount;
2400
+ } catch (error) {
2401
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
2402
+ }
2403
+ }
2404
+ if (result.length > 0) {
2405
+ if (nextPage || pageSize !== void 0 && pageSize < this.metadata.totalRecords) {
2406
+ this.hasReadFirstPage = true;
2407
+ }
2408
+ }
2409
+ return result;
2410
+ }
2411
+ /**
2412
+ * Set the starting record for pagination (1-based index)
2413
+ */
2414
+ setStartRecord(startRecord) {
2415
+ this.currentRecord = startRecord - 1;
2416
+ this.hasReadFirstPage = false;
2417
+ }
2418
+ /**
2419
+ * Reset read pagination state
2420
+ */
2421
+ resetPagination() {
2422
+ this.currentRecord = 0;
2423
+ this.hasReadFirstPage = false;
2424
+ }
2425
+ /**
2426
+ * Set file-level synopsis calculation function
2427
+ */
2428
+ setFileSynopsisFunction(fn) {
2429
+ this.fileSynopsisFunction = fn;
2430
+ }
2431
+ /**
2432
+ * Set version-level synopsis calculation function
2433
+ */
2434
+ setVersionSynopsisFunction(fn) {
2435
+ this.versionSynopsisFunction = fn;
2436
+ }
2437
+ /**
2438
+ * Get current version name
2439
+ */
2440
+ getCurrentVersion() {
2441
+ return this.currentVersion;
2442
+ }
2443
+ /**
2444
+ * Get current metadata
2445
+ */
2446
+ getMetadata() {
2447
+ return { ...this.metadata };
2448
+ }
2449
+ };
1718
2450
  export {
1719
2451
  Args,
1720
2452
  Divider,
2453
+ FileDatabase,
2454
+ FileDatabaseError,
1721
2455
  FooterPresets,
1722
2456
  GridCell,
1723
2457
  InputField,
@@ -1736,6 +2470,8 @@ export {
1736
2470
  buildBreadcrumb,
1737
2471
  buildDetailBreadcrumb,
1738
2472
  buildFooter,
2473
+ defaultFileSynopsisFunction,
2474
+ defaultVersionSynopsisFunction,
1739
2475
  getArgsInstance,
1740
2476
  getParamsInstance,
1741
2477
  joiEdateType,