@nmakarov/cli-toolkit 0.1.4 → 0.3.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.cjs CHANGED
@@ -32,6 +32,8 @@ var src_exports = {};
32
32
  __export(src_exports, {
33
33
  Args: () => Args,
34
34
  Divider: () => Divider,
35
+ FileDatabase: () => FileDatabase,
36
+ FileDatabaseError: () => FileDatabaseError,
35
37
  FooterPresets: () => FooterPresets,
36
38
  GridCell: () => GridCell,
37
39
  InputField: () => InputField,
@@ -50,6 +52,8 @@ __export(src_exports, {
50
52
  buildBreadcrumb: () => buildBreadcrumb,
51
53
  buildDetailBreadcrumb: () => buildDetailBreadcrumb,
52
54
  buildFooter: () => buildFooter,
55
+ defaultFileSynopsisFunction: () => defaultFileSynopsisFunction,
56
+ defaultVersionSynopsisFunction: () => defaultVersionSynopsisFunction,
53
57
  getArgsInstance: () => getArgsInstance,
54
58
  getParamsInstance: () => getParamsInstance,
55
59
  joiEdateType: () => joiEdateType,
@@ -449,7 +453,7 @@ var Args = class {
449
453
  command: this.commands[0] || "",
450
454
  flags: { ...this.flags },
451
455
  options: { ...this.options },
452
- usedKeys: new Set(this.usedKeys)
456
+ usedKeys: Array.from(this.usedKeys)
453
457
  };
454
458
  }
455
459
  /**
@@ -665,8 +669,6 @@ var Params = class {
665
669
  } else if (str.match(/^boolean|^bool/i)) {
666
670
  type = import_joi.default.boolean();
667
671
  } else if (str.match(/^date/i)) {
668
- type = import_joi.default.date();
669
- } else if (str.match(/^edate/i)) {
670
672
  type = import_joi.default.custom(joiEdateType);
671
673
  } else if (str.match(/^duration/i)) {
672
674
  type = import_joi.default.string().isoDuration();
@@ -1662,11 +1664,11 @@ function buildBreadcrumb(parts) {
1662
1664
  if (parts.length === 1) return parts[0];
1663
1665
  return parts.slice(1).map((part) => `\u2190 ${part}`).join(" ");
1664
1666
  }
1665
- function buildDetailBreadcrumb(path, suffix = "") {
1666
- if (path.length <= 1) {
1667
- return suffix ? `\u2190 ${suffix}` : path[0] || "";
1667
+ function buildDetailBreadcrumb(path4, suffix = "") {
1668
+ if (path4.length <= 1) {
1669
+ return suffix ? `\u2190 ${suffix}` : path4[0] || "";
1668
1670
  }
1669
- const breadcrumb = buildBreadcrumb(path);
1671
+ const breadcrumb = buildBreadcrumb(path4);
1670
1672
  return suffix ? `${breadcrumb} ${suffix}` : breadcrumb;
1671
1673
  }
1672
1674
 
@@ -1774,10 +1776,900 @@ function organizeFooterMessages(messages) {
1774
1776
  lines.push(...others);
1775
1777
  return lines;
1776
1778
  }
1779
+
1780
+ // src/filedatabase/index.ts
1781
+ var import_fs4 = __toESM(require("fs"), 1);
1782
+ var import_path4 = __toESM(require("path"), 1);
1783
+
1784
+ // src/utils/os-utils.ts
1785
+ var import_fs2 = __toESM(require("fs"), 1);
1786
+ var import_path2 = __toESM(require("path"), 1);
1787
+ var import_child_process = require("child_process");
1788
+ function getFreeDiskSpace(targetPath) {
1789
+ try {
1790
+ let pathToCheck = targetPath;
1791
+ if (!import_fs2.default.existsSync(targetPath)) {
1792
+ const parentDir = import_path2.default.dirname(targetPath);
1793
+ if (import_fs2.default.existsSync(parentDir)) {
1794
+ pathToCheck = parentDir;
1795
+ } else {
1796
+ pathToCheck = process.platform === "win32" ? "C:\\" : "/";
1797
+ }
1798
+ }
1799
+ if (process.platform === "win32") {
1800
+ return null;
1801
+ } else {
1802
+ const stdout = (0, import_child_process.execSync)(`df -k "${pathToCheck}"`, { encoding: "utf8" });
1803
+ const lines = stdout.trim().split("\n");
1804
+ const parts = lines[1].split(/\s+/);
1805
+ const freeKb = parseInt(parts[3], 10);
1806
+ return freeKb * 1024;
1807
+ }
1808
+ } catch (error) {
1809
+ return null;
1810
+ }
1811
+ }
1812
+
1813
+ // src/utils/fs-utils.ts
1814
+ var import_fs3 = __toESM(require("fs"), 1);
1815
+ var import_path3 = __toESM(require("path"), 1);
1816
+ async function ensurePath(...pathParts) {
1817
+ const fullPath = import_path3.default.resolve(...pathParts);
1818
+ if (!import_fs3.default.existsSync(fullPath)) {
1819
+ await import_fs3.default.promises.mkdir(fullPath, { recursive: true });
1820
+ }
1821
+ return fullPath;
1822
+ }
1823
+ function getFileExtension(dataType) {
1824
+ switch (dataType) {
1825
+ case "json-array":
1826
+ case "json-object":
1827
+ return "json";
1828
+ case "text":
1829
+ return "txt";
1830
+ case "xml":
1831
+ return "xml";
1832
+ default:
1833
+ return "json";
1834
+ }
1835
+ }
1836
+
1837
+ // src/utils/format-utils.ts
1838
+ function bytesToHumanReadable(bytes) {
1839
+ if (bytes === 0) return "0 B";
1840
+ const k = 1024;
1841
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
1842
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1843
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
1844
+ }
1845
+
1846
+ // src/utils/date-utils.ts
1847
+ function isTimestampFolder(folderName) {
1848
+ const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|\.\d{3}Z)$/;
1849
+ if (!isoRegex.test(folderName)) {
1850
+ return false;
1851
+ }
1852
+ const date = new Date(folderName);
1853
+ return !isNaN(date.getTime()) && date.getTime() > 0;
1854
+ }
1855
+
1856
+ // src/filedatabase/serializers.ts
1857
+ function detectDataType(data) {
1858
+ if (Array.isArray(data)) {
1859
+ return "json-array";
1860
+ } else if (typeof data === "object" && data !== null) {
1861
+ return "json-object";
1862
+ } else if (typeof data === "string") {
1863
+ const trimmed = data.trim();
1864
+ if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
1865
+ return "xml";
1866
+ }
1867
+ return "text";
1868
+ } else {
1869
+ return "text";
1870
+ }
1871
+ }
1872
+ function serializeData(data) {
1873
+ const dataType = detectDataType(data);
1874
+ if (dataType === "json-array" || dataType === "json-object") {
1875
+ return JSON.stringify(data, null, 4);
1876
+ } else {
1877
+ return String(data);
1878
+ }
1879
+ }
1880
+ function deserializeData(rawData, dataType) {
1881
+ if (dataType === "json-array" || dataType === "json-object") {
1882
+ return JSON.parse(rawData);
1883
+ } else {
1884
+ return rawData;
1885
+ }
1886
+ }
1887
+
1888
+ // src/filedatabase/synopsis-functions.ts
1889
+ function defaultFileSynopsisFunction(fileEntry, data) {
1890
+ if (!Array.isArray(data) || data.length === 0) {
1891
+ return { ...fileEntry };
1892
+ }
1893
+ const timestamps = [];
1894
+ const statusCounts = {};
1895
+ for (const item of data) {
1896
+ let ts = null;
1897
+ let status = null;
1898
+ for (const [key, value] of Object.entries(item)) {
1899
+ const k = key.toLowerCase();
1900
+ if (k === "modificationtimestamp") {
1901
+ ts = new Date(value).getTime();
1902
+ }
1903
+ if (k === "standardstatus") {
1904
+ status = value;
1905
+ }
1906
+ }
1907
+ if (ts && !isNaN(ts)) {
1908
+ timestamps.push(ts);
1909
+ }
1910
+ if (status !== null && status !== void 0) {
1911
+ statusCounts[status] = (statusCounts[status] || 0) + 1;
1912
+ }
1913
+ }
1914
+ const result = { ...fileEntry };
1915
+ if (timestamps.length) {
1916
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
1917
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
1918
+ }
1919
+ if (Object.keys(statusCounts).length) {
1920
+ result.StandardStatuses = statusCounts;
1921
+ }
1922
+ return result;
1923
+ }
1924
+ function defaultVersionSynopsisFunction(metadata) {
1925
+ if (!metadata?.files || !Array.isArray(metadata.files)) {
1926
+ return metadata;
1927
+ }
1928
+ const timestamps = [];
1929
+ const statusCounts = {};
1930
+ for (const file of metadata.files) {
1931
+ if (file.minModificationTimestamp) {
1932
+ const minTs = new Date(file.minModificationTimestamp).getTime();
1933
+ if (!isNaN(minTs)) timestamps.push(minTs);
1934
+ }
1935
+ if (file.maxModificationTimestamp) {
1936
+ const maxTs = new Date(file.maxModificationTimestamp).getTime();
1937
+ if (!isNaN(maxTs)) timestamps.push(maxTs);
1938
+ }
1939
+ if (file.StandardStatuses && typeof file.StandardStatuses === "object") {
1940
+ for (const [status, count] of Object.entries(file.StandardStatuses)) {
1941
+ statusCounts[status] = (statusCounts[status] || 0) + count;
1942
+ }
1943
+ }
1944
+ }
1945
+ const result = { ...metadata };
1946
+ if (timestamps.length) {
1947
+ result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
1948
+ result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
1949
+ }
1950
+ if (Object.keys(statusCounts).length > 0) {
1951
+ result.StandardStatuses = statusCounts;
1952
+ }
1953
+ return result;
1954
+ }
1955
+
1956
+ // src/filedatabase/index.ts
1957
+ var FileDatabaseError = class extends Error {
1958
+ constructor(message) {
1959
+ super(message);
1960
+ this.name = "FileDatabaseError";
1961
+ }
1962
+ };
1963
+ var FileDatabase = class {
1964
+ basePath;
1965
+ namespace;
1966
+ tableName = null;
1967
+ versioned;
1968
+ maxVersions;
1969
+ pageSize;
1970
+ useMetadata;
1971
+ freeSpaceThreshold;
1972
+ logger;
1973
+ // Current operation state
1974
+ currentVersion = null;
1975
+ currentVersionFolder = null;
1976
+ currentFileNumber = 0;
1977
+ currentRecord = 0;
1978
+ hasReadFirstPage = false;
1979
+ lastFileData = null;
1980
+ metadata;
1981
+ // Synopsis calculation functions
1982
+ fileSynopsisFunction = null;
1983
+ versionSynopsisFunction = null;
1984
+ constructor(config2) {
1985
+ if (!config2.basePath) {
1986
+ throw new ParamError("[FileDatabase] basePath is required");
1987
+ }
1988
+ this.basePath = config2.basePath;
1989
+ this.namespace = config2.namespace || "default";
1990
+ this.tableName = config2.tableName || null;
1991
+ this.versioned = config2.versioned ?? true;
1992
+ this.maxVersions = config2.maxVersions || 5;
1993
+ this.pageSize = config2.pageSize || 5e3;
1994
+ this.useMetadata = config2.useMetadata !== false;
1995
+ this.freeSpaceThreshold = config2.freeSpaceThreshold || 100 * 1024 * 1024;
1996
+ this.logger = config2.logger || console;
1997
+ this.metadata = this.getDefaultMetadata();
1998
+ }
1999
+ /**
2000
+ * Get default metadata structure
2001
+ */
2002
+ getDefaultMetadata() {
2003
+ return {
2004
+ version: this.currentVersion || null,
2005
+ files: [],
2006
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2007
+ modifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
2008
+ totalRecords: 0,
2009
+ synopsis: null,
2010
+ dataType: null
2011
+ };
2012
+ }
2013
+ /**
2014
+ * Get the destination path (basePath/namespace/tableName[/version])
2015
+ */
2016
+ getDestinationPath(version) {
2017
+ const errors = ["basePath", "namespace", "tableName"].filter((prop) => !this[prop]).map((prop) => `${prop} is not set`);
2018
+ if (errors.length) {
2019
+ throw new FileDatabaseError(`[FileDatabase] ${errors.join("; ")}`);
2020
+ }
2021
+ let parts = [this.basePath, this.namespace];
2022
+ if (this.tableName) {
2023
+ parts.push(...this.tableName.split("/"));
2024
+ }
2025
+ if (this.versioned && version) {
2026
+ parts.push(version);
2027
+ }
2028
+ return import_path4.default.resolve(...parts);
2029
+ }
2030
+ /**
2031
+ * Set current version and version folder
2032
+ */
2033
+ async setCurrentVersion(version) {
2034
+ this.currentVersion = version;
2035
+ this.currentVersionFolder = await ensurePath(this.getDestinationPath(), version);
2036
+ }
2037
+ /**
2038
+ * Create a new version folder with comprehensive timestamp logic
2039
+ * Only works in versioned mode
2040
+ */
2041
+ async makeNewVersion() {
2042
+ if (!this.versioned) {
2043
+ throw new FileDatabaseError("makeNewVersion() only works in versioned mode");
2044
+ }
2045
+ this.metadata = this.getDefaultMetadata();
2046
+ const existingVersions = await this.getVersions();
2047
+ let versionName;
2048
+ if (existingVersions.length > 0) {
2049
+ const maxTimestamp = existingVersions.reduce((max, version) => {
2050
+ const versionDate = new Date(version.replace("Z", ""));
2051
+ const maxDate2 = new Date(max.replace("Z", ""));
2052
+ return versionDate > maxDate2 ? version : max;
2053
+ });
2054
+ const maxDate = new Date(maxTimestamp.replace("Z", ""));
2055
+ const nextDate = new Date(maxDate.getTime() + 1e3);
2056
+ versionName = nextDate.toISOString().split(".")[0] + "Z";
2057
+ } else {
2058
+ const now = /* @__PURE__ */ new Date();
2059
+ versionName = now.toISOString().split(".")[0] + "Z";
2060
+ }
2061
+ await this.setCurrentVersion(versionName);
2062
+ this.currentFileNumber = 0;
2063
+ const versions = await this.getVersions();
2064
+ while (versions.length > this.maxVersions) {
2065
+ const versionToDelete = import_path4.default.resolve(this.getDestinationPath(), versions.shift());
2066
+ this.logger.debug?.(`[FileDatabase] Deleting old version: ${versionToDelete}`);
2067
+ await import_fs4.default.promises.rm(versionToDelete, { recursive: true, force: true });
2068
+ }
2069
+ return versionName;
2070
+ }
2071
+ /**
2072
+ * Get list of all versions (sorted chronologically)
2073
+ * Only works in versioned mode
2074
+ */
2075
+ async getVersions() {
2076
+ if (!this.versioned) {
2077
+ return [];
2078
+ }
2079
+ const destPath = this.getDestinationPath();
2080
+ try {
2081
+ await ensurePath(destPath);
2082
+ const items = await import_fs4.default.promises.readdir(destPath);
2083
+ const versions = items.filter((item) => {
2084
+ const itemPath = import_path4.default.join(destPath, item);
2085
+ const stat = import_fs4.default.statSync(itemPath);
2086
+ return stat.isDirectory() && isTimestampFolder(item);
2087
+ });
2088
+ return versions.sort();
2089
+ } catch (error) {
2090
+ return [];
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Get the latest version (most recent timestamp)
2095
+ * Only works in versioned mode
2096
+ * @returns Latest version string or null if no versions
2097
+ */
2098
+ async getLatestVersion() {
2099
+ if (!this.versioned) {
2100
+ throw new FileDatabaseError("getLatestVersion() only works in versioned mode");
2101
+ }
2102
+ const versions = await this.getVersions();
2103
+ if (versions.length === 0) {
2104
+ return null;
2105
+ }
2106
+ return versions[versions.length - 1];
2107
+ }
2108
+ /**
2109
+ * Check if any data exists in this table
2110
+ * Works for both versioned and non-versioned modes
2111
+ * @returns true if data exists
2112
+ */
2113
+ async hasData() {
2114
+ const tablePath = this.getDestinationPath();
2115
+ if (!import_fs4.default.existsSync(tablePath)) {
2116
+ return false;
2117
+ }
2118
+ if (this.versioned) {
2119
+ const versions = await this.getVersions();
2120
+ return versions.length > 0;
2121
+ } else {
2122
+ const items = await import_fs4.default.promises.readdir(tablePath);
2123
+ return items.some(
2124
+ (item) => item === "metadata.json" || item.match(/^\d{6}\.(json|txt|xml)$/) || item.endsWith(".json")
2125
+ );
2126
+ }
2127
+ }
2128
+ /**
2129
+ * Auto-detect the data format in this table
2130
+ * Used when reading existing data
2131
+ * @returns Format detection result
2132
+ */
2133
+ async detectDataFormat() {
2134
+ const tablePath = this.getDestinationPath();
2135
+ if (!import_fs4.default.existsSync(tablePath)) {
2136
+ return { versioned: false, hasMetadata: false, dataType: null };
2137
+ }
2138
+ const items = await import_fs4.default.promises.readdir(tablePath);
2139
+ if (items.includes("metadata.json")) {
2140
+ const metadata = JSON.parse(
2141
+ await import_fs4.default.promises.readFile(import_path4.default.join(tablePath, "metadata.json"), "utf8")
2142
+ );
2143
+ return {
2144
+ versioned: false,
2145
+ hasMetadata: true,
2146
+ dataType: metadata.dataType || null
2147
+ };
2148
+ }
2149
+ const versionFolders = items.filter((item) => {
2150
+ const itemPath = import_path4.default.join(tablePath, item);
2151
+ const stat = import_fs4.default.statSync(itemPath);
2152
+ return stat.isDirectory() && isTimestampFolder(item);
2153
+ });
2154
+ if (versionFolders.length > 0) {
2155
+ const latestVersion = versionFolders.sort().pop();
2156
+ const versionMetadataPath = import_path4.default.join(tablePath, latestVersion, "metadata.json");
2157
+ return {
2158
+ versioned: true,
2159
+ hasMetadata: import_fs4.default.existsSync(versionMetadataPath),
2160
+ dataType: null
2161
+ };
2162
+ }
2163
+ const dataFiles = items.filter((f) => f.match(/^\d{6}\.(json|txt|xml)$/));
2164
+ if (dataFiles.length > 0) {
2165
+ return {
2166
+ versioned: false,
2167
+ hasMetadata: false,
2168
+ dataType: null
2169
+ };
2170
+ }
2171
+ return { versioned: false, hasMetadata: false, dataType: null };
2172
+ }
2173
+ /**
2174
+ * Load metadata from JSON file
2175
+ */
2176
+ async loadMetadataJson(version) {
2177
+ const metadataFile = import_path4.default.join(this.getDestinationPath(), version, "metadata.json");
2178
+ if (import_fs4.default.existsSync(metadataFile)) {
2179
+ try {
2180
+ const rawData = await import_fs4.default.promises.readFile(metadataFile, "utf8");
2181
+ return JSON.parse(rawData);
2182
+ } catch (e) {
2183
+ throw new FileDatabaseError(`Failed to read metadata for version "${version}": ${e.message}`);
2184
+ }
2185
+ }
2186
+ return null;
2187
+ }
2188
+ /**
2189
+ * Build metadata by scanning files in a version folder (backward compatibility)
2190
+ * Reads all files to get accurate counts - used when synopsis calculation is needed
2191
+ */
2192
+ async figureMetadataFromVersionFiles(version) {
2193
+ const versionPath = import_path4.default.join(this.getDestinationPath(), version);
2194
+ if (!import_fs4.default.existsSync(versionPath)) {
2195
+ return this.getDefaultMetadata();
2196
+ }
2197
+ const files = (await import_fs4.default.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
2198
+ const metadata = this.getDefaultMetadata();
2199
+ metadata.version = version;
2200
+ metadata.files = [];
2201
+ let totalRecords = 0;
2202
+ let detectedDataType = null;
2203
+ for (let i = 0; i < files.length; i++) {
2204
+ const fileName = files[i];
2205
+ const filePath = import_path4.default.join(versionPath, fileName);
2206
+ try {
2207
+ const rawData = await import_fs4.default.promises.readFile(filePath, "utf8");
2208
+ const extension = import_path4.default.extname(fileName).toLowerCase();
2209
+ let dataType = "text";
2210
+ if (extension === ".json") {
2211
+ dataType = "json-array";
2212
+ } else if (extension === ".xml") {
2213
+ dataType = "xml";
2214
+ }
2215
+ const fileData = deserializeData(rawData, dataType);
2216
+ const recordsCount = Array.isArray(fileData) ? fileData.length : 1;
2217
+ if (detectedDataType === null) {
2218
+ detectedDataType = detectDataType(fileData);
2219
+ }
2220
+ const fileInfo = {
2221
+ number: i + 1,
2222
+ recordsCount,
2223
+ fileName
2224
+ };
2225
+ metadata.files.push(fileInfo);
2226
+ totalRecords += recordsCount;
2227
+ } catch (error) {
2228
+ this.logger.error?.(`[FileDatabase] Failed to read file ${fileName}: ${error.message}`);
2229
+ }
2230
+ }
2231
+ metadata.totalRecords = totalRecords;
2232
+ metadata.dataType = detectedDataType;
2233
+ return metadata;
2234
+ }
2235
+ /**
2236
+ * Build metadata optimized - only reads first and last files
2237
+ * Assumes all middle files have the same record count as the first file
2238
+ * Much faster for large datasets with many files
2239
+ */
2240
+ async buildMetadataOptimized(version) {
2241
+ const versionPath = import_path4.default.join(this.getDestinationPath(), version);
2242
+ if (!import_fs4.default.existsSync(versionPath)) {
2243
+ return this.getDefaultMetadata();
2244
+ }
2245
+ const files = (await import_fs4.default.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
2246
+ if (files.length === 0) {
2247
+ return this.getDefaultMetadata();
2248
+ }
2249
+ const metadata = this.getDefaultMetadata();
2250
+ metadata.version = version;
2251
+ metadata.files = files.map((fileName, index) => ({
2252
+ number: index + 1,
2253
+ recordsCount: 0,
2254
+ fileName
2255
+ }));
2256
+ const firstFile = metadata.files[0];
2257
+ const firstFilePath = import_path4.default.join(versionPath, firstFile.fileName);
2258
+ const firstFileRaw = await import_fs4.default.promises.readFile(firstFilePath, "utf8");
2259
+ let firstFileData;
2260
+ try {
2261
+ firstFileData = JSON.parse(firstFileRaw);
2262
+ } catch (e) {
2263
+ firstFileData = firstFileRaw;
2264
+ }
2265
+ metadata.dataType = detectDataType(firstFileData);
2266
+ if (metadata.dataType === "json-array") {
2267
+ const firstFileCount = Array.isArray(firstFileData) ? firstFileData.length : 1;
2268
+ firstFile.recordsCount = firstFileCount;
2269
+ for (let i = 1; i < metadata.files.length - 1; i++) {
2270
+ metadata.files[i].recordsCount = firstFileCount;
2271
+ }
2272
+ if (files.length > 1) {
2273
+ const lastFile = metadata.files[metadata.files.length - 1];
2274
+ const lastFilePath = import_path4.default.join(versionPath, lastFile.fileName);
2275
+ const lastFileRaw = await import_fs4.default.promises.readFile(lastFilePath, "utf8");
2276
+ const lastFileData = deserializeData(lastFileRaw, metadata.dataType);
2277
+ lastFile.recordsCount = Array.isArray(lastFileData) ? lastFileData.length : 1;
2278
+ }
2279
+ metadata.totalRecords = metadata.files.reduce((sum, file) => sum + file.recordsCount, 0);
2280
+ } else {
2281
+ metadata.files.forEach((file) => {
2282
+ file.recordsCount = 1;
2283
+ });
2284
+ metadata.totalRecords = files.length;
2285
+ }
2286
+ return metadata;
2287
+ }
2288
+ /**
2289
+ * Figure out metadata - tries JSON first, then builds from files
2290
+ * Uses optimized building when no synopsis calculation is needed
2291
+ */
2292
+ async figureMetadata(version, useOptimized = true) {
2293
+ if (this.useMetadata) {
2294
+ const metadata = await this.loadMetadataJson(version);
2295
+ if (metadata) {
2296
+ return metadata;
2297
+ }
2298
+ }
2299
+ if (useOptimized && !this.fileSynopsisFunction && !this.versionSynopsisFunction) {
2300
+ return await this.buildMetadataOptimized(version);
2301
+ }
2302
+ return await this.figureMetadataFromVersionFiles(version);
2303
+ }
2304
+ /**
2305
+ * Load version metadata (main entry point for loading)
2306
+ */
2307
+ async loadVersionMetadata(version) {
2308
+ const metadata = await this.figureMetadata(version);
2309
+ this.metadata = metadata;
2310
+ return metadata;
2311
+ }
2312
+ /**
2313
+ * Save version metadata to file
2314
+ */
2315
+ async saveVersionMetadata(metadata) {
2316
+ if (!this.useMetadata) {
2317
+ return;
2318
+ }
2319
+ const metadataToSave = metadata || this.metadata;
2320
+ let metadataFile;
2321
+ if (this.versioned) {
2322
+ if (!this.currentVersion) {
2323
+ return;
2324
+ }
2325
+ metadataFile = import_path4.default.join(this.getDestinationPath(), this.currentVersion, "metadata.json");
2326
+ } else {
2327
+ metadataFile = import_path4.default.join(this.getDestinationPath(), "metadata.json");
2328
+ }
2329
+ await import_fs4.default.promises.writeFile(metadataFile, JSON.stringify(metadataToSave, null, 4), "utf8");
2330
+ }
2331
+ /**
2332
+ * Create a new file entry in metadata
2333
+ */
2334
+ makeNewFile() {
2335
+ this.currentFileNumber = (this.currentFileNumber || 0) + 1;
2336
+ const dataType = this.metadata.dataType || "json-array";
2337
+ const fileEntry = {
2338
+ number: this.currentFileNumber,
2339
+ recordsCount: 0,
2340
+ fileName: `${this.currentFileNumber.toString().padStart(6, "0")}.${getFileExtension(dataType)}`
2341
+ };
2342
+ this.metadata.files.push(fileEntry);
2343
+ this.lastFileData = null;
2344
+ this.logger.debug?.(`[FileDatabase] Created new file: ${fileEntry.fileName}, fileNumber: ${this.currentFileNumber}`);
2345
+ }
2346
+ /**
2347
+ * Figure out what data to write and which file to use (for pagination)
2348
+ */
2349
+ figureOutDataAndFileToWrite(data) {
2350
+ let dataToWrite;
2351
+ let dataLeftOver;
2352
+ const lastFile = this.metadata.files[this.metadata.files.length - 1];
2353
+ const lastFileRecordsCount = lastFile.recordsCount;
2354
+ if (Array.isArray(data)) {
2355
+ if (lastFileRecordsCount < this.pageSize) {
2356
+ dataToWrite = [...this.lastFileData || [], ...data.slice(0, this.pageSize - lastFileRecordsCount)];
2357
+ dataLeftOver = data.slice(this.pageSize - lastFileRecordsCount);
2358
+ } else {
2359
+ this.makeNewFile();
2360
+ dataToWrite = data.slice(0, this.pageSize);
2361
+ dataLeftOver = data.slice(this.pageSize);
2362
+ }
2363
+ this.lastFileData = dataToWrite;
2364
+ } else {
2365
+ dataToWrite = data;
2366
+ dataLeftOver = null;
2367
+ }
2368
+ const fileName = this.metadata.files[this.metadata.files.length - 1].fileName;
2369
+ this.logger.debug?.(
2370
+ `[FileDatabase] figureOutDataAndFileToWrite: filename=${fileName}, dataToWrite.length=${Array.isArray(dataToWrite) ? dataToWrite.length : "N/A"}, lastFileRecordsCount=${lastFileRecordsCount}`
2371
+ );
2372
+ return { dataToWrite, dataLeftOver, fileName };
2373
+ }
2374
+ /**
2375
+ * Calculate file-level synopsis if function is set
2376
+ */
2377
+ calculateFileSynopsis(data, fileIndex = this.metadata.files.length - 1) {
2378
+ if (!this.fileSynopsisFunction) {
2379
+ return;
2380
+ }
2381
+ const fileInfo = this.metadata.files[fileIndex];
2382
+ const enhancedFileInfo = this.fileSynopsisFunction(fileInfo, data);
2383
+ this.metadata.files[fileIndex] = enhancedFileInfo;
2384
+ }
2385
+ /**
2386
+ * Calculate version-level synopsis if function is set
2387
+ */
2388
+ calculateVersionSynopsis() {
2389
+ if (!this.versionSynopsisFunction) {
2390
+ return;
2391
+ }
2392
+ const enhancedMetadata = this.versionSynopsisFunction(this.metadata);
2393
+ this.metadata = enhancedMetadata;
2394
+ }
2395
+ /**
2396
+ * Update metadata after writing data
2397
+ */
2398
+ updateMetadata(dataToWrite, fileName) {
2399
+ let currentFile;
2400
+ if (fileName) {
2401
+ const foundFile = this.metadata.files.find((file) => file.fileName === fileName);
2402
+ if (!foundFile) {
2403
+ this.logger.warn?.(`[FileDatabase] File ${fileName} not found in metadata, using last file`);
2404
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
2405
+ } else {
2406
+ currentFile = foundFile;
2407
+ }
2408
+ } else {
2409
+ currentFile = this.metadata.files[this.metadata.files.length - 1];
2410
+ }
2411
+ const recordsCount = Array.isArray(dataToWrite) ? dataToWrite.length : 1;
2412
+ currentFile.recordsCount = recordsCount;
2413
+ const fileIndex = this.metadata.files.indexOf(currentFile);
2414
+ if (fileIndex !== -1) {
2415
+ this.calculateFileSynopsis(dataToWrite, fileIndex);
2416
+ }
2417
+ this.metadata.version = this.currentVersion;
2418
+ this.metadata.modifiedAt = (/* @__PURE__ */ new Date()).toISOString();
2419
+ this.metadata.dataType = detectDataType(dataToWrite);
2420
+ this.metadata.totalRecords = this.metadata.files.reduce((sum, file) => sum + (file.recordsCount || 0), 0);
2421
+ this.logger.debug?.(
2422
+ `[FileDatabase] Updated metadata for file ${currentFile.fileName}: recordsCount=${recordsCount}, totalRecords=${this.metadata.totalRecords}`
2423
+ );
2424
+ }
2425
+ /**
2426
+ * Safe write with disk space check
2427
+ */
2428
+ async safeWrite(filePath, data) {
2429
+ const serializedData = serializeData(data);
2430
+ const dir = import_path4.default.dirname(filePath);
2431
+ const requiredBytes = Buffer.byteLength(serializedData, "utf8");
2432
+ const freeBytes = getFreeDiskSpace(dir);
2433
+ if (freeBytes !== null) {
2434
+ if (freeBytes < requiredBytes) {
2435
+ throw new FileDatabaseError(
2436
+ `Not enough disk space. Required: ${bytesToHumanReadable(requiredBytes)}, Free: ${bytesToHumanReadable(freeBytes)}`
2437
+ );
2438
+ }
2439
+ if (freeBytes < this.freeSpaceThreshold) {
2440
+ this.logger.warn?.(`Low disk space warning: only ${bytesToHumanReadable(freeBytes)} left`);
2441
+ }
2442
+ }
2443
+ try {
2444
+ await import_fs4.default.promises.writeFile(filePath, serializedData, "utf8");
2445
+ this.logger.debug?.(`[FileDatabase] Wrote ${bytesToHumanReadable(requiredBytes)} to ${filePath}`);
2446
+ } catch (error) {
2447
+ throw new FileDatabaseError(`Failed to write file ${filePath}: ${error.message}`);
2448
+ }
2449
+ }
2450
+ /**
2451
+ * Prepare the instance for read or write operations
2452
+ * This discovers state and sets up internal members based on mode and current data
2453
+ */
2454
+ async prepare({ write, read, version }) {
2455
+ if (write) {
2456
+ if (this.versioned) {
2457
+ if (this.currentVersion === null) {
2458
+ await this.makeNewVersion();
2459
+ this.metadata = this.getDefaultMetadata();
2460
+ this.metadata.version = this.currentVersion;
2461
+ this.makeNewFile();
2462
+ } else {
2463
+ if (!this.metadata.files.length) {
2464
+ this.metadata = await this.figureMetadata(this.currentVersion);
2465
+ }
2466
+ }
2467
+ } else {
2468
+ await ensurePath(this.getDestinationPath());
2469
+ if (this.useMetadata === true) {
2470
+ const metadataPath = import_path4.default.join(this.getDestinationPath(), "metadata.json");
2471
+ if (import_fs4.default.existsSync(metadataPath)) {
2472
+ try {
2473
+ const rawData = await import_fs4.default.promises.readFile(metadataPath, "utf8");
2474
+ this.metadata = JSON.parse(rawData);
2475
+ } catch (e) {
2476
+ this.metadata = this.getDefaultMetadata();
2477
+ }
2478
+ } else {
2479
+ this.metadata = this.getDefaultMetadata();
2480
+ this.makeNewFile();
2481
+ }
2482
+ } else {
2483
+ this.metadata = this.getDefaultMetadata();
2484
+ this.makeNewFile();
2485
+ }
2486
+ }
2487
+ } else if (read) {
2488
+ if (this.versioned) {
2489
+ const versions = await this.getVersions();
2490
+ if (versions.length === 0) {
2491
+ throw new FileDatabaseError("[FileDatabase] No versions found, cannot read");
2492
+ }
2493
+ if (version) {
2494
+ if (!versions.includes(version)) {
2495
+ throw new FileDatabaseError(`[FileDatabase] Version "${version}" not found`);
2496
+ }
2497
+ await this.setCurrentVersion(version);
2498
+ } else {
2499
+ await this.setCurrentVersion(versions[versions.length - 1]);
2500
+ }
2501
+ if (!this.metadata.files.length) {
2502
+ this.metadata = await this.figureMetadata(this.currentVersion);
2503
+ }
2504
+ } else {
2505
+ this.currentVersion = null;
2506
+ if (this.useMetadata === void 0) {
2507
+ const format = await this.detectDataFormat();
2508
+ this.useMetadata = format.hasMetadata;
2509
+ }
2510
+ if (this.useMetadata) {
2511
+ const metadataPath = import_path4.default.join(this.getDestinationPath(), "metadata.json");
2512
+ if (import_fs4.default.existsSync(metadataPath)) {
2513
+ try {
2514
+ const rawData = await import_fs4.default.promises.readFile(metadataPath, "utf8");
2515
+ this.metadata = JSON.parse(rawData);
2516
+ } catch (e) {
2517
+ throw new FileDatabaseError(`Failed to read metadata: ${e.message}`);
2518
+ }
2519
+ } else {
2520
+ throw new FileDatabaseError("[FileDatabase] No metadata found in non-versioned mode");
2521
+ }
2522
+ } else {
2523
+ this.metadata = await this.figureMetadataFromVersionFiles("");
2524
+ }
2525
+ }
2526
+ }
2527
+ }
2528
+ /**
2529
+ * Write data to the file database
2530
+ */
2531
+ async write(data, options = {}) {
2532
+ if (options.forceNewVersion && !this.versioned) {
2533
+ throw new FileDatabaseError("Cannot use forceNewVersion in non-versioned mode");
2534
+ }
2535
+ await this.prepare({ write: true });
2536
+ if (options.forceNewVersion) {
2537
+ await this.makeNewVersion();
2538
+ this.metadata = this.getDefaultMetadata();
2539
+ this.metadata.version = this.currentVersion;
2540
+ this.makeNewFile();
2541
+ }
2542
+ let { dataToWrite, dataLeftOver, fileName } = this.figureOutDataAndFileToWrite(data);
2543
+ const destPath = this.getDestinationPath(this.currentVersion || void 0);
2544
+ await this.safeWrite(import_path4.default.join(destPath, fileName), dataToWrite);
2545
+ this.updateMetadata(dataToWrite, fileName);
2546
+ while (dataLeftOver && dataLeftOver.length > 0) {
2547
+ const writeContext = this.figureOutDataAndFileToWrite(dataLeftOver);
2548
+ await this.safeWrite(import_path4.default.join(destPath, writeContext.fileName), writeContext.dataToWrite);
2549
+ this.updateMetadata(writeContext.dataToWrite, writeContext.fileName);
2550
+ dataLeftOver = writeContext.dataLeftOver;
2551
+ }
2552
+ this.calculateVersionSynopsis();
2553
+ if (this.useMetadata) {
2554
+ await this.saveVersionMetadata(this.metadata);
2555
+ }
2556
+ }
2557
+ /**
2558
+ * Read data from the file database
2559
+ */
2560
+ async read(options = {}) {
2561
+ const { version, nextPage = false, pageSize } = options;
2562
+ await this.prepare({ read: true, version });
2563
+ const isNonPaginatedData = this.metadata.dataType === "text" || this.metadata.dataType === "xml" || this.metadata.dataType === "json-object";
2564
+ if (isNonPaginatedData) {
2565
+ const file = this.metadata.files[0];
2566
+ const filePath = import_path4.default.join(this.getDestinationPath(this.currentVersion || void 0), file.fileName);
2567
+ try {
2568
+ const rawData = await import_fs4.default.promises.readFile(filePath, "utf8");
2569
+ return deserializeData(rawData, this.metadata.dataType);
2570
+ } catch (error) {
2571
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
2572
+ }
2573
+ }
2574
+ let effectivePageSize;
2575
+ if (nextPage && this.hasReadFirstPage) {
2576
+ effectivePageSize = pageSize || this.pageSize;
2577
+ this.currentRecord += effectivePageSize;
2578
+ } else if (!nextPage) {
2579
+ effectivePageSize = pageSize !== void 0 ? pageSize : this.metadata.totalRecords;
2580
+ this.currentRecord = 0;
2581
+ } else {
2582
+ effectivePageSize = pageSize || this.pageSize;
2583
+ }
2584
+ if (this.currentRecord >= this.metadata.totalRecords) {
2585
+ return [];
2586
+ }
2587
+ const result = [];
2588
+ let recordsRead = 0;
2589
+ let currentFileIndex = 0;
2590
+ let currentFileOffset = 0;
2591
+ let totalRecords = 0;
2592
+ for (let i = 0; i < this.metadata.files.length; i++) {
2593
+ const file = this.metadata.files[i];
2594
+ if (this.currentRecord < totalRecords + file.recordsCount) {
2595
+ currentFileIndex = i;
2596
+ currentFileOffset = totalRecords;
2597
+ break;
2598
+ }
2599
+ totalRecords += file.recordsCount;
2600
+ }
2601
+ let cumulativeRecords = currentFileOffset;
2602
+ for (let i = currentFileIndex; i < this.metadata.files.length && recordsRead < effectivePageSize; i++) {
2603
+ const file = this.metadata.files[i];
2604
+ const filePath = import_path4.default.join(this.getDestinationPath(this.currentVersion || void 0), file.fileName);
2605
+ try {
2606
+ const rawData = await import_fs4.default.promises.readFile(filePath, "utf8");
2607
+ const fileData = deserializeData(rawData, this.metadata.dataType);
2608
+ let startIndex = 0;
2609
+ if (i === currentFileIndex) {
2610
+ startIndex = this.currentRecord - cumulativeRecords;
2611
+ }
2612
+ const endIndex = Math.min(startIndex + (effectivePageSize - recordsRead), fileData.length);
2613
+ const recordsFromThisFile = fileData.slice(startIndex, endIndex);
2614
+ result.push(...recordsFromThisFile);
2615
+ recordsRead += recordsFromThisFile.length;
2616
+ cumulativeRecords += file.recordsCount;
2617
+ } catch (error) {
2618
+ throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
2619
+ }
2620
+ }
2621
+ if (result.length > 0) {
2622
+ if (nextPage || pageSize !== void 0 && pageSize < this.metadata.totalRecords) {
2623
+ this.hasReadFirstPage = true;
2624
+ }
2625
+ }
2626
+ return result;
2627
+ }
2628
+ /**
2629
+ * Set the starting record for pagination (1-based index)
2630
+ */
2631
+ setStartRecord(startRecord) {
2632
+ this.currentRecord = startRecord - 1;
2633
+ this.hasReadFirstPage = false;
2634
+ }
2635
+ /**
2636
+ * Reset read pagination state
2637
+ */
2638
+ resetPagination() {
2639
+ this.currentRecord = 0;
2640
+ this.hasReadFirstPage = false;
2641
+ }
2642
+ /**
2643
+ * Set file-level synopsis calculation function
2644
+ */
2645
+ setFileSynopsisFunction(fn) {
2646
+ this.fileSynopsisFunction = fn;
2647
+ }
2648
+ /**
2649
+ * Set version-level synopsis calculation function
2650
+ */
2651
+ setVersionSynopsisFunction(fn) {
2652
+ this.versionSynopsisFunction = fn;
2653
+ }
2654
+ /**
2655
+ * Get current version name
2656
+ */
2657
+ getCurrentVersion() {
2658
+ return this.currentVersion;
2659
+ }
2660
+ /**
2661
+ * Get current metadata
2662
+ */
2663
+ getMetadata() {
2664
+ return { ...this.metadata };
2665
+ }
2666
+ };
1777
2667
  // Annotate the CommonJS export names for ESM import in node:
1778
2668
  0 && (module.exports = {
1779
2669
  Args,
1780
2670
  Divider,
2671
+ FileDatabase,
2672
+ FileDatabaseError,
1781
2673
  FooterPresets,
1782
2674
  GridCell,
1783
2675
  InputField,
@@ -1796,6 +2688,8 @@ function organizeFooterMessages(messages) {
1796
2688
  buildBreadcrumb,
1797
2689
  buildDetailBreadcrumb,
1798
2690
  buildFooter,
2691
+ defaultFileSynopsisFunction,
2692
+ defaultVersionSynopsisFunction,
1799
2693
  getArgsInstance,
1800
2694
  getParamsInstance,
1801
2695
  joiEdateType,