@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/README.md +113 -2
- package/dist/args.cjs +1 -1
- package/dist/args.cjs.map +1 -1
- package/dist/args.js +1 -1
- package/dist/args.js.map +1 -1
- package/dist/filedatabase.cjs +948 -0
- package/dist/filedatabase.cjs.map +1 -0
- package/dist/filedatabase.js +908 -0
- package/dist/filedatabase.js.map +1 -0
- package/dist/http-client.cjs +356 -0
- package/dist/http-client.cjs.map +1 -0
- package/dist/http-client.js +318 -0
- package/dist/http-client.js.map +1 -0
- package/dist/index.cjs +901 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +897 -7
- package/dist/index.js.map +1 -1
- package/dist/mock-server.cjs +1483 -0
- package/dist/mock-server.cjs.map +1 -0
- package/dist/mock-server.js +1445 -0
- package/dist/mock-server.js.map +1 -0
- package/dist/params.cjs +0 -2
- package/dist/params.cjs.map +1 -1
- package/dist/params.js +0 -2
- package/dist/params.js.map +1 -1
- package/package.json +33 -3
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/filedatabase.ts
|
|
31
|
+
var filedatabase_exports = {};
|
|
32
|
+
__export(filedatabase_exports, {
|
|
33
|
+
FileDatabase: () => FileDatabase,
|
|
34
|
+
FileDatabaseError: () => FileDatabaseError,
|
|
35
|
+
defaultFileSynopsisFunction: () => defaultFileSynopsisFunction,
|
|
36
|
+
defaultVersionSynopsisFunction: () => defaultVersionSynopsisFunction
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(filedatabase_exports);
|
|
39
|
+
|
|
40
|
+
// src/filedatabase/index.ts
|
|
41
|
+
var import_fs3 = __toESM(require("fs"), 1);
|
|
42
|
+
var import_path3 = __toESM(require("path"), 1);
|
|
43
|
+
|
|
44
|
+
// src/utils/os-utils.ts
|
|
45
|
+
var import_fs = __toESM(require("fs"), 1);
|
|
46
|
+
var import_path = __toESM(require("path"), 1);
|
|
47
|
+
var import_child_process = require("child_process");
|
|
48
|
+
function getFreeDiskSpace(targetPath) {
|
|
49
|
+
try {
|
|
50
|
+
let pathToCheck = targetPath;
|
|
51
|
+
if (!import_fs.default.existsSync(targetPath)) {
|
|
52
|
+
const parentDir = import_path.default.dirname(targetPath);
|
|
53
|
+
if (import_fs.default.existsSync(parentDir)) {
|
|
54
|
+
pathToCheck = parentDir;
|
|
55
|
+
} else {
|
|
56
|
+
pathToCheck = process.platform === "win32" ? "C:\\" : "/";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (process.platform === "win32") {
|
|
60
|
+
return null;
|
|
61
|
+
} else {
|
|
62
|
+
const stdout = (0, import_child_process.execSync)(`df -k "${pathToCheck}"`, { encoding: "utf8" });
|
|
63
|
+
const lines = stdout.trim().split("\n");
|
|
64
|
+
const parts = lines[1].split(/\s+/);
|
|
65
|
+
const freeKb = parseInt(parts[3], 10);
|
|
66
|
+
return freeKb * 1024;
|
|
67
|
+
}
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/utils/fs-utils.ts
|
|
74
|
+
var import_fs2 = __toESM(require("fs"), 1);
|
|
75
|
+
var import_path2 = __toESM(require("path"), 1);
|
|
76
|
+
async function ensurePath(...pathParts) {
|
|
77
|
+
const fullPath = import_path2.default.resolve(...pathParts);
|
|
78
|
+
if (!import_fs2.default.existsSync(fullPath)) {
|
|
79
|
+
await import_fs2.default.promises.mkdir(fullPath, { recursive: true });
|
|
80
|
+
}
|
|
81
|
+
return fullPath;
|
|
82
|
+
}
|
|
83
|
+
function getFileExtension(dataType) {
|
|
84
|
+
switch (dataType) {
|
|
85
|
+
case "json-array":
|
|
86
|
+
case "json-object":
|
|
87
|
+
return "json";
|
|
88
|
+
case "text":
|
|
89
|
+
return "txt";
|
|
90
|
+
case "xml":
|
|
91
|
+
return "xml";
|
|
92
|
+
default:
|
|
93
|
+
return "json";
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/utils/format-utils.ts
|
|
98
|
+
function bytesToHumanReadable(bytes) {
|
|
99
|
+
if (bytes === 0) return "0 B";
|
|
100
|
+
const k = 1024;
|
|
101
|
+
const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
|
|
102
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
103
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/utils/date-utils.ts
|
|
107
|
+
function isTimestampFolder(folderName) {
|
|
108
|
+
const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|\.\d{3}Z)$/;
|
|
109
|
+
if (!isoRegex.test(folderName)) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
const date = new Date(folderName);
|
|
113
|
+
return !isNaN(date.getTime()) && date.getTime() > 0;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// src/filedatabase/serializers.ts
|
|
117
|
+
function detectDataType(data) {
|
|
118
|
+
if (Array.isArray(data)) {
|
|
119
|
+
return "json-array";
|
|
120
|
+
} else if (typeof data === "object" && data !== null) {
|
|
121
|
+
return "json-object";
|
|
122
|
+
} else if (typeof data === "string") {
|
|
123
|
+
const trimmed = data.trim();
|
|
124
|
+
if (trimmed.startsWith("<?xml") || trimmed.startsWith("<")) {
|
|
125
|
+
return "xml";
|
|
126
|
+
}
|
|
127
|
+
return "text";
|
|
128
|
+
} else {
|
|
129
|
+
return "text";
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function serializeData(data) {
|
|
133
|
+
const dataType = detectDataType(data);
|
|
134
|
+
if (dataType === "json-array" || dataType === "json-object") {
|
|
135
|
+
return JSON.stringify(data, null, 4);
|
|
136
|
+
} else {
|
|
137
|
+
return String(data);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function deserializeData(rawData, dataType) {
|
|
141
|
+
if (dataType === "json-array" || dataType === "json-object") {
|
|
142
|
+
return JSON.parse(rawData);
|
|
143
|
+
} else {
|
|
144
|
+
return rawData;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/errors.ts
|
|
149
|
+
var FrameworkError = class extends Error {
|
|
150
|
+
constructor(message) {
|
|
151
|
+
super(message);
|
|
152
|
+
this.name = "FrameworkError";
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
var ParamError = class extends FrameworkError {
|
|
156
|
+
constructor(message) {
|
|
157
|
+
super(message);
|
|
158
|
+
this.name = "ParamError";
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// src/filedatabase/synopsis-functions.ts
|
|
163
|
+
function defaultFileSynopsisFunction(fileEntry, data) {
|
|
164
|
+
if (!Array.isArray(data) || data.length === 0) {
|
|
165
|
+
return { ...fileEntry };
|
|
166
|
+
}
|
|
167
|
+
const timestamps = [];
|
|
168
|
+
const statusCounts = {};
|
|
169
|
+
for (const item of data) {
|
|
170
|
+
let ts = null;
|
|
171
|
+
let status = null;
|
|
172
|
+
for (const [key, value] of Object.entries(item)) {
|
|
173
|
+
const k = key.toLowerCase();
|
|
174
|
+
if (k === "modificationtimestamp") {
|
|
175
|
+
ts = new Date(value).getTime();
|
|
176
|
+
}
|
|
177
|
+
if (k === "standardstatus") {
|
|
178
|
+
status = value;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (ts && !isNaN(ts)) {
|
|
182
|
+
timestamps.push(ts);
|
|
183
|
+
}
|
|
184
|
+
if (status !== null && status !== void 0) {
|
|
185
|
+
statusCounts[status] = (statusCounts[status] || 0) + 1;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const result = { ...fileEntry };
|
|
189
|
+
if (timestamps.length) {
|
|
190
|
+
result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
|
|
191
|
+
result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
|
|
192
|
+
}
|
|
193
|
+
if (Object.keys(statusCounts).length) {
|
|
194
|
+
result.StandardStatuses = statusCounts;
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
}
|
|
198
|
+
function defaultVersionSynopsisFunction(metadata) {
|
|
199
|
+
if (!metadata?.files || !Array.isArray(metadata.files)) {
|
|
200
|
+
return metadata;
|
|
201
|
+
}
|
|
202
|
+
const timestamps = [];
|
|
203
|
+
const statusCounts = {};
|
|
204
|
+
for (const file of metadata.files) {
|
|
205
|
+
if (file.minModificationTimestamp) {
|
|
206
|
+
const minTs = new Date(file.minModificationTimestamp).getTime();
|
|
207
|
+
if (!isNaN(minTs)) timestamps.push(minTs);
|
|
208
|
+
}
|
|
209
|
+
if (file.maxModificationTimestamp) {
|
|
210
|
+
const maxTs = new Date(file.maxModificationTimestamp).getTime();
|
|
211
|
+
if (!isNaN(maxTs)) timestamps.push(maxTs);
|
|
212
|
+
}
|
|
213
|
+
if (file.StandardStatuses && typeof file.StandardStatuses === "object") {
|
|
214
|
+
for (const [status, count] of Object.entries(file.StandardStatuses)) {
|
|
215
|
+
statusCounts[status] = (statusCounts[status] || 0) + count;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const result = { ...metadata };
|
|
220
|
+
if (timestamps.length) {
|
|
221
|
+
result.minModificationTimestamp = new Date(Math.min(...timestamps)).toISOString();
|
|
222
|
+
result.maxModificationTimestamp = new Date(Math.max(...timestamps)).toISOString();
|
|
223
|
+
}
|
|
224
|
+
if (Object.keys(statusCounts).length > 0) {
|
|
225
|
+
result.StandardStatuses = statusCounts;
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/filedatabase/index.ts
|
|
231
|
+
var FileDatabaseError = class extends Error {
|
|
232
|
+
constructor(message) {
|
|
233
|
+
super(message);
|
|
234
|
+
this.name = "FileDatabaseError";
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
var FileDatabase = class {
|
|
238
|
+
basePath;
|
|
239
|
+
namespace;
|
|
240
|
+
tableName = null;
|
|
241
|
+
versioned;
|
|
242
|
+
maxVersions;
|
|
243
|
+
pageSize;
|
|
244
|
+
useMetadata;
|
|
245
|
+
freeSpaceThreshold;
|
|
246
|
+
logger;
|
|
247
|
+
// Current operation state
|
|
248
|
+
currentVersion = null;
|
|
249
|
+
currentVersionFolder = null;
|
|
250
|
+
currentFileNumber = 0;
|
|
251
|
+
currentRecord = 0;
|
|
252
|
+
hasReadFirstPage = false;
|
|
253
|
+
lastFileData = null;
|
|
254
|
+
metadata;
|
|
255
|
+
// Synopsis calculation functions
|
|
256
|
+
fileSynopsisFunction = null;
|
|
257
|
+
versionSynopsisFunction = null;
|
|
258
|
+
constructor(config) {
|
|
259
|
+
if (!config.basePath) {
|
|
260
|
+
throw new ParamError("[FileDatabase] basePath is required");
|
|
261
|
+
}
|
|
262
|
+
this.basePath = config.basePath;
|
|
263
|
+
this.namespace = config.namespace || "default";
|
|
264
|
+
this.tableName = config.tableName || null;
|
|
265
|
+
this.versioned = config.versioned ?? true;
|
|
266
|
+
this.maxVersions = config.maxVersions || 5;
|
|
267
|
+
this.pageSize = config.pageSize || 5e3;
|
|
268
|
+
this.useMetadata = config.useMetadata !== false;
|
|
269
|
+
this.freeSpaceThreshold = config.freeSpaceThreshold || 100 * 1024 * 1024;
|
|
270
|
+
this.logger = config.logger || console;
|
|
271
|
+
this.metadata = this.getDefaultMetadata();
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Get default metadata structure
|
|
275
|
+
*/
|
|
276
|
+
getDefaultMetadata() {
|
|
277
|
+
return {
|
|
278
|
+
version: this.currentVersion || null,
|
|
279
|
+
files: [],
|
|
280
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
281
|
+
modifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
282
|
+
totalRecords: 0,
|
|
283
|
+
synopsis: null,
|
|
284
|
+
dataType: null
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Get the destination path (basePath/namespace/tableName[/version])
|
|
289
|
+
*/
|
|
290
|
+
getDestinationPath(version) {
|
|
291
|
+
const errors = ["basePath", "namespace", "tableName"].filter((prop) => !this[prop]).map((prop) => `${prop} is not set`);
|
|
292
|
+
if (errors.length) {
|
|
293
|
+
throw new FileDatabaseError(`[FileDatabase] ${errors.join("; ")}`);
|
|
294
|
+
}
|
|
295
|
+
let parts = [this.basePath, this.namespace];
|
|
296
|
+
if (this.tableName) {
|
|
297
|
+
parts.push(...this.tableName.split("/"));
|
|
298
|
+
}
|
|
299
|
+
if (this.versioned && version) {
|
|
300
|
+
parts.push(version);
|
|
301
|
+
}
|
|
302
|
+
return import_path3.default.resolve(...parts);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Set current version and version folder
|
|
306
|
+
*/
|
|
307
|
+
async setCurrentVersion(version) {
|
|
308
|
+
this.currentVersion = version;
|
|
309
|
+
this.currentVersionFolder = await ensurePath(this.getDestinationPath(), version);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Create a new version folder with comprehensive timestamp logic
|
|
313
|
+
* Only works in versioned mode
|
|
314
|
+
*/
|
|
315
|
+
async makeNewVersion() {
|
|
316
|
+
if (!this.versioned) {
|
|
317
|
+
throw new FileDatabaseError("makeNewVersion() only works in versioned mode");
|
|
318
|
+
}
|
|
319
|
+
this.metadata = this.getDefaultMetadata();
|
|
320
|
+
const existingVersions = await this.getVersions();
|
|
321
|
+
let versionName;
|
|
322
|
+
if (existingVersions.length > 0) {
|
|
323
|
+
const maxTimestamp = existingVersions.reduce((max, version) => {
|
|
324
|
+
const versionDate = new Date(version.replace("Z", ""));
|
|
325
|
+
const maxDate2 = new Date(max.replace("Z", ""));
|
|
326
|
+
return versionDate > maxDate2 ? version : max;
|
|
327
|
+
});
|
|
328
|
+
const maxDate = new Date(maxTimestamp.replace("Z", ""));
|
|
329
|
+
const nextDate = new Date(maxDate.getTime() + 1e3);
|
|
330
|
+
versionName = nextDate.toISOString().split(".")[0] + "Z";
|
|
331
|
+
} else {
|
|
332
|
+
const now = /* @__PURE__ */ new Date();
|
|
333
|
+
versionName = now.toISOString().split(".")[0] + "Z";
|
|
334
|
+
}
|
|
335
|
+
await this.setCurrentVersion(versionName);
|
|
336
|
+
this.currentFileNumber = 0;
|
|
337
|
+
const versions = await this.getVersions();
|
|
338
|
+
while (versions.length > this.maxVersions) {
|
|
339
|
+
const versionToDelete = import_path3.default.resolve(this.getDestinationPath(), versions.shift());
|
|
340
|
+
this.logger.debug?.(`[FileDatabase] Deleting old version: ${versionToDelete}`);
|
|
341
|
+
await import_fs3.default.promises.rm(versionToDelete, { recursive: true, force: true });
|
|
342
|
+
}
|
|
343
|
+
return versionName;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Get list of all versions (sorted chronologically)
|
|
347
|
+
* Only works in versioned mode
|
|
348
|
+
*/
|
|
349
|
+
async getVersions() {
|
|
350
|
+
if (!this.versioned) {
|
|
351
|
+
return [];
|
|
352
|
+
}
|
|
353
|
+
const destPath = this.getDestinationPath();
|
|
354
|
+
try {
|
|
355
|
+
await ensurePath(destPath);
|
|
356
|
+
const items = await import_fs3.default.promises.readdir(destPath);
|
|
357
|
+
const versions = items.filter((item) => {
|
|
358
|
+
const itemPath = import_path3.default.join(destPath, item);
|
|
359
|
+
const stat = import_fs3.default.statSync(itemPath);
|
|
360
|
+
return stat.isDirectory() && isTimestampFolder(item);
|
|
361
|
+
});
|
|
362
|
+
return versions.sort();
|
|
363
|
+
} catch (error) {
|
|
364
|
+
return [];
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Get the latest version (most recent timestamp)
|
|
369
|
+
* Only works in versioned mode
|
|
370
|
+
* @returns Latest version string or null if no versions
|
|
371
|
+
*/
|
|
372
|
+
async getLatestVersion() {
|
|
373
|
+
if (!this.versioned) {
|
|
374
|
+
throw new FileDatabaseError("getLatestVersion() only works in versioned mode");
|
|
375
|
+
}
|
|
376
|
+
const versions = await this.getVersions();
|
|
377
|
+
if (versions.length === 0) {
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
return versions[versions.length - 1];
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Check if any data exists in this table
|
|
384
|
+
* Works for both versioned and non-versioned modes
|
|
385
|
+
* @returns true if data exists
|
|
386
|
+
*/
|
|
387
|
+
async hasData() {
|
|
388
|
+
const tablePath = this.getDestinationPath();
|
|
389
|
+
if (!import_fs3.default.existsSync(tablePath)) {
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
if (this.versioned) {
|
|
393
|
+
const versions = await this.getVersions();
|
|
394
|
+
return versions.length > 0;
|
|
395
|
+
} else {
|
|
396
|
+
const items = await import_fs3.default.promises.readdir(tablePath);
|
|
397
|
+
return items.some(
|
|
398
|
+
(item) => item === "metadata.json" || item.match(/^\d{6}\.(json|txt|xml)$/) || item.endsWith(".json")
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Auto-detect the data format in this table
|
|
404
|
+
* Used when reading existing data
|
|
405
|
+
* @returns Format detection result
|
|
406
|
+
*/
|
|
407
|
+
async detectDataFormat() {
|
|
408
|
+
const tablePath = this.getDestinationPath();
|
|
409
|
+
if (!import_fs3.default.existsSync(tablePath)) {
|
|
410
|
+
return { versioned: false, hasMetadata: false, dataType: null };
|
|
411
|
+
}
|
|
412
|
+
const items = await import_fs3.default.promises.readdir(tablePath);
|
|
413
|
+
if (items.includes("metadata.json")) {
|
|
414
|
+
const metadata = JSON.parse(
|
|
415
|
+
await import_fs3.default.promises.readFile(import_path3.default.join(tablePath, "metadata.json"), "utf8")
|
|
416
|
+
);
|
|
417
|
+
return {
|
|
418
|
+
versioned: false,
|
|
419
|
+
hasMetadata: true,
|
|
420
|
+
dataType: metadata.dataType || null
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
const versionFolders = items.filter((item) => {
|
|
424
|
+
const itemPath = import_path3.default.join(tablePath, item);
|
|
425
|
+
const stat = import_fs3.default.statSync(itemPath);
|
|
426
|
+
return stat.isDirectory() && isTimestampFolder(item);
|
|
427
|
+
});
|
|
428
|
+
if (versionFolders.length > 0) {
|
|
429
|
+
const latestVersion = versionFolders.sort().pop();
|
|
430
|
+
const versionMetadataPath = import_path3.default.join(tablePath, latestVersion, "metadata.json");
|
|
431
|
+
return {
|
|
432
|
+
versioned: true,
|
|
433
|
+
hasMetadata: import_fs3.default.existsSync(versionMetadataPath),
|
|
434
|
+
dataType: null
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
const dataFiles = items.filter((f) => f.match(/^\d{6}\.(json|txt|xml)$/));
|
|
438
|
+
if (dataFiles.length > 0) {
|
|
439
|
+
return {
|
|
440
|
+
versioned: false,
|
|
441
|
+
hasMetadata: false,
|
|
442
|
+
dataType: null
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
return { versioned: false, hasMetadata: false, dataType: null };
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Load metadata from JSON file
|
|
449
|
+
*/
|
|
450
|
+
async loadMetadataJson(version) {
|
|
451
|
+
const metadataFile = import_path3.default.join(this.getDestinationPath(), version, "metadata.json");
|
|
452
|
+
if (import_fs3.default.existsSync(metadataFile)) {
|
|
453
|
+
try {
|
|
454
|
+
const rawData = await import_fs3.default.promises.readFile(metadataFile, "utf8");
|
|
455
|
+
return JSON.parse(rawData);
|
|
456
|
+
} catch (e) {
|
|
457
|
+
throw new FileDatabaseError(`Failed to read metadata for version "${version}": ${e.message}`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Build metadata by scanning files in a version folder (backward compatibility)
|
|
464
|
+
* Reads all files to get accurate counts - used when synopsis calculation is needed
|
|
465
|
+
*/
|
|
466
|
+
async figureMetadataFromVersionFiles(version) {
|
|
467
|
+
const versionPath = import_path3.default.join(this.getDestinationPath(), version);
|
|
468
|
+
if (!import_fs3.default.existsSync(versionPath)) {
|
|
469
|
+
return this.getDefaultMetadata();
|
|
470
|
+
}
|
|
471
|
+
const files = (await import_fs3.default.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
|
|
472
|
+
const metadata = this.getDefaultMetadata();
|
|
473
|
+
metadata.version = version;
|
|
474
|
+
metadata.files = [];
|
|
475
|
+
let totalRecords = 0;
|
|
476
|
+
let detectedDataType = null;
|
|
477
|
+
for (let i = 0; i < files.length; i++) {
|
|
478
|
+
const fileName = files[i];
|
|
479
|
+
const filePath = import_path3.default.join(versionPath, fileName);
|
|
480
|
+
try {
|
|
481
|
+
const rawData = await import_fs3.default.promises.readFile(filePath, "utf8");
|
|
482
|
+
const extension = import_path3.default.extname(fileName).toLowerCase();
|
|
483
|
+
let dataType = "text";
|
|
484
|
+
if (extension === ".json") {
|
|
485
|
+
dataType = "json-array";
|
|
486
|
+
} else if (extension === ".xml") {
|
|
487
|
+
dataType = "xml";
|
|
488
|
+
}
|
|
489
|
+
const fileData = deserializeData(rawData, dataType);
|
|
490
|
+
const recordsCount = Array.isArray(fileData) ? fileData.length : 1;
|
|
491
|
+
if (detectedDataType === null) {
|
|
492
|
+
detectedDataType = detectDataType(fileData);
|
|
493
|
+
}
|
|
494
|
+
const fileInfo = {
|
|
495
|
+
number: i + 1,
|
|
496
|
+
recordsCount,
|
|
497
|
+
fileName
|
|
498
|
+
};
|
|
499
|
+
metadata.files.push(fileInfo);
|
|
500
|
+
totalRecords += recordsCount;
|
|
501
|
+
} catch (error) {
|
|
502
|
+
this.logger.error?.(`[FileDatabase] Failed to read file ${fileName}: ${error.message}`);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
metadata.totalRecords = totalRecords;
|
|
506
|
+
metadata.dataType = detectedDataType;
|
|
507
|
+
return metadata;
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Build metadata optimized - only reads first and last files
|
|
511
|
+
* Assumes all middle files have the same record count as the first file
|
|
512
|
+
* Much faster for large datasets with many files
|
|
513
|
+
*/
|
|
514
|
+
async buildMetadataOptimized(version) {
|
|
515
|
+
const versionPath = import_path3.default.join(this.getDestinationPath(), version);
|
|
516
|
+
if (!import_fs3.default.existsSync(versionPath)) {
|
|
517
|
+
return this.getDefaultMetadata();
|
|
518
|
+
}
|
|
519
|
+
const files = (await import_fs3.default.promises.readdir(versionPath)).filter((file) => file !== "metadata.json" && !file.startsWith(".")).sort();
|
|
520
|
+
if (files.length === 0) {
|
|
521
|
+
return this.getDefaultMetadata();
|
|
522
|
+
}
|
|
523
|
+
const metadata = this.getDefaultMetadata();
|
|
524
|
+
metadata.version = version;
|
|
525
|
+
metadata.files = files.map((fileName, index) => ({
|
|
526
|
+
number: index + 1,
|
|
527
|
+
recordsCount: 0,
|
|
528
|
+
fileName
|
|
529
|
+
}));
|
|
530
|
+
const firstFile = metadata.files[0];
|
|
531
|
+
const firstFilePath = import_path3.default.join(versionPath, firstFile.fileName);
|
|
532
|
+
const firstFileRaw = await import_fs3.default.promises.readFile(firstFilePath, "utf8");
|
|
533
|
+
let firstFileData;
|
|
534
|
+
try {
|
|
535
|
+
firstFileData = JSON.parse(firstFileRaw);
|
|
536
|
+
} catch (e) {
|
|
537
|
+
firstFileData = firstFileRaw;
|
|
538
|
+
}
|
|
539
|
+
metadata.dataType = detectDataType(firstFileData);
|
|
540
|
+
if (metadata.dataType === "json-array") {
|
|
541
|
+
const firstFileCount = Array.isArray(firstFileData) ? firstFileData.length : 1;
|
|
542
|
+
firstFile.recordsCount = firstFileCount;
|
|
543
|
+
for (let i = 1; i < metadata.files.length - 1; i++) {
|
|
544
|
+
metadata.files[i].recordsCount = firstFileCount;
|
|
545
|
+
}
|
|
546
|
+
if (files.length > 1) {
|
|
547
|
+
const lastFile = metadata.files[metadata.files.length - 1];
|
|
548
|
+
const lastFilePath = import_path3.default.join(versionPath, lastFile.fileName);
|
|
549
|
+
const lastFileRaw = await import_fs3.default.promises.readFile(lastFilePath, "utf8");
|
|
550
|
+
const lastFileData = deserializeData(lastFileRaw, metadata.dataType);
|
|
551
|
+
lastFile.recordsCount = Array.isArray(lastFileData) ? lastFileData.length : 1;
|
|
552
|
+
}
|
|
553
|
+
metadata.totalRecords = metadata.files.reduce((sum, file) => sum + file.recordsCount, 0);
|
|
554
|
+
} else {
|
|
555
|
+
metadata.files.forEach((file) => {
|
|
556
|
+
file.recordsCount = 1;
|
|
557
|
+
});
|
|
558
|
+
metadata.totalRecords = files.length;
|
|
559
|
+
}
|
|
560
|
+
return metadata;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Figure out metadata - tries JSON first, then builds from files
|
|
564
|
+
* Uses optimized building when no synopsis calculation is needed
|
|
565
|
+
*/
|
|
566
|
+
async figureMetadata(version, useOptimized = true) {
|
|
567
|
+
if (this.useMetadata) {
|
|
568
|
+
const metadata = await this.loadMetadataJson(version);
|
|
569
|
+
if (metadata) {
|
|
570
|
+
return metadata;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (useOptimized && !this.fileSynopsisFunction && !this.versionSynopsisFunction) {
|
|
574
|
+
return await this.buildMetadataOptimized(version);
|
|
575
|
+
}
|
|
576
|
+
return await this.figureMetadataFromVersionFiles(version);
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Load version metadata (main entry point for loading)
|
|
580
|
+
*/
|
|
581
|
+
async loadVersionMetadata(version) {
|
|
582
|
+
const metadata = await this.figureMetadata(version);
|
|
583
|
+
this.metadata = metadata;
|
|
584
|
+
return metadata;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Save version metadata to file
|
|
588
|
+
*/
|
|
589
|
+
async saveVersionMetadata(metadata) {
|
|
590
|
+
if (!this.useMetadata) {
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
const metadataToSave = metadata || this.metadata;
|
|
594
|
+
let metadataFile;
|
|
595
|
+
if (this.versioned) {
|
|
596
|
+
if (!this.currentVersion) {
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
metadataFile = import_path3.default.join(this.getDestinationPath(), this.currentVersion, "metadata.json");
|
|
600
|
+
} else {
|
|
601
|
+
metadataFile = import_path3.default.join(this.getDestinationPath(), "metadata.json");
|
|
602
|
+
}
|
|
603
|
+
await import_fs3.default.promises.writeFile(metadataFile, JSON.stringify(metadataToSave, null, 4), "utf8");
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Create a new file entry in metadata
|
|
607
|
+
*/
|
|
608
|
+
makeNewFile() {
|
|
609
|
+
this.currentFileNumber = (this.currentFileNumber || 0) + 1;
|
|
610
|
+
const dataType = this.metadata.dataType || "json-array";
|
|
611
|
+
const fileEntry = {
|
|
612
|
+
number: this.currentFileNumber,
|
|
613
|
+
recordsCount: 0,
|
|
614
|
+
fileName: `${this.currentFileNumber.toString().padStart(6, "0")}.${getFileExtension(dataType)}`
|
|
615
|
+
};
|
|
616
|
+
this.metadata.files.push(fileEntry);
|
|
617
|
+
this.lastFileData = null;
|
|
618
|
+
this.logger.debug?.(`[FileDatabase] Created new file: ${fileEntry.fileName}, fileNumber: ${this.currentFileNumber}`);
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Figure out what data to write and which file to use (for pagination)
|
|
622
|
+
*/
|
|
623
|
+
figureOutDataAndFileToWrite(data) {
|
|
624
|
+
let dataToWrite;
|
|
625
|
+
let dataLeftOver;
|
|
626
|
+
const lastFile = this.metadata.files[this.metadata.files.length - 1];
|
|
627
|
+
const lastFileRecordsCount = lastFile.recordsCount;
|
|
628
|
+
if (Array.isArray(data)) {
|
|
629
|
+
if (lastFileRecordsCount < this.pageSize) {
|
|
630
|
+
dataToWrite = [...this.lastFileData || [], ...data.slice(0, this.pageSize - lastFileRecordsCount)];
|
|
631
|
+
dataLeftOver = data.slice(this.pageSize - lastFileRecordsCount);
|
|
632
|
+
} else {
|
|
633
|
+
this.makeNewFile();
|
|
634
|
+
dataToWrite = data.slice(0, this.pageSize);
|
|
635
|
+
dataLeftOver = data.slice(this.pageSize);
|
|
636
|
+
}
|
|
637
|
+
this.lastFileData = dataToWrite;
|
|
638
|
+
} else {
|
|
639
|
+
dataToWrite = data;
|
|
640
|
+
dataLeftOver = null;
|
|
641
|
+
}
|
|
642
|
+
const fileName = this.metadata.files[this.metadata.files.length - 1].fileName;
|
|
643
|
+
this.logger.debug?.(
|
|
644
|
+
`[FileDatabase] figureOutDataAndFileToWrite: filename=${fileName}, dataToWrite.length=${Array.isArray(dataToWrite) ? dataToWrite.length : "N/A"}, lastFileRecordsCount=${lastFileRecordsCount}`
|
|
645
|
+
);
|
|
646
|
+
return { dataToWrite, dataLeftOver, fileName };
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Calculate file-level synopsis if function is set
|
|
650
|
+
*/
|
|
651
|
+
calculateFileSynopsis(data, fileIndex = this.metadata.files.length - 1) {
|
|
652
|
+
if (!this.fileSynopsisFunction) {
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const fileInfo = this.metadata.files[fileIndex];
|
|
656
|
+
const enhancedFileInfo = this.fileSynopsisFunction(fileInfo, data);
|
|
657
|
+
this.metadata.files[fileIndex] = enhancedFileInfo;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Calculate version-level synopsis if function is set
|
|
661
|
+
*/
|
|
662
|
+
calculateVersionSynopsis() {
|
|
663
|
+
if (!this.versionSynopsisFunction) {
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
const enhancedMetadata = this.versionSynopsisFunction(this.metadata);
|
|
667
|
+
this.metadata = enhancedMetadata;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Update metadata after writing data
|
|
671
|
+
*/
|
|
672
|
+
updateMetadata(dataToWrite, fileName) {
|
|
673
|
+
let currentFile;
|
|
674
|
+
if (fileName) {
|
|
675
|
+
const foundFile = this.metadata.files.find((file) => file.fileName === fileName);
|
|
676
|
+
if (!foundFile) {
|
|
677
|
+
this.logger.warn?.(`[FileDatabase] File ${fileName} not found in metadata, using last file`);
|
|
678
|
+
currentFile = this.metadata.files[this.metadata.files.length - 1];
|
|
679
|
+
} else {
|
|
680
|
+
currentFile = foundFile;
|
|
681
|
+
}
|
|
682
|
+
} else {
|
|
683
|
+
currentFile = this.metadata.files[this.metadata.files.length - 1];
|
|
684
|
+
}
|
|
685
|
+
const recordsCount = Array.isArray(dataToWrite) ? dataToWrite.length : 1;
|
|
686
|
+
currentFile.recordsCount = recordsCount;
|
|
687
|
+
const fileIndex = this.metadata.files.indexOf(currentFile);
|
|
688
|
+
if (fileIndex !== -1) {
|
|
689
|
+
this.calculateFileSynopsis(dataToWrite, fileIndex);
|
|
690
|
+
}
|
|
691
|
+
this.metadata.version = this.currentVersion;
|
|
692
|
+
this.metadata.modifiedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
693
|
+
this.metadata.dataType = detectDataType(dataToWrite);
|
|
694
|
+
this.metadata.totalRecords = this.metadata.files.reduce((sum, file) => sum + (file.recordsCount || 0), 0);
|
|
695
|
+
this.logger.debug?.(
|
|
696
|
+
`[FileDatabase] Updated metadata for file ${currentFile.fileName}: recordsCount=${recordsCount}, totalRecords=${this.metadata.totalRecords}`
|
|
697
|
+
);
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Safe write with disk space check
|
|
701
|
+
*/
|
|
702
|
+
async safeWrite(filePath, data) {
|
|
703
|
+
const serializedData = serializeData(data);
|
|
704
|
+
const dir = import_path3.default.dirname(filePath);
|
|
705
|
+
const requiredBytes = Buffer.byteLength(serializedData, "utf8");
|
|
706
|
+
const freeBytes = getFreeDiskSpace(dir);
|
|
707
|
+
if (freeBytes !== null) {
|
|
708
|
+
if (freeBytes < requiredBytes) {
|
|
709
|
+
throw new FileDatabaseError(
|
|
710
|
+
`Not enough disk space. Required: ${bytesToHumanReadable(requiredBytes)}, Free: ${bytesToHumanReadable(freeBytes)}`
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
if (freeBytes < this.freeSpaceThreshold) {
|
|
714
|
+
this.logger.warn?.(`Low disk space warning: only ${bytesToHumanReadable(freeBytes)} left`);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
try {
|
|
718
|
+
await import_fs3.default.promises.writeFile(filePath, serializedData, "utf8");
|
|
719
|
+
this.logger.debug?.(`[FileDatabase] Wrote ${bytesToHumanReadable(requiredBytes)} to ${filePath}`);
|
|
720
|
+
} catch (error) {
|
|
721
|
+
throw new FileDatabaseError(`Failed to write file ${filePath}: ${error.message}`);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Prepare the instance for read or write operations
|
|
726
|
+
* This discovers state and sets up internal members based on mode and current data
|
|
727
|
+
*/
|
|
728
|
+
async prepare({ write, read, version }) {
|
|
729
|
+
if (write) {
|
|
730
|
+
if (this.versioned) {
|
|
731
|
+
if (this.currentVersion === null) {
|
|
732
|
+
await this.makeNewVersion();
|
|
733
|
+
this.metadata = this.getDefaultMetadata();
|
|
734
|
+
this.metadata.version = this.currentVersion;
|
|
735
|
+
this.makeNewFile();
|
|
736
|
+
} else {
|
|
737
|
+
if (!this.metadata.files.length) {
|
|
738
|
+
this.metadata = await this.figureMetadata(this.currentVersion);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
} else {
|
|
742
|
+
await ensurePath(this.getDestinationPath());
|
|
743
|
+
if (this.useMetadata === true) {
|
|
744
|
+
const metadataPath = import_path3.default.join(this.getDestinationPath(), "metadata.json");
|
|
745
|
+
if (import_fs3.default.existsSync(metadataPath)) {
|
|
746
|
+
try {
|
|
747
|
+
const rawData = await import_fs3.default.promises.readFile(metadataPath, "utf8");
|
|
748
|
+
this.metadata = JSON.parse(rawData);
|
|
749
|
+
} catch (e) {
|
|
750
|
+
this.metadata = this.getDefaultMetadata();
|
|
751
|
+
}
|
|
752
|
+
} else {
|
|
753
|
+
this.metadata = this.getDefaultMetadata();
|
|
754
|
+
this.makeNewFile();
|
|
755
|
+
}
|
|
756
|
+
} else {
|
|
757
|
+
this.metadata = this.getDefaultMetadata();
|
|
758
|
+
this.makeNewFile();
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
} else if (read) {
|
|
762
|
+
if (this.versioned) {
|
|
763
|
+
const versions = await this.getVersions();
|
|
764
|
+
if (versions.length === 0) {
|
|
765
|
+
throw new FileDatabaseError("[FileDatabase] No versions found, cannot read");
|
|
766
|
+
}
|
|
767
|
+
if (version) {
|
|
768
|
+
if (!versions.includes(version)) {
|
|
769
|
+
throw new FileDatabaseError(`[FileDatabase] Version "${version}" not found`);
|
|
770
|
+
}
|
|
771
|
+
await this.setCurrentVersion(version);
|
|
772
|
+
} else {
|
|
773
|
+
await this.setCurrentVersion(versions[versions.length - 1]);
|
|
774
|
+
}
|
|
775
|
+
if (!this.metadata.files.length) {
|
|
776
|
+
this.metadata = await this.figureMetadata(this.currentVersion);
|
|
777
|
+
}
|
|
778
|
+
} else {
|
|
779
|
+
this.currentVersion = null;
|
|
780
|
+
if (this.useMetadata === void 0) {
|
|
781
|
+
const format = await this.detectDataFormat();
|
|
782
|
+
this.useMetadata = format.hasMetadata;
|
|
783
|
+
}
|
|
784
|
+
if (this.useMetadata) {
|
|
785
|
+
const metadataPath = import_path3.default.join(this.getDestinationPath(), "metadata.json");
|
|
786
|
+
if (import_fs3.default.existsSync(metadataPath)) {
|
|
787
|
+
try {
|
|
788
|
+
const rawData = await import_fs3.default.promises.readFile(metadataPath, "utf8");
|
|
789
|
+
this.metadata = JSON.parse(rawData);
|
|
790
|
+
} catch (e) {
|
|
791
|
+
throw new FileDatabaseError(`Failed to read metadata: ${e.message}`);
|
|
792
|
+
}
|
|
793
|
+
} else {
|
|
794
|
+
throw new FileDatabaseError("[FileDatabase] No metadata found in non-versioned mode");
|
|
795
|
+
}
|
|
796
|
+
} else {
|
|
797
|
+
this.metadata = await this.figureMetadataFromVersionFiles("");
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Write data to the file database
|
|
804
|
+
*/
|
|
805
|
+
async write(data, options = {}) {
|
|
806
|
+
if (options.forceNewVersion && !this.versioned) {
|
|
807
|
+
throw new FileDatabaseError("Cannot use forceNewVersion in non-versioned mode");
|
|
808
|
+
}
|
|
809
|
+
await this.prepare({ write: true });
|
|
810
|
+
if (options.forceNewVersion) {
|
|
811
|
+
await this.makeNewVersion();
|
|
812
|
+
this.metadata = this.getDefaultMetadata();
|
|
813
|
+
this.metadata.version = this.currentVersion;
|
|
814
|
+
this.makeNewFile();
|
|
815
|
+
}
|
|
816
|
+
let { dataToWrite, dataLeftOver, fileName } = this.figureOutDataAndFileToWrite(data);
|
|
817
|
+
const destPath = this.getDestinationPath(this.currentVersion || void 0);
|
|
818
|
+
await this.safeWrite(import_path3.default.join(destPath, fileName), dataToWrite);
|
|
819
|
+
this.updateMetadata(dataToWrite, fileName);
|
|
820
|
+
while (dataLeftOver && dataLeftOver.length > 0) {
|
|
821
|
+
const writeContext = this.figureOutDataAndFileToWrite(dataLeftOver);
|
|
822
|
+
await this.safeWrite(import_path3.default.join(destPath, writeContext.fileName), writeContext.dataToWrite);
|
|
823
|
+
this.updateMetadata(writeContext.dataToWrite, writeContext.fileName);
|
|
824
|
+
dataLeftOver = writeContext.dataLeftOver;
|
|
825
|
+
}
|
|
826
|
+
this.calculateVersionSynopsis();
|
|
827
|
+
if (this.useMetadata) {
|
|
828
|
+
await this.saveVersionMetadata(this.metadata);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Read data from the file database
|
|
833
|
+
*/
|
|
834
|
+
async read(options = {}) {
|
|
835
|
+
const { version, nextPage = false, pageSize } = options;
|
|
836
|
+
await this.prepare({ read: true, version });
|
|
837
|
+
const isNonPaginatedData = this.metadata.dataType === "text" || this.metadata.dataType === "xml" || this.metadata.dataType === "json-object";
|
|
838
|
+
if (isNonPaginatedData) {
|
|
839
|
+
const file = this.metadata.files[0];
|
|
840
|
+
const filePath = import_path3.default.join(this.getDestinationPath(this.currentVersion || void 0), file.fileName);
|
|
841
|
+
try {
|
|
842
|
+
const rawData = await import_fs3.default.promises.readFile(filePath, "utf8");
|
|
843
|
+
return deserializeData(rawData, this.metadata.dataType);
|
|
844
|
+
} catch (error) {
|
|
845
|
+
throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
let effectivePageSize;
|
|
849
|
+
if (nextPage && this.hasReadFirstPage) {
|
|
850
|
+
effectivePageSize = pageSize || this.pageSize;
|
|
851
|
+
this.currentRecord += effectivePageSize;
|
|
852
|
+
} else if (!nextPage) {
|
|
853
|
+
effectivePageSize = pageSize !== void 0 ? pageSize : this.metadata.totalRecords;
|
|
854
|
+
this.currentRecord = 0;
|
|
855
|
+
} else {
|
|
856
|
+
effectivePageSize = pageSize || this.pageSize;
|
|
857
|
+
}
|
|
858
|
+
if (this.currentRecord >= this.metadata.totalRecords) {
|
|
859
|
+
return [];
|
|
860
|
+
}
|
|
861
|
+
const result = [];
|
|
862
|
+
let recordsRead = 0;
|
|
863
|
+
let currentFileIndex = 0;
|
|
864
|
+
let currentFileOffset = 0;
|
|
865
|
+
let totalRecords = 0;
|
|
866
|
+
for (let i = 0; i < this.metadata.files.length; i++) {
|
|
867
|
+
const file = this.metadata.files[i];
|
|
868
|
+
if (this.currentRecord < totalRecords + file.recordsCount) {
|
|
869
|
+
currentFileIndex = i;
|
|
870
|
+
currentFileOffset = totalRecords;
|
|
871
|
+
break;
|
|
872
|
+
}
|
|
873
|
+
totalRecords += file.recordsCount;
|
|
874
|
+
}
|
|
875
|
+
let cumulativeRecords = currentFileOffset;
|
|
876
|
+
for (let i = currentFileIndex; i < this.metadata.files.length && recordsRead < effectivePageSize; i++) {
|
|
877
|
+
const file = this.metadata.files[i];
|
|
878
|
+
const filePath = import_path3.default.join(this.getDestinationPath(this.currentVersion || void 0), file.fileName);
|
|
879
|
+
try {
|
|
880
|
+
const rawData = await import_fs3.default.promises.readFile(filePath, "utf8");
|
|
881
|
+
const fileData = deserializeData(rawData, this.metadata.dataType);
|
|
882
|
+
let startIndex = 0;
|
|
883
|
+
if (i === currentFileIndex) {
|
|
884
|
+
startIndex = this.currentRecord - cumulativeRecords;
|
|
885
|
+
}
|
|
886
|
+
const endIndex = Math.min(startIndex + (effectivePageSize - recordsRead), fileData.length);
|
|
887
|
+
const recordsFromThisFile = fileData.slice(startIndex, endIndex);
|
|
888
|
+
result.push(...recordsFromThisFile);
|
|
889
|
+
recordsRead += recordsFromThisFile.length;
|
|
890
|
+
cumulativeRecords += file.recordsCount;
|
|
891
|
+
} catch (error) {
|
|
892
|
+
throw new FileDatabaseError(`Failed to read file ${file.fileName}: ${error.message}`);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
if (result.length > 0) {
|
|
896
|
+
if (nextPage || pageSize !== void 0 && pageSize < this.metadata.totalRecords) {
|
|
897
|
+
this.hasReadFirstPage = true;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
return result;
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Set the starting record for pagination (1-based index)
|
|
904
|
+
*/
|
|
905
|
+
setStartRecord(startRecord) {
|
|
906
|
+
this.currentRecord = startRecord - 1;
|
|
907
|
+
this.hasReadFirstPage = false;
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Reset read pagination state
|
|
911
|
+
*/
|
|
912
|
+
resetPagination() {
|
|
913
|
+
this.currentRecord = 0;
|
|
914
|
+
this.hasReadFirstPage = false;
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Set file-level synopsis calculation function
|
|
918
|
+
*/
|
|
919
|
+
setFileSynopsisFunction(fn) {
|
|
920
|
+
this.fileSynopsisFunction = fn;
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* Set version-level synopsis calculation function
|
|
924
|
+
*/
|
|
925
|
+
setVersionSynopsisFunction(fn) {
|
|
926
|
+
this.versionSynopsisFunction = fn;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Get current version name
|
|
930
|
+
*/
|
|
931
|
+
getCurrentVersion() {
|
|
932
|
+
return this.currentVersion;
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Get current metadata
|
|
936
|
+
*/
|
|
937
|
+
getMetadata() {
|
|
938
|
+
return { ...this.metadata };
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
942
|
+
0 && (module.exports = {
|
|
943
|
+
FileDatabase,
|
|
944
|
+
FileDatabaseError,
|
|
945
|
+
defaultFileSynopsisFunction,
|
|
946
|
+
defaultVersionSynopsisFunction
|
|
947
|
+
});
|
|
948
|
+
//# sourceMappingURL=filedatabase.cjs.map
|