inibase 1.0.0-rc.8 → 1.0.0-rc.81

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 ADDED
@@ -0,0 +1,1322 @@
1
+ import "dotenv/config";
2
+ import { randomBytes, scryptSync } from "node:crypto";
3
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
4
+ import { mkdir, readFile, readdir, rename, unlink, writeFile, } from "node:fs/promises";
5
+ import { join, parse } from "node:path";
6
+ import { inspect } from "node:util";
7
+ import Inison from "inison";
8
+ import * as File from "./file.js";
9
+ import * as Utils from "./utils.js";
10
+ import * as UtilsServer from "./utils.server.js";
11
+ export default class Inibase {
12
+ pageInfo;
13
+ salt;
14
+ databasePath;
15
+ tables;
16
+ fileExtension = ".txt";
17
+ checkIFunique;
18
+ totalItems;
19
+ constructor(database, mainFolder = ".") {
20
+ this.databasePath = join(mainFolder, database);
21
+ this.tables = {};
22
+ this.totalItems = {};
23
+ this.pageInfo = {};
24
+ this.checkIFunique = {};
25
+ if (!process.env.INIBASE_SECRET) {
26
+ if (existsSync(".env") &&
27
+ readFileSync(".env").includes("INIBASE_SECRET="))
28
+ throw this.throwError("NO_ENV");
29
+ this.salt = scryptSync(randomBytes(16), randomBytes(16), 32);
30
+ appendFileSync(".env", `\nINIBASE_SECRET=${this.salt.toString("hex")}\n`);
31
+ }
32
+ else
33
+ this.salt = Buffer.from(process.env.INIBASE_SECRET, "hex");
34
+ }
35
+ throwError(code, variable, language = "en") {
36
+ const errorMessages = {
37
+ en: {
38
+ FIELD_UNIQUE: "Field {variable} should be unique, got {variable} instead",
39
+ FIELD_REQUIRED: "Field {variable} is required",
40
+ TABLE_EXISTS: "Table {variable} already exists",
41
+ TABLE_NOT_EXISTS: "Table {variable} doesn't exist",
42
+ NO_SCHEMA: "Table {variable} does't have a schema",
43
+ NO_ITEMS: "Table {variable} is empty",
44
+ NO_RESULTS: "No results found for table {variable}",
45
+ INVALID_ID: "The given ID(s) is/are not valid(s)",
46
+ INVALID_TYPE: "Expect {variable} to be {variable}, got {variable} instead",
47
+ INVALID_PARAMETERS: "The given parameters are not valid",
48
+ NO_ENV: Number(process.versions.node.split(".").reduce((a, b) => a + b)) >= 26
49
+ ? "please run with '--env-file=.env'"
50
+ : "please use dotenv",
51
+ },
52
+ // Add more languages and error messages as needed
53
+ };
54
+ const errorMessage = errorMessages[language][code];
55
+ if (!errorMessage)
56
+ return new Error("ERR");
57
+ return new Error(variable
58
+ ? Array.isArray(variable)
59
+ ? errorMessage.replace(/\{variable\}/g, () => variable.shift()?.toString() ?? "")
60
+ : errorMessage.replaceAll("{variable}", `'${variable.toString()}'`)
61
+ : errorMessage.replaceAll("{variable}", ""));
62
+ }
63
+ getFileExtension = (tableName) => {
64
+ let mainExtension = this.fileExtension;
65
+ // TODO: ADD ENCRYPTION
66
+ // if(this.tables[tableName].config.encryption)
67
+ // mainExtension += ".enc"
68
+ if (this.tables[tableName].config.compression)
69
+ mainExtension += ".gz";
70
+ return mainExtension;
71
+ };
72
+ _schemaToIdsPath = (tableName, schema, prefix = "") => {
73
+ const RETURN = {};
74
+ for (const field of schema)
75
+ if ((field.type === "array" || field.type === "object") &&
76
+ field.children &&
77
+ Utils.isArrayOfObjects(field.children)) {
78
+ Utils.deepMerge(RETURN, this._schemaToIdsPath(tableName, field.children, `${(prefix ?? "") + field.key}.`));
79
+ }
80
+ else if (field.id)
81
+ RETURN[field.id] = `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`;
82
+ return RETURN;
83
+ };
84
+ /**
85
+ * Create a new table inside database, with predefined schema and config
86
+ *
87
+ * @param {string} tableName
88
+ * @param {Schema} [schema]
89
+ * @param {Config} [config]
90
+ */
91
+ async createTable(tableName, schema, config) {
92
+ const tablePath = join(this.databasePath, tableName);
93
+ if (await File.isExists(tablePath))
94
+ throw this.throwError("TABLE_EXISTS", tableName);
95
+ await mkdir(join(tablePath, ".tmp"), { recursive: true });
96
+ await mkdir(join(tablePath, ".cache"));
97
+ // if config not set => load default global env config
98
+ if (!config)
99
+ config = {
100
+ compression: process.env.INIBASE_COMPRESSION == "true",
101
+ cache: process.env.INIBASE_CACHE === "true",
102
+ prepend: process.env.INIBASE_PREPEND === "true",
103
+ };
104
+ if (config) {
105
+ if (config.compression)
106
+ await writeFile(join(tablePath, ".compression.config"), "");
107
+ if (config.cache)
108
+ await writeFile(join(tablePath, ".cache.config"), "");
109
+ if (config.prepend)
110
+ await writeFile(join(tablePath, ".prepend.config"), "");
111
+ }
112
+ if (schema)
113
+ await writeFile(join(tablePath, "schema.json"), JSON.stringify(UtilsServer.addIdToSchema(schema, 0, this.salt), null, 2));
114
+ }
115
+ /**
116
+ * Update table schema or config
117
+ *
118
+ * @param {string} tableName
119
+ * @param {Schema} [schema]
120
+ * @param {Config} [config]
121
+ */
122
+ async updateTable(tableName, schema, config) {
123
+ const table = await this.getTable(tableName), tablePath = join(this.databasePath, tableName);
124
+ if (config) {
125
+ if (config.compression !== undefined &&
126
+ config.compression !== table.config.compression) {
127
+ await UtilsServer.execFile("find", [
128
+ tableName,
129
+ "-type",
130
+ "f",
131
+ "-name",
132
+ `*${this.fileExtension}${config.compression ? "" : ".gz"}`,
133
+ "-exec",
134
+ config.compression ? "gzip" : "gunzip",
135
+ "-f",
136
+ "{}",
137
+ "+",
138
+ ], { cwd: this.databasePath });
139
+ if (config.compression)
140
+ await writeFile(join(tablePath, ".compression.config"), "");
141
+ else
142
+ await unlink(join(tablePath, ".compression.config"));
143
+ }
144
+ if (config.cache !== undefined && config.cache !== table.config.cache) {
145
+ if (config.cache)
146
+ await writeFile(join(tablePath, ".cache.config"), "");
147
+ else
148
+ await unlink(join(tablePath, ".cache.config"));
149
+ }
150
+ if (config.prepend !== undefined &&
151
+ config.prepend !== table.config.prepend) {
152
+ await UtilsServer.execFile("find", [
153
+ tableName,
154
+ "-type",
155
+ "f",
156
+ "-name",
157
+ `*${this.fileExtension}${config.compression ? ".gz" : ""}`,
158
+ "-exec",
159
+ "sh",
160
+ "-c",
161
+ `for file; do ${config.compression
162
+ ? 'zcat "$file" | tac | gzip > "$file.reversed" && mv "$file.reversed" "$file"'
163
+ : 'tac "$file" > "$file.reversed" && mv "$file.reversed" "$file"'}; done`,
164
+ "_",
165
+ "{}",
166
+ "+",
167
+ ], { cwd: this.databasePath });
168
+ if (config.prepend)
169
+ await writeFile(join(tablePath, ".prepend.config"), "");
170
+ else
171
+ await unlink(join(tablePath, ".prepend.config"));
172
+ }
173
+ }
174
+ if (schema) {
175
+ // remove id from schema
176
+ schema = schema.filter(({ key }) => !["id", "createdAt", "updatedAt"].includes(key));
177
+ if (await File.isExists(join(tablePath, "schema.json"))) {
178
+ // update columns files names based on field id
179
+ schema = UtilsServer.addIdToSchema(schema, table.schema?.length
180
+ ? UtilsServer.findLastIdNumber(table.schema, this.salt)
181
+ : 0, this.salt);
182
+ if (table.schema?.length) {
183
+ const replaceOldPathes = Utils.findChangedProperties(this._schemaToIdsPath(tableName, table.schema), this._schemaToIdsPath(tableName, schema));
184
+ if (replaceOldPathes)
185
+ await Promise.all(Object.entries(replaceOldPathes).map(async ([oldPath, newPath]) => {
186
+ if (await File.isExists(join(tablePath, oldPath)))
187
+ await rename(join(tablePath, oldPath), join(tablePath, newPath));
188
+ }));
189
+ }
190
+ }
191
+ else
192
+ schema = UtilsServer.addIdToSchema(schema, 0, this.salt);
193
+ await writeFile(join(tablePath, "schema.json"), JSON.stringify(schema, null, 2));
194
+ }
195
+ delete this.tables[tableName];
196
+ }
197
+ /**
198
+ * Get table schema and config
199
+ *
200
+ * @param {string} tableName
201
+ * @return {*} {Promise<TableObject>}
202
+ */
203
+ async getTable(tableName) {
204
+ const tablePath = join(this.databasePath, tableName);
205
+ if (!(await File.isExists(tablePath)))
206
+ throw this.throwError("TABLE_NOT_EXISTS", tableName);
207
+ if (!this.tables[tableName])
208
+ this.tables[tableName] = {
209
+ schema: await this.getTableSchema(tableName),
210
+ config: {
211
+ compression: await File.isExists(join(tablePath, ".compression.config")),
212
+ cache: await File.isExists(join(tablePath, ".cache.config")),
213
+ prepend: await File.isExists(join(tablePath, ".prepend.config")),
214
+ },
215
+ };
216
+ return this.tables[tableName];
217
+ }
218
+ async getTableSchema(tableName, encodeIDs = true) {
219
+ const tableSchemaPath = join(this.databasePath, tableName, "schema.json");
220
+ if (!(await File.isExists(tableSchemaPath)))
221
+ return undefined;
222
+ const schemaFile = await readFile(tableSchemaPath, "utf8");
223
+ if (!schemaFile)
224
+ return undefined;
225
+ let schema = JSON.parse(schemaFile);
226
+ const lastIdNumber = UtilsServer.findLastIdNumber(schema, this.salt);
227
+ schema = [
228
+ {
229
+ id: 0,
230
+ key: "id",
231
+ type: "id",
232
+ required: true,
233
+ },
234
+ ...schema,
235
+ {
236
+ id: lastIdNumber + 1,
237
+ key: "createdAt",
238
+ type: "date",
239
+ required: true,
240
+ },
241
+ {
242
+ id: lastIdNumber + 2,
243
+ key: "updatedAt",
244
+ type: "date",
245
+ required: false,
246
+ },
247
+ ];
248
+ if (!encodeIDs)
249
+ return schema;
250
+ return UtilsServer.encodeSchemaID(schema, this.salt);
251
+ }
252
+ async throwErrorIfTableEmpty(tableName) {
253
+ const table = await this.getTable(tableName);
254
+ if (!table.schema)
255
+ throw this.throwError("NO_SCHEMA", tableName);
256
+ if (!(await File.isExists(join(this.databasePath, tableName, `id${this.getFileExtension(tableName)}`))))
257
+ throw this.throwError("NO_ITEMS", tableName);
258
+ return table;
259
+ }
260
+ validateData(data, schema, skipRequiredField = false) {
261
+ if (Utils.isArrayOfObjects(data))
262
+ for (const single_data of data)
263
+ this.validateData(single_data, schema, skipRequiredField);
264
+ else if (Utils.isObject(data)) {
265
+ for (const field of schema) {
266
+ if (!Object.hasOwn(data, field.key) ||
267
+ data[field.key] === null ||
268
+ data[field.key] === undefined) {
269
+ if (field.required && !skipRequiredField)
270
+ throw this.throwError("FIELD_REQUIRED", field.key);
271
+ return;
272
+ }
273
+ if (Object.hasOwn(data, field.key) &&
274
+ !Utils.validateFieldType(data[field.key], field.type, (field.type === "array" || field.type === "object") &&
275
+ field.children &&
276
+ !Utils.isArrayOfObjects(field.children)
277
+ ? field.children
278
+ : undefined))
279
+ throw this.throwError("INVALID_TYPE", [
280
+ field.key,
281
+ Array.isArray(field.type) ? field.type.join(", ") : field.type,
282
+ data[field.key],
283
+ ]);
284
+ if ((field.type === "array" || field.type === "object") &&
285
+ field.children &&
286
+ Utils.isArrayOfObjects(field.children))
287
+ this.validateData(data[field.key], field.children, skipRequiredField);
288
+ else if (field.unique) {
289
+ if (!this.checkIFunique[field.key])
290
+ this.checkIFunique[field.key] = [];
291
+ this.checkIFunique[`${field.key}`].push(data[field.key]);
292
+ }
293
+ }
294
+ }
295
+ }
296
+ formatField(value, fieldType, fieldChildrenType, _formatOnlyAvailiableKeys) {
297
+ if (Array.isArray(fieldType))
298
+ fieldType = (Utils.detectFieldType(value, fieldType) ??
299
+ fieldType[0]);
300
+ if (!value)
301
+ return null;
302
+ switch (fieldType) {
303
+ case "array":
304
+ if (!fieldChildrenType)
305
+ return null;
306
+ if (!Array.isArray(value))
307
+ value = [value];
308
+ if (Utils.isArrayOfObjects(fieldChildrenType))
309
+ return this.formatData(value, fieldChildrenType, _formatOnlyAvailiableKeys);
310
+ return value.map((_value) => this.formatField(_value, fieldChildrenType));
311
+ case "object":
312
+ if (Array.isArray(value))
313
+ value = value[0];
314
+ if (Utils.isArrayOfObjects(fieldChildrenType))
315
+ return this.formatData(value, fieldChildrenType, _formatOnlyAvailiableKeys);
316
+ break;
317
+ case "table":
318
+ if (Array.isArray(value))
319
+ value = value[0];
320
+ if (Utils.isObject(value)) {
321
+ if (Object.hasOwn(value, "id") &&
322
+ (Utils.isValidID(value.id) ||
323
+ Utils.isNumber(value.id)))
324
+ return Utils.isNumber(value.id)
325
+ ? Number(value.id)
326
+ : UtilsServer.decodeID(value.id, this.salt);
327
+ }
328
+ else if (Utils.isValidID(value) || Utils.isNumber(value))
329
+ return Utils.isNumber(value)
330
+ ? Number(value)
331
+ : UtilsServer.decodeID(value, this.salt);
332
+ break;
333
+ case "password":
334
+ if (Array.isArray(value))
335
+ value = value[0];
336
+ return Utils.isPassword(value)
337
+ ? value
338
+ : UtilsServer.hashPassword(String(value));
339
+ case "number":
340
+ if (Array.isArray(value))
341
+ value = value[0];
342
+ return Utils.isNumber(value) ? Number(value) : null;
343
+ case "date": {
344
+ if (Array.isArray(value))
345
+ value = value[0];
346
+ if (Utils.isNumber(value))
347
+ return value;
348
+ const dateToTimestamp = Date.parse(value);
349
+ return Number.isNaN(dateToTimestamp) ? null : dateToTimestamp;
350
+ }
351
+ case "id":
352
+ if (Array.isArray(value))
353
+ value = value[0];
354
+ return Utils.isNumber(value)
355
+ ? value
356
+ : UtilsServer.decodeID(value, this.salt);
357
+ case "json":
358
+ return typeof value !== "string" || !Utils.isJSON(value)
359
+ ? Inison.stringify(value)
360
+ : value;
361
+ default:
362
+ return value;
363
+ }
364
+ return null;
365
+ }
366
+ async checkUnique(tableName, schema) {
367
+ const tablePath = join(this.databasePath, tableName);
368
+ for await (const [key, values] of Object.entries(this.checkIFunique)) {
369
+ const field = Utils.getField(key, schema);
370
+ if (!field)
371
+ continue;
372
+ const [searchResult, totalLines] = await File.search(join(tablePath, `${key}${this.getFileExtension(tableName)}`), Array.isArray(values) ? "=" : "[]", values, undefined, field.type, field.children, 1, undefined, false, this.salt);
373
+ if (searchResult && totalLines > 0)
374
+ throw this.throwError("FIELD_UNIQUE", [
375
+ field.key,
376
+ Array.isArray(values) ? values.join(", ") : values,
377
+ ]);
378
+ }
379
+ this.checkIFunique = {};
380
+ }
381
+ formatData(data, schema, formatOnlyAvailiableKeys) {
382
+ if (Utils.isArrayOfObjects(data))
383
+ return data.map((single_data) => this.formatData(single_data, schema, formatOnlyAvailiableKeys));
384
+ if (Utils.isObject(data)) {
385
+ const RETURN = {};
386
+ for (const field of schema) {
387
+ if (!Object.hasOwn(data, field.key)) {
388
+ if (formatOnlyAvailiableKeys)
389
+ continue;
390
+ RETURN[field.key] = this.getDefaultValue(field);
391
+ continue;
392
+ }
393
+ RETURN[field.key] = this.formatField(data[field.key], field.type, field.children, formatOnlyAvailiableKeys);
394
+ }
395
+ return RETURN;
396
+ }
397
+ return [];
398
+ }
399
+ getDefaultValue(field) {
400
+ if (Array.isArray(field.type))
401
+ return this.getDefaultValue({
402
+ ...field,
403
+ type: field.type.sort((a, b) => Number(b === "array") - Number(a === "array") ||
404
+ Number(a === "string") - Number(b === "string") ||
405
+ Number(a === "number") - Number(b === "number"))[0],
406
+ });
407
+ switch (field.type) {
408
+ case "array":
409
+ return Utils.isArrayOfObjects(field.children)
410
+ ? [
411
+ this.getDefaultValue({
412
+ ...field,
413
+ type: "object",
414
+ children: field.children,
415
+ }),
416
+ ]
417
+ : null;
418
+ case "object": {
419
+ if (!field.children || !Utils.isArrayOfObjects(field.children))
420
+ return null;
421
+ const RETURN = {};
422
+ for (const f of field.children)
423
+ RETURN[f.key] = this.getDefaultValue(f);
424
+ return RETURN;
425
+ }
426
+ case "boolean":
427
+ return false;
428
+ default:
429
+ return null;
430
+ }
431
+ }
432
+ _combineObjectsToArray = (input) => input.reduce((result, current) => {
433
+ for (const [key, value] of Object.entries(current))
434
+ if (Object.hasOwn(result, key) && Array.isArray(result[key]))
435
+ result[key].push(value);
436
+ else
437
+ result[key] = [value];
438
+ return result;
439
+ }, {});
440
+ _CombineData = (data, prefix) => {
441
+ if (Utils.isArrayOfObjects(data))
442
+ return this._combineObjectsToArray(data.map((single_data) => this._CombineData(single_data)));
443
+ const RETURN = {};
444
+ for (const [key, value] of Object.entries(data)) {
445
+ if (Utils.isObject(value))
446
+ Object.assign(RETURN, this._CombineData(value, `${key}.`));
447
+ else if (Utils.isArrayOfObjects(value)) {
448
+ Object.assign(RETURN, this._CombineData(this._combineObjectsToArray(value), `${(prefix ?? "") + key}.`));
449
+ }
450
+ else if (Utils.isArrayOfArrays(value) &&
451
+ value.every(Utils.isArrayOfObjects))
452
+ Object.assign(RETURN, this._CombineData(this._combineObjectsToArray(value.map(this._combineObjectsToArray)), `${(prefix ?? "") + key}.`));
453
+ else
454
+ RETURN[(prefix ?? "") + key] = File.encode(value);
455
+ }
456
+ return RETURN;
457
+ };
458
+ joinPathesContents(tableName, data) {
459
+ const tablePath = join(this.databasePath, tableName), combinedData = this._CombineData(data);
460
+ const newCombinedData = {};
461
+ for (const [key, value] of Object.entries(combinedData))
462
+ newCombinedData[join(tablePath, `${key}${this.getFileExtension(tableName)}`)] = value;
463
+ return newCombinedData;
464
+ }
465
+ _getItemsFromSchemaHelper(RETURN, item, index, field) {
466
+ if (Utils.isObject(item)) {
467
+ if (!RETURN[index])
468
+ RETURN[index] = {};
469
+ if (!RETURN[index][field.key])
470
+ RETURN[index][field.key] = [];
471
+ for (const child_field of field.children.filter((children) => children.type === "array" &&
472
+ Utils.isArrayOfObjects(children.children))) {
473
+ if (Utils.isObject(item[child_field.key])) {
474
+ for (const [key, value] of Object.entries(item[child_field.key])) {
475
+ for (let _i = 0; _i < value.length; _i++) {
476
+ if ((Array.isArray(value[_i]) && Utils.isArrayOfNulls(value[_i])) ||
477
+ value[_i] === null)
478
+ continue;
479
+ if (!RETURN[index][field.key][_i])
480
+ RETURN[index][field.key][_i] = {};
481
+ if (!RETURN[index][field.key][_i][child_field.key])
482
+ RETURN[index][field.key][_i][child_field.key] = [];
483
+ if (!Array.isArray(value[_i])) {
484
+ if (!RETURN[index][field.key][_i][child_field.key][0])
485
+ RETURN[index][field.key][_i][child_field.key][0] = {};
486
+ RETURN[index][field.key][_i][child_field.key][0][key] =
487
+ value[_i];
488
+ }
489
+ else {
490
+ value[_i].forEach((_element, _index) => {
491
+ // Recursive call
492
+ this._getItemsFromSchemaHelper(RETURN[index][field.key][_i][child_field.key][_index], _element, _index, child_field);
493
+ // Perform property assignments
494
+ if (!RETURN[index][field.key][_i][child_field.key][_index])
495
+ RETURN[index][field.key][_i][child_field.key][_index] = {};
496
+ RETURN[index][field.key][_i][child_field.key][_index][key] =
497
+ _element;
498
+ });
499
+ }
500
+ }
501
+ }
502
+ }
503
+ }
504
+ }
505
+ }
506
+ async getItemsFromSchema(tableName, schema, linesNumber, options, prefix) {
507
+ const tablePath = join(this.databasePath, tableName);
508
+ let RETURN = {};
509
+ for await (const field of schema) {
510
+ if ((field.type === "array" ||
511
+ (Array.isArray(field.type) && field.type.includes("array"))) &&
512
+ field.children) {
513
+ if (Utils.isArrayOfObjects(field.children)) {
514
+ if (field.children.filter((children) => children.type === "array" &&
515
+ Utils.isArrayOfObjects(children.children)).length) {
516
+ // one of children has array field type and has children array of object = Schema
517
+ const childItems = await this.getItemsFromSchema(tableName, field.children.filter((children) => children.type === "array" &&
518
+ Utils.isArrayOfObjects(children.children)), linesNumber, options, `${(prefix ?? "") + field.key}.`);
519
+ if (childItems)
520
+ for (const [index, item] of Object.entries(childItems))
521
+ this._getItemsFromSchemaHelper(RETURN, item, index, field);
522
+ field.children = field.children.filter((children) => children.type !== "array" ||
523
+ !Utils.isArrayOfObjects(children.children));
524
+ }
525
+ const fieldItems = await this.getItemsFromSchema(tableName, field.children, linesNumber, options, `${(prefix ?? "") + field.key}.`);
526
+ if (fieldItems)
527
+ for (const [index, item] of Object.entries(fieldItems)) {
528
+ if (!RETURN[index])
529
+ RETURN[index] = {};
530
+ if (Utils.isObject(item)) {
531
+ if (!Utils.isArrayOfNulls(Object.values(item))) {
532
+ if (RETURN[index][field.key])
533
+ Object.entries(item).forEach(([key, value], _index) => {
534
+ for (let _index = 0; _index < value.length; _index++)
535
+ if (RETURN[index][field.key][_index])
536
+ Object.assign(RETURN[index][field.key][_index], {
537
+ [key]: value[_index],
538
+ });
539
+ else
540
+ RETURN[index][field.key][_index] = {
541
+ [key]: value[_index],
542
+ };
543
+ });
544
+ else if (Object.values(item).every((_i) => Utils.isArrayOfArrays(_i) || Array.isArray(_i)) &&
545
+ prefix)
546
+ RETURN[index][field.key] = item;
547
+ else {
548
+ RETURN[index][field.key] = [];
549
+ Object.entries(item).forEach(([key, value], _ind) => {
550
+ if (!Array.isArray(value)) {
551
+ RETURN[index][field.key][_ind] = {};
552
+ RETURN[index][field.key][_ind][key] = value;
553
+ }
554
+ else
555
+ for (let _i = 0; _i < value.length; _i++) {
556
+ if (value[_i] === null ||
557
+ (Array.isArray(value[_i]) &&
558
+ Utils.isArrayOfNulls(value[_i])))
559
+ continue;
560
+ if (!RETURN[index][field.key][_i])
561
+ RETURN[index][field.key][_i] = {};
562
+ RETURN[index][field.key][_i][key] = value[_i];
563
+ }
564
+ });
565
+ }
566
+ }
567
+ else
568
+ RETURN[index][field.key] = null;
569
+ }
570
+ else
571
+ RETURN[index][field.key] = item;
572
+ }
573
+ }
574
+ else if (field.children === "table" ||
575
+ (Array.isArray(field.type) && field.type.includes("table")) ||
576
+ (Array.isArray(field.children) && field.children.includes("table"))) {
577
+ if (field.table &&
578
+ (await File.isExists(join(this.databasePath, field.table))) &&
579
+ (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`)))) {
580
+ if (options.columns)
581
+ options.columns = options.columns
582
+ .filter((column) => column.includes(`${field.key}.`))
583
+ .map((column) => column.replace(`${field.key}.`, ""));
584
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, field.type, field.children, this.salt);
585
+ if (items)
586
+ for await (const [index, item] of Object.entries(items)) {
587
+ if (!RETURN[index])
588
+ RETURN[index] = {};
589
+ RETURN[index][field.key] = item
590
+ ? await this.get(field.table, item, options)
591
+ : this.getDefaultValue(field);
592
+ }
593
+ }
594
+ }
595
+ else if (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`))) {
596
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, field.type, field.children, this.salt);
597
+ if (items)
598
+ for (const [index, item] of Object.entries(items)) {
599
+ if (!RETURN[index])
600
+ RETURN[index] = {};
601
+ RETURN[index][field.key] = item ?? this.getDefaultValue(field);
602
+ }
603
+ }
604
+ }
605
+ else if (field.type === "object") {
606
+ const fieldItems = await this.getItemsFromSchema(tableName, field.children, linesNumber, options, `${(prefix ?? "") + field.key}.`);
607
+ if (fieldItems)
608
+ for (const [index, item] of Object.entries(fieldItems)) {
609
+ if (!RETURN[index])
610
+ RETURN[index] = {};
611
+ if (Utils.isObject(item)) {
612
+ if (!Object.values(item).every((i) => i === null))
613
+ RETURN[index][field.key] = item;
614
+ else
615
+ RETURN[index][field.key] = null;
616
+ }
617
+ else
618
+ RETURN[index][field.key] = null;
619
+ }
620
+ }
621
+ else if (field.type === "table") {
622
+ if (field.table &&
623
+ (await File.isExists(join(this.databasePath, field.table))) &&
624
+ (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`)))) {
625
+ if (options.columns)
626
+ options.columns = options.columns
627
+ .filter((column) => column.includes(`${field.key}.`))
628
+ .map((column) => column.replace(`${field.key}.`, ""));
629
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, "number", undefined, this.salt);
630
+ if (items)
631
+ for await (const [index, item] of Object.entries(items)) {
632
+ if (!RETURN[index])
633
+ RETURN[index] = {};
634
+ RETURN[index][field.key] = item
635
+ ? await this.get(field.table, UtilsServer.encodeID(item, this.salt), options)
636
+ : this.getDefaultValue(field);
637
+ }
638
+ }
639
+ }
640
+ else if (await File.isExists(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`))) {
641
+ const items = await File.get(join(tablePath, `${(prefix ?? "") + field.key}${this.getFileExtension(tableName)}`), linesNumber, field.type, field.children, this.salt);
642
+ if (items)
643
+ for (const [index, item] of Object.entries(items)) {
644
+ if (!RETURN[index])
645
+ RETURN[index] = {};
646
+ RETURN[index][field.key] = item ?? this.getDefaultValue(field);
647
+ }
648
+ else
649
+ RETURN = Object.fromEntries(Object.entries(RETURN).map(([index, data]) => [
650
+ index,
651
+ { ...data, [field.key]: this.getDefaultValue(field) },
652
+ ]));
653
+ }
654
+ }
655
+ return RETURN;
656
+ }
657
+ async applyCriteria(tableName, schema, options, criteria, allTrue) {
658
+ const tablePath = join(this.databasePath, tableName);
659
+ let RETURN = {}, RETURN_LineNumbers = null;
660
+ if (!criteria)
661
+ return [null, null];
662
+ if (criteria.and && Utils.isObject(criteria.and)) {
663
+ const [searchResult, lineNumbers] = await this.applyCriteria(tableName, schema, options, criteria.and, true);
664
+ if (searchResult) {
665
+ RETURN = Utils.deepMerge(RETURN, Object.fromEntries(Object.entries(searchResult).filter(([_k, v], _i) => Object.keys(v).length ===
666
+ Object.keys(criteria.and ?? {}).length)));
667
+ delete criteria.and;
668
+ RETURN_LineNumbers = lineNumbers;
669
+ }
670
+ else
671
+ return [null, null];
672
+ }
673
+ if (criteria.or && Utils.isObject(criteria.or)) {
674
+ const [searchResult, lineNumbers] = await this.applyCriteria(tableName, schema, options, criteria.or, false);
675
+ delete criteria.or;
676
+ if (searchResult) {
677
+ RETURN = Utils.deepMerge(RETURN, searchResult);
678
+ RETURN_LineNumbers = lineNumbers;
679
+ }
680
+ }
681
+ if (Object.keys(criteria).length > 0) {
682
+ if (allTrue === undefined)
683
+ allTrue = true;
684
+ let index = -1;
685
+ for await (const [key, value] of Object.entries(criteria)) {
686
+ const field = Utils.getField(key, schema);
687
+ index++;
688
+ let searchOperator = undefined, searchComparedAtValue = undefined, searchLogicalOperator = undefined;
689
+ if (Utils.isObject(value)) {
690
+ if (value?.or &&
691
+ Array.isArray(value?.or)) {
692
+ const searchCriteria = (value?.or)
693
+ .map((single_or) => typeof single_or === "string"
694
+ ? Utils.FormatObjectCriteriaValue(single_or)
695
+ : ["=", single_or])
696
+ .filter((a) => a);
697
+ if (searchCriteria.length > 0) {
698
+ searchOperator = searchCriteria.map((single_or) => single_or[0]);
699
+ searchComparedAtValue = searchCriteria.map((single_or) => single_or[1]);
700
+ searchLogicalOperator = "or";
701
+ }
702
+ delete value.or;
703
+ }
704
+ if (value?.and &&
705
+ Array.isArray(value?.and)) {
706
+ const searchCriteria = (value?.and)
707
+ .map((single_and) => typeof single_and === "string"
708
+ ? Utils.FormatObjectCriteriaValue(single_and)
709
+ : ["=", single_and])
710
+ .filter((a) => a);
711
+ if (searchCriteria.length > 0) {
712
+ searchOperator = searchCriteria.map((single_and) => single_and[0]);
713
+ searchComparedAtValue = searchCriteria.map((single_and) => single_and[1]);
714
+ searchLogicalOperator = "and";
715
+ }
716
+ delete value.and;
717
+ }
718
+ }
719
+ else if (Array.isArray(value)) {
720
+ const searchCriteria = value
721
+ .map((single) => typeof single === "string"
722
+ ? Utils.FormatObjectCriteriaValue(single)
723
+ : ["=", single])
724
+ .filter((a) => a);
725
+ if (searchCriteria.length > 0) {
726
+ searchOperator = searchCriteria.map((single) => single[0]);
727
+ searchComparedAtValue = searchCriteria.map((single) => single[1]);
728
+ searchLogicalOperator = "and";
729
+ }
730
+ }
731
+ else if (typeof value === "string") {
732
+ const ComparisonOperatorValue = Utils.FormatObjectCriteriaValue(value);
733
+ if (ComparisonOperatorValue) {
734
+ searchOperator = ComparisonOperatorValue[0];
735
+ searchComparedAtValue = ComparisonOperatorValue[1];
736
+ }
737
+ }
738
+ else {
739
+ searchOperator = "=";
740
+ searchComparedAtValue = value;
741
+ }
742
+ const [searchResult, totalLines, linesNumbers] = await File.search(join(tablePath, `${key}${this.getFileExtension(tableName)}`), searchOperator ?? "=", searchComparedAtValue ?? null, searchLogicalOperator, field?.type, field?.children, options.perPage, (options.page - 1) * options.perPage + 1, true, this.salt);
743
+ if (searchResult) {
744
+ RETURN = Utils.deepMerge(RETURN, Object.fromEntries(Object.entries(searchResult).map(([id, value]) => [
745
+ id,
746
+ {
747
+ [key]: value,
748
+ },
749
+ ])));
750
+ this.totalItems[`${tableName}-${key}`] = totalLines;
751
+ RETURN_LineNumbers = linesNumbers;
752
+ }
753
+ if (allTrue && index > 0) {
754
+ if (!Object.keys(RETURN).length)
755
+ RETURN = {};
756
+ RETURN = Object.fromEntries(Object.entries(RETURN).filter(([_index, item]) => Object.keys(item).length > index));
757
+ if (!Object.keys(RETURN).length)
758
+ RETURN = {};
759
+ }
760
+ }
761
+ }
762
+ return [Object.keys(RETURN).length ? RETURN : null, RETURN_LineNumbers];
763
+ }
764
+ _filterSchemaByColumns(schema, columns) {
765
+ return schema
766
+ .map((field) => {
767
+ if (columns.some((column) => column.startsWith("!")))
768
+ return columns.includes(`!${field.key}`) ? null : field;
769
+ if (columns.includes(field.key) || columns.includes("*"))
770
+ return field;
771
+ if ((field.type === "array" || field.type === "object") &&
772
+ Utils.isArrayOfObjects(field.children) &&
773
+ columns.filter((column) => column.startsWith(`${field.key}.`) ||
774
+ column.startsWith(`!${field.key}.`)).length) {
775
+ field.children = this._filterSchemaByColumns(field.children, columns
776
+ .filter((column) => column.startsWith(`${field.key}.`) ||
777
+ column.startsWith(`!${field.key}.`))
778
+ .map((column) => column.replace(`${field.key}.`, "")));
779
+ return field;
780
+ }
781
+ return null;
782
+ })
783
+ .filter((i) => i);
784
+ }
785
+ /**
786
+ * Clear table cache
787
+ *
788
+ * @param {string} tableName
789
+ */
790
+ async clearCache(tableName) {
791
+ const cacheFolderPath = join(this.databasePath, tableName, ".cache");
792
+ await Promise.all((await readdir(cacheFolderPath))
793
+ .filter((file) => file !== ".pagination")
794
+ .map((file) => unlink(join(cacheFolderPath, file))));
795
+ }
796
+ async get(tableName, where, options = {
797
+ page: 1,
798
+ perPage: 15,
799
+ }, onlyOne, onlyLinesNumbers) {
800
+ const tablePath = join(this.databasePath, tableName);
801
+ // Ensure options.columns is an array
802
+ if (options.columns) {
803
+ options.columns = Array.isArray(options.columns)
804
+ ? options.columns
805
+ : [options.columns];
806
+ if (options.columns.length && !options.columns.includes("id"))
807
+ options.columns.push("id");
808
+ }
809
+ // Default values for page and perPage
810
+ options.page = options.page || 1;
811
+ options.perPage = options.perPage || 15;
812
+ let RETURN;
813
+ let schema = (await this.getTable(tableName)).schema;
814
+ if (!schema)
815
+ throw this.throwError("NO_SCHEMA", tableName);
816
+ if (!(await File.isExists(join(tablePath, `id${this.getFileExtension(tableName)}`))))
817
+ return null;
818
+ if (options.columns?.length)
819
+ schema = this._filterSchemaByColumns(schema, options.columns);
820
+ if (where &&
821
+ ((Array.isArray(where) && !where.length) ||
822
+ (Utils.isObject(where) && !Object.keys(where).length)))
823
+ where = undefined;
824
+ if (options.sort) {
825
+ let sortArray, awkCommand = "";
826
+ if (Utils.isObject(options.sort) && !Array.isArray(options.sort)) {
827
+ // {name: "ASC", age: "DESC"}
828
+ sortArray = Object.entries(options.sort).map(([key, value]) => [
829
+ key,
830
+ typeof value === "string" ? value.toLowerCase() === "asc" : value > 0,
831
+ ]);
832
+ }
833
+ else
834
+ sortArray = []
835
+ .concat(options.sort)
836
+ .map((column) => [column, true]);
837
+ let cacheKey = "";
838
+ // Criteria
839
+ if (this.tables[tableName].config.cache)
840
+ cacheKey = UtilsServer.hashString(inspect(sortArray, { sorted: true }));
841
+ if (where) {
842
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
843
+ if (!lineNumbers.length)
844
+ throw this.throwError("NO_RESULTS", tableName);
845
+ const itemsIDs = Object.values((await File.get(join(tablePath, `id${this.getFileExtension(tableName)}`), lineNumbers, "number", undefined, this.salt)) ?? {}).map(Number);
846
+ awkCommand = `awk '${itemsIDs.map((id) => `$1 == ${id}`).join(" || ")}'`;
847
+ }
848
+ else
849
+ awkCommand = `awk '${Array.from({ length: options.perPage }, (_, index) => (options.page - 1) * options.perPage +
850
+ index +
851
+ 1)
852
+ .map((lineNumber) => `NR==${lineNumber}`)
853
+ .join(" || ")}'`;
854
+ const filesPathes = [["id", true], ...sortArray].map((column) => join(tablePath, `${column[0]}${this.getFileExtension(tableName)}`));
855
+ for await (const path of filesPathes.slice(1))
856
+ if (!(await File.isExists(path)))
857
+ return null;
858
+ // Construct the paste command to merge files and filter lines by IDs
859
+ const pasteCommand = `paste ${filesPathes.join(" ")}`;
860
+ // Construct the sort command dynamically based on the number of files for sorting
861
+ const index = 2;
862
+ const sortColumns = sortArray
863
+ .map(([key, ascending], i) => {
864
+ const field = Utils.getField(key, schema);
865
+ if (field)
866
+ return `-k${i + index},${i + index}${Utils.isFieldType(["id", "number", "date"], field.type, field.children)
867
+ ? "n"
868
+ : ""}${!ascending ? "r" : ""}`;
869
+ return "";
870
+ })
871
+ .join(" ");
872
+ const sortCommand = `sort ${sortColumns} -T=${join(tablePath, ".tmp")}`;
873
+ try {
874
+ if (cacheKey)
875
+ await File.lock(join(tablePath, ".tmp"), cacheKey);
876
+ // Combine && Execute the commands synchronously
877
+ let lines = (await UtilsServer.exec(this.tables[tableName].config.cache
878
+ ? (await File.isExists(join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)))
879
+ ? `${awkCommand} ${join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)}`
880
+ : `${pasteCommand} | ${sortCommand} -o ${join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)} && ${awkCommand} ${join(tablePath, ".cache", `${cacheKey}${this.fileExtension}`)}`
881
+ : `${pasteCommand} | ${sortCommand} | ${awkCommand}`, {
882
+ encoding: "utf-8",
883
+ })).stdout
884
+ .trim()
885
+ .split("\n");
886
+ if (where)
887
+ lines = lines.slice((options.page - 1) * options.perPage, options.page * options.perPage);
888
+ else if (!this.totalItems[`${tableName}-*`])
889
+ this.totalItems[`${tableName}-*`] = await File.count(join(tablePath, `id${this.getFileExtension(tableName)}`));
890
+ if (!lines.length)
891
+ return null;
892
+ // Parse the result and extract the specified lines
893
+ const outputArray = lines.map((line) => {
894
+ const splitedFileColumns = line.split("\t"); // Assuming tab-separated columns
895
+ const outputObject = {};
896
+ // Extract values for each file, including `id${this.getFileExtension(tableName)}`
897
+ filesPathes.forEach((fileName, index) => {
898
+ const field = Utils.getField(parse(fileName).name, schema);
899
+ if (field)
900
+ outputObject[field.key] = File.decode(splitedFileColumns[index], field?.type, field?.children, this.salt);
901
+ });
902
+ return outputObject;
903
+ });
904
+ const restOfColumns = await this.get(tableName, outputArray.map(({ id }) => id), (({ sort, ...rest }) => rest)(options));
905
+ return restOfColumns
906
+ ? outputArray.map((item) => ({
907
+ ...item,
908
+ ...restOfColumns.find(({ id }) => id === item.id),
909
+ }))
910
+ : outputArray;
911
+ }
912
+ finally {
913
+ if (cacheKey)
914
+ await File.unlock(join(tablePath, ".tmp"), cacheKey);
915
+ }
916
+ }
917
+ if (!where) {
918
+ // Display all data
919
+ RETURN = Object.values(await this.getItemsFromSchema(tableName, schema, Array.from({ length: options.perPage }, (_, index) => (options.page - 1) * options.perPage +
920
+ index +
921
+ 1), options));
922
+ if (await File.isExists(join(tablePath, ".cache", ".pagination"))) {
923
+ if (!this.totalItems[`${tableName}-*`])
924
+ this.totalItems[`${tableName}-*`] = Number((await readFile(join(tablePath, ".cache", ".pagination"), "utf8")).split(",")[1]);
925
+ }
926
+ else {
927
+ const lastId = Number(Object.keys((await File.get(join(tablePath, `id${this.getFileExtension(tableName)}`), -1, "number", undefined, this.salt, true))?.[0] ?? 0));
928
+ if (!this.totalItems[`${tableName}-*`])
929
+ this.totalItems[`${tableName}-*`] = await File.count(join(tablePath, `id${this.getFileExtension(tableName)}`));
930
+ await writeFile(join(tablePath, ".cache", ".pagination"), `${lastId},${this.totalItems[`${tableName}-*`]}`);
931
+ }
932
+ }
933
+ else if ((Array.isArray(where) && where.every(Utils.isNumber)) ||
934
+ Utils.isNumber(where)) {
935
+ // "where" in this case, is the line(s) number(s) and not id(s)
936
+ let lineNumbers = where;
937
+ if (!Array.isArray(lineNumbers))
938
+ lineNumbers = [lineNumbers];
939
+ if (!this.totalItems[`${tableName}-*`])
940
+ this.totalItems[`${tableName}-*`] = lineNumbers.length;
941
+ // useless
942
+ if (onlyLinesNumbers)
943
+ return lineNumbers;
944
+ RETURN = Object.values((await this.getItemsFromSchema(tableName, schema, lineNumbers, options)) ?? {});
945
+ if (RETURN?.length && !Array.isArray(where))
946
+ RETURN = RETURN[0];
947
+ }
948
+ else if ((Array.isArray(where) && where.every(Utils.isValidID)) ||
949
+ Utils.isValidID(where)) {
950
+ let Ids = where;
951
+ if (!Array.isArray(Ids))
952
+ Ids = [Ids];
953
+ const [lineNumbers, countItems] = await File.search(join(tablePath, `id${this.getFileExtension(tableName)}`), "[]", Ids.map((id) => Utils.isNumber(id) ? Number(id) : UtilsServer.decodeID(id, this.salt)), undefined, "number", undefined, Ids.length, 0, !this.totalItems[`${tableName}-*`], this.salt);
954
+ if (!lineNumbers)
955
+ throw this.throwError("NO_RESULTS", tableName);
956
+ if (!this.totalItems[`${tableName}-*`])
957
+ this.totalItems[`${tableName}-*`] = countItems;
958
+ if (onlyLinesNumbers)
959
+ return Object.keys(lineNumbers).length
960
+ ? Object.keys(lineNumbers).map(Number)
961
+ : null;
962
+ if (options.columns) {
963
+ options.columns = options.columns.filter((column) => column !== "id");
964
+ if (!options.columns?.length)
965
+ options.columns = undefined;
966
+ }
967
+ RETURN = Object.values((await this.getItemsFromSchema(tableName, schema, Object.keys(lineNumbers).map(Number), options)) ?? {});
968
+ if (RETURN?.length && !Array.isArray(where))
969
+ RETURN = RETURN[0];
970
+ }
971
+ else if (Utils.isObject(where)) {
972
+ let cachedFilePath = "";
973
+ // Criteria
974
+ if (this.tables[tableName].config.cache)
975
+ cachedFilePath = join(tablePath, ".cache", `${UtilsServer.hashString(inspect(where, { sorted: true }))}${this.fileExtension}`);
976
+ if (this.tables[tableName].config.cache &&
977
+ (await File.isExists(cachedFilePath))) {
978
+ const cachedItems = (await readFile(cachedFilePath, "utf8")).split(",");
979
+ if (!this.totalItems[`${tableName}-*`])
980
+ this.totalItems[`${tableName}-*`] = cachedItems.length;
981
+ if (onlyLinesNumbers)
982
+ return cachedItems.map(Number);
983
+ return this.get(tableName, cachedItems
984
+ .slice((options.page - 1) * options.perPage, options.page * options.perPage)
985
+ .map(Number), options);
986
+ }
987
+ let linesNumbers = null;
988
+ [RETURN, linesNumbers] = await this.applyCriteria(tableName, schema, options, where);
989
+ if (RETURN && linesNumbers) {
990
+ if (!this.totalItems[`${tableName}-*`])
991
+ this.totalItems[`${tableName}-*`] = linesNumbers.size;
992
+ if (onlyLinesNumbers)
993
+ return Array.from(linesNumbers);
994
+ const alreadyExistsColumns = Object.keys(Object.values(RETURN)[0]), alreadyExistsColumnsIDs = Utils.flattenSchema(schema)
995
+ .filter(({ key }) => alreadyExistsColumns.includes(key))
996
+ .map(({ id }) => id);
997
+ RETURN = Object.values(Utils.deepMerge(RETURN, await this.getItemsFromSchema(tableName, Utils.filterSchema(schema, ({ id, type, children }) => !alreadyExistsColumnsIDs.includes(id) ||
998
+ Utils.isFieldType("table", type, children)), Object.keys(RETURN).map(Number), options)));
999
+ if (this.tables[tableName].config.cache)
1000
+ await writeFile(cachedFilePath, Array.from(linesNumbers).join(","));
1001
+ }
1002
+ }
1003
+ if (!RETURN ||
1004
+ (Utils.isObject(RETURN) && !Object.keys(RETURN).length) ||
1005
+ (Array.isArray(RETURN) && !RETURN.length))
1006
+ return null;
1007
+ const greatestTotalItems = this.totalItems[`${tableName}-*`] ??
1008
+ Math.max(...Object.entries(this.totalItems)
1009
+ .filter(([k]) => k.startsWith(`${tableName}-`))
1010
+ .map(([, v]) => v));
1011
+ this.pageInfo[tableName] = {
1012
+ ...(({ columns, ...restOfOptions }) => restOfOptions)(options),
1013
+ perPage: Array.isArray(RETURN) ? RETURN.length : 1,
1014
+ totalPages: Math.ceil(greatestTotalItems / options.perPage),
1015
+ total: greatestTotalItems,
1016
+ };
1017
+ return onlyOne && Array.isArray(RETURN) ? RETURN[0] : RETURN;
1018
+ }
1019
+ async post(tableName, data, options, returnPostedData) {
1020
+ if (!options)
1021
+ options = {
1022
+ page: 1,
1023
+ perPage: 15,
1024
+ };
1025
+ const tablePath = join(this.databasePath, tableName), schema = (await this.getTable(tableName)).schema;
1026
+ if (!schema)
1027
+ throw this.throwError("NO_SCHEMA", tableName);
1028
+ if (!returnPostedData)
1029
+ returnPostedData = false;
1030
+ let RETURN;
1031
+ const keys = UtilsServer.hashString(Object.keys(Array.isArray(data) ? data[0] : data).join("."));
1032
+ let lastId = 0, renameList = [];
1033
+ try {
1034
+ await File.lock(join(tablePath, ".tmp"), keys);
1035
+ if (await File.isExists(join(tablePath, `id${this.getFileExtension(tableName)}`))) {
1036
+ if (await File.isExists(join(tablePath, ".cache", ".pagination")))
1037
+ [lastId, this.totalItems[`${tableName}-*`]] = (await readFile(join(tablePath, ".cache", ".pagination"), "utf8"))
1038
+ .split(",")
1039
+ .map(Number);
1040
+ else {
1041
+ lastId = Number(Object.keys((await File.get(join(tablePath, `id${this.getFileExtension(tableName)}`), -1, "number", undefined, this.salt, true))?.[0] ?? 0));
1042
+ if (!this.totalItems[`${tableName}-*`])
1043
+ this.totalItems[`${tableName}-*`] = await File.count(join(tablePath, `id${this.getFileExtension(tableName)}`));
1044
+ }
1045
+ }
1046
+ else
1047
+ this.totalItems[`${tableName}-*`] = 0;
1048
+ if (Utils.isArrayOfObjects(data))
1049
+ RETURN = data.map(({ id, updatedAt, createdAt, ...rest }) => ({
1050
+ id: ++lastId,
1051
+ ...rest,
1052
+ createdAt: Date.now(),
1053
+ }));
1054
+ else
1055
+ RETURN = (({ id, updatedAt, createdAt, ...rest }) => ({
1056
+ id: ++lastId,
1057
+ ...rest,
1058
+ createdAt: Date.now(),
1059
+ }))(data);
1060
+ this.validateData(RETURN, schema);
1061
+ await this.checkUnique(tableName, schema);
1062
+ RETURN = this.formatData(RETURN, schema);
1063
+ const pathesContents = this.joinPathesContents(tableName, this.tables[tableName].config.prepend
1064
+ ? Array.isArray(RETURN)
1065
+ ? RETURN.toReversed()
1066
+ : RETURN
1067
+ : RETURN);
1068
+ await Promise.all(Object.entries(pathesContents).map(async ([path, content]) => renameList.push(this.tables[tableName].config.prepend
1069
+ ? await File.prepend(path, content)
1070
+ : await File.append(path, content))));
1071
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
1072
+ renameList = [];
1073
+ if (this.tables[tableName].config.cache)
1074
+ await this.clearCache(tableName);
1075
+ this.totalItems[`${tableName}-*`] += Array.isArray(RETURN)
1076
+ ? RETURN.length
1077
+ : 1;
1078
+ await writeFile(join(tablePath, ".cache", ".pagination"), `${lastId},${this.totalItems[`${tableName}-*`]}`);
1079
+ if (returnPostedData)
1080
+ return this.get(tableName, this.tables[tableName].config.prepend
1081
+ ? Array.isArray(RETURN)
1082
+ ? RETURN.map((_, index) => index + 1)
1083
+ : 1
1084
+ : Array.isArray(RETURN)
1085
+ ? RETURN.map((_, index) => this.totalItems[`${tableName}-*`] - index)
1086
+ : this.totalItems[`${tableName}-*`], options, !Utils.isArrayOfObjects(data));
1087
+ }
1088
+ finally {
1089
+ if (renameList.length)
1090
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
1091
+ await File.unlock(join(tablePath, ".tmp"), keys);
1092
+ }
1093
+ }
1094
+ async put(tableName, data, where, options = {
1095
+ page: 1,
1096
+ perPage: 15,
1097
+ }, returnUpdatedData) {
1098
+ let renameList = [];
1099
+ const tablePath = join(this.databasePath, tableName), schema = (await this.throwErrorIfTableEmpty(tableName)).schema;
1100
+ this.validateData(data, schema, true);
1101
+ await this.checkUnique(tableName, schema);
1102
+ data = this.formatData(data, schema, true);
1103
+ if (!where) {
1104
+ if (Utils.isArrayOfObjects(data)) {
1105
+ if (!data.every((item) => Object.hasOwn(item, "id") && Utils.isValidID(item.id)))
1106
+ throw this.throwError("INVALID_ID");
1107
+ // TODO: Reduce I/O
1108
+ return this.put(tableName, data, data
1109
+ .filter(({ id }) => id !== undefined)
1110
+ .map(({ id }) => id));
1111
+ }
1112
+ if (Object.hasOwn(data, "id")) {
1113
+ if (!Utils.isValidID(data.id))
1114
+ throw this.throwError("INVALID_ID", data.id);
1115
+ return this.put(tableName, data, data.id);
1116
+ }
1117
+ let totalItems;
1118
+ if (await File.isExists(join(tablePath, ".cache", ".pagination")))
1119
+ totalItems = (await readFile(join(tablePath, ".cache", ".pagination"), "utf8"))
1120
+ .split(",")
1121
+ .map(Number)[1];
1122
+ else
1123
+ totalItems = await File.count(join(tablePath, `id${this.getFileExtension(tableName)}`));
1124
+ const pathesContents = this.joinPathesContents(tableName, {
1125
+ ...(({ id, ...restOfData }) => restOfData)(data),
1126
+ updatedAt: Date.now(),
1127
+ });
1128
+ try {
1129
+ await File.lock(join(tablePath, ".tmp"));
1130
+ await Promise.all(Object.entries(pathesContents).map(async ([path, content]) => {
1131
+ const replacementObject = {};
1132
+ for (const index of [...Array(totalItems)].keys())
1133
+ replacementObject[`${index + 1}`] = content;
1134
+ renameList.push(await File.replace(path, replacementObject));
1135
+ }));
1136
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
1137
+ if (this.tables[tableName].config.cache)
1138
+ await this.clearCache(join(tablePath, ".cache"));
1139
+ if (returnUpdatedData)
1140
+ return await this.get(tableName, undefined, options);
1141
+ }
1142
+ finally {
1143
+ if (renameList.length)
1144
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
1145
+ await File.unlock(join(tablePath, ".tmp"));
1146
+ }
1147
+ }
1148
+ else if ((Array.isArray(where) && where.every(Utils.isValidID)) ||
1149
+ Utils.isValidID(where)) {
1150
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1151
+ return this.put(tableName, data, lineNumbers);
1152
+ }
1153
+ else if ((Array.isArray(where) && where.every(Utils.isNumber)) ||
1154
+ Utils.isNumber(where)) {
1155
+ // "where" in this case, is the line(s) number(s) and not id(s)
1156
+ const pathesContents = Object.fromEntries(Object.entries(this.joinPathesContents(tableName, Utils.isArrayOfObjects(data)
1157
+ ? data.map((item) => ({
1158
+ ...item,
1159
+ updatedAt: Date.now(),
1160
+ }))
1161
+ : { ...data, updatedAt: Date.now() })).map(([path, content]) => [
1162
+ path,
1163
+ [...(Array.isArray(where) ? where : [where])].reduce((obj, lineNum, index) => Object.assign(obj, {
1164
+ [lineNum]: Array.isArray(content) ? content[index] : content,
1165
+ }), {}),
1166
+ ]));
1167
+ const keys = UtilsServer.hashString(Object.keys(pathesContents)
1168
+ .map((path) => path.replaceAll(this.getFileExtension(tableName), ""))
1169
+ .join("."));
1170
+ try {
1171
+ await File.lock(join(tablePath, ".tmp"), keys);
1172
+ await Promise.all(Object.entries(pathesContents).map(async ([path, content]) => renameList.push(await File.replace(path, content))));
1173
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
1174
+ renameList = [];
1175
+ if (this.tables[tableName].config.cache)
1176
+ await this.clearCache(tableName);
1177
+ if (returnUpdatedData)
1178
+ return this.get(tableName, where, options, !Array.isArray(where));
1179
+ }
1180
+ finally {
1181
+ if (renameList.length)
1182
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
1183
+ await File.unlock(join(tablePath, ".tmp"), keys);
1184
+ }
1185
+ }
1186
+ else if (Utils.isObject(where)) {
1187
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1188
+ if (returnUpdatedData)
1189
+ return this.put(tableName, data, lineNumbers, options, returnUpdatedData);
1190
+ await this.put(tableName, data, lineNumbers, options, returnUpdatedData);
1191
+ }
1192
+ else
1193
+ throw this.throwError("INVALID_PARAMETERS");
1194
+ }
1195
+ /**
1196
+ * Delete item(s) in a table
1197
+ *
1198
+ * @param {string} tableName
1199
+ * @param {(number | string | (number | string)[] | Criteria)} [where]
1200
+ * @return {boolean | null} {(Promise<boolean | null>)}
1201
+ */
1202
+ async delete(tableName, where, _id) {
1203
+ const renameList = [];
1204
+ const tablePath = join(this.databasePath, tableName);
1205
+ await this.throwErrorIfTableEmpty(tableName);
1206
+ if (!where) {
1207
+ try {
1208
+ await File.lock(join(tablePath, ".tmp"));
1209
+ await Promise.all((await readdir(tablePath))
1210
+ ?.filter((fileName) => fileName.endsWith(this.getFileExtension(tableName)))
1211
+ .map(async (file) => unlink(join(tablePath, file))));
1212
+ if (this.tables[tableName].config.cache)
1213
+ await this.clearCache(tableName);
1214
+ return true;
1215
+ }
1216
+ finally {
1217
+ await File.unlock(join(tablePath, ".tmp"));
1218
+ }
1219
+ }
1220
+ if ((Array.isArray(where) && where.every(Utils.isValidID)) ||
1221
+ Utils.isValidID(where)) {
1222
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1223
+ return this.delete(tableName, lineNumbers, where);
1224
+ }
1225
+ if ((Array.isArray(where) && where.every(Utils.isNumber)) ||
1226
+ Utils.isNumber(where)) {
1227
+ // "where" in this case, is the line(s) number(s) and not id(s)
1228
+ const files = (await readdir(tablePath))?.filter((fileName) => fileName.endsWith(this.getFileExtension(tableName)));
1229
+ if (files.length) {
1230
+ try {
1231
+ await File.lock(join(tablePath, ".tmp"));
1232
+ await Promise.all(files.map(async (file) => renameList.push(await File.remove(join(tablePath, file), where))));
1233
+ await Promise.all(renameList.map(async ([tempPath, filePath]) => rename(tempPath, filePath)));
1234
+ if (this.tables[tableName].config.cache)
1235
+ await this.clearCache(tableName);
1236
+ if (await File.isExists(join(tablePath, ".cache", ".pagination"))) {
1237
+ const [lastId, totalItems] = (await readFile(join(tablePath, ".cache", ".pagination"), "utf8"))
1238
+ .split(",")
1239
+ .map(Number);
1240
+ await writeFile(join(tablePath, ".cache", ".pagination"), `${lastId},${totalItems - (Array.isArray(where) ? where.length : 1)}`);
1241
+ }
1242
+ return true;
1243
+ }
1244
+ finally {
1245
+ if (renameList.length)
1246
+ await Promise.allSettled(renameList.map(async ([tempPath, _]) => unlink(tempPath)));
1247
+ await File.unlock(join(tablePath, ".tmp"));
1248
+ }
1249
+ }
1250
+ }
1251
+ else if (Utils.isObject(where)) {
1252
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1253
+ return this.delete(tableName, lineNumbers);
1254
+ }
1255
+ else
1256
+ throw this.throwError("INVALID_PARAMETERS");
1257
+ return false;
1258
+ }
1259
+ async sum(tableName, columns, where) {
1260
+ const RETURN = {};
1261
+ const tablePath = join(this.databasePath, tableName);
1262
+ await this.throwErrorIfTableEmpty(tableName);
1263
+ if (!Array.isArray(columns))
1264
+ columns = [columns];
1265
+ for await (const column of columns) {
1266
+ const columnPath = join(tablePath, `${column}${this.getFileExtension(tableName)}`);
1267
+ if (await File.isExists(columnPath)) {
1268
+ if (where) {
1269
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1270
+ RETURN[column] = lineNumbers
1271
+ ? await File.sum(columnPath, lineNumbers)
1272
+ : 0;
1273
+ }
1274
+ else
1275
+ RETURN[column] = await File.sum(columnPath);
1276
+ }
1277
+ }
1278
+ return Array.isArray(columns) ? RETURN : Object.values(RETURN)[0];
1279
+ }
1280
+ async max(tableName, columns, where) {
1281
+ const RETURN = {};
1282
+ const tablePath = join(this.databasePath, tableName);
1283
+ await this.throwErrorIfTableEmpty(tableName);
1284
+ if (!Array.isArray(columns))
1285
+ columns = [columns];
1286
+ for await (const column of columns) {
1287
+ const columnPath = join(tablePath, `${column}${this.getFileExtension(tableName)}`);
1288
+ if (await File.isExists(columnPath)) {
1289
+ if (where) {
1290
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1291
+ RETURN[column] = lineNumbers
1292
+ ? await File.max(columnPath, lineNumbers)
1293
+ : 0;
1294
+ }
1295
+ else
1296
+ RETURN[column] = await File.max(columnPath);
1297
+ }
1298
+ }
1299
+ return RETURN;
1300
+ }
1301
+ async min(tableName, columns, where) {
1302
+ const RETURN = {};
1303
+ const tablePath = join(this.databasePath, tableName);
1304
+ await this.throwErrorIfTableEmpty(tableName);
1305
+ if (!Array.isArray(columns))
1306
+ columns = [columns];
1307
+ for await (const column of columns) {
1308
+ const columnPath = join(tablePath, `${column}${this.getFileExtension(tableName)}`);
1309
+ if (await File.isExists(columnPath)) {
1310
+ if (where) {
1311
+ const lineNumbers = await this.get(tableName, where, undefined, undefined, true);
1312
+ RETURN[column] = lineNumbers
1313
+ ? await File.min(columnPath, lineNumbers)
1314
+ : 0;
1315
+ }
1316
+ else
1317
+ RETURN[column] = await File.min(columnPath);
1318
+ }
1319
+ }
1320
+ return RETURN;
1321
+ }
1322
+ }