@alwatr/nitrobase-engine 7.4.0 → 7.5.4
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/CHANGELOG.md +22 -0
- package/dist/alwatr-nitrobase.d.ts +9 -12
- package/dist/alwatr-nitrobase.d.ts.map +1 -1
- package/dist/main.cjs +33 -32
- package/dist/main.cjs.map +2 -2
- package/dist/main.mjs +33 -32
- package/dist/main.mjs.map +2 -2
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,28 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [7.5.4](https://github.com/Alwatr/nitrobase/compare/v7.5.3...v7.5.4) (2025-01-12)
|
|
7
|
+
|
|
8
|
+
### Bug Fixes
|
|
9
|
+
|
|
10
|
+
* **nitrobase:** optional data in newStoreFile_ and throw Error when data not exist for document type ([6d2a173](https://github.com/Alwatr/nitrobase/commit/6d2a173ca4414d6928ef1b703dd0836648eb0787)) by @alimd
|
|
11
|
+
* **nitrobase:** remove initialData parameter from newCollection method ([56cacf0](https://github.com/Alwatr/nitrobase/commit/56cacf0e65e8be2d68f4621eaf4e6d847bf39293)) by @alimd
|
|
12
|
+
* **nitrobase:** required initial data for newDocument ([61f1788](https://github.com/Alwatr/nitrobase/commit/61f178850594ccfc0c1a4ab9429cc2e0438eb11c)) by @alimd
|
|
13
|
+
|
|
14
|
+
### Code Refactoring
|
|
15
|
+
|
|
16
|
+
* **nitrobase:** bind storeChanged_ method directly instead of using bind in multiple locations ([dba1da6](https://github.com/Alwatr/nitrobase/commit/dba1da6bf095e6984af98d8e6c65c64fcc3fb5af)) by @alimd
|
|
17
|
+
|
|
18
|
+
### Dependencies update
|
|
19
|
+
|
|
20
|
+
* **deps-dev:** bump the dependencies group across 1 directory with 11 updates ([fdd30a6](https://github.com/Alwatr/nitrobase/commit/fdd30a6639ae7ead4e8dbfaca0295cb2bf0e6649)) by @dependabot[bot]
|
|
21
|
+
|
|
22
|
+
## [7.5.0](https://github.com/Alwatr/nitrobase/compare/v7.4.1...v7.5.0) (2024-11-09)
|
|
23
|
+
|
|
24
|
+
### Code Refactoring
|
|
25
|
+
|
|
26
|
+
* **engine:** make `config` as a public property ([6453540](https://github.com/Alwatr/nitrobase/commit/6453540aac42340cfe3b7ac9e4c26f904aaccdcc)) by @mohammadhonarvar
|
|
27
|
+
|
|
6
28
|
## [7.4.0](https://github.com/Alwatr/nitrobase/compare/v7.3.1...v7.4.0) (2024-11-08)
|
|
7
29
|
|
|
8
30
|
### Dependencies update
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CollectionReference, DocumentReference } from '@alwatr/nitrobase-reference';
|
|
2
|
-
import { type StoreFileStat, type
|
|
2
|
+
import { type StoreFileStat, type StoreFileId, type CollectionItem } from '@alwatr/nitrobase-types';
|
|
3
3
|
/**
|
|
4
4
|
* AlwatrNitrobase configuration.
|
|
5
5
|
*/
|
|
@@ -28,7 +28,7 @@ export interface AlwatrNitrobaseConfig {
|
|
|
28
28
|
* It also provides methods to interact with `documents` and `collections` in the nitrobase.
|
|
29
29
|
*/
|
|
30
30
|
export declare class AlwatrNitrobase {
|
|
31
|
-
|
|
31
|
+
readonly config: AlwatrNitrobaseConfig;
|
|
32
32
|
/**
|
|
33
33
|
* The Alwatr Nitrobase version string.
|
|
34
34
|
*
|
|
@@ -51,7 +51,7 @@ export declare class AlwatrNitrobase {
|
|
|
51
51
|
/**
|
|
52
52
|
* Constructs an AlwatrNitrobase instance with the provided configuration.
|
|
53
53
|
*
|
|
54
|
-
* @param
|
|
54
|
+
* @param config The configuration of the AlwatrNitrobase engine.
|
|
55
55
|
* @example
|
|
56
56
|
* ```typescript
|
|
57
57
|
* const alwatrStore = new AlwatrNitrobase({
|
|
@@ -60,7 +60,7 @@ export declare class AlwatrNitrobase {
|
|
|
60
60
|
* });
|
|
61
61
|
* ```
|
|
62
62
|
*/
|
|
63
|
-
constructor(
|
|
63
|
+
constructor(config: AlwatrNitrobaseConfig);
|
|
64
64
|
/**
|
|
65
65
|
* Checks if a nitrobase file with the given ID exists.
|
|
66
66
|
*
|
|
@@ -79,7 +79,7 @@ export declare class AlwatrNitrobase {
|
|
|
79
79
|
* If a document with the same ID already exists, an error is thrown.
|
|
80
80
|
*
|
|
81
81
|
* @param stat nitrobase file stat
|
|
82
|
-
* @param
|
|
82
|
+
* @param data initial data for the document
|
|
83
83
|
* @template TDoc document data type
|
|
84
84
|
* @example
|
|
85
85
|
* ```typescript
|
|
@@ -96,14 +96,12 @@ export declare class AlwatrNitrobase {
|
|
|
96
96
|
* );
|
|
97
97
|
* ```
|
|
98
98
|
*/
|
|
99
|
-
newDocument<
|
|
99
|
+
newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void;
|
|
100
100
|
/**
|
|
101
101
|
* Defines a new collection with the given configuration and initial data.
|
|
102
102
|
* If a collection with the same ID already exists, an error is thrown.
|
|
103
103
|
*
|
|
104
104
|
* @param stat nitrobase file stat
|
|
105
|
-
* @param initialData initial data for the collection
|
|
106
|
-
* @template TItem collection item data type
|
|
107
105
|
* @example
|
|
108
106
|
* ```typescript
|
|
109
107
|
* await alwatrStore.newCollection<Order>(
|
|
@@ -115,15 +113,14 @@ export declare class AlwatrNitrobase {
|
|
|
115
113
|
* );
|
|
116
114
|
* ```
|
|
117
115
|
*/
|
|
118
|
-
newCollection
|
|
116
|
+
newCollection(stat: Omit<StoreFileStat, 'type'>): void;
|
|
119
117
|
/**
|
|
120
118
|
* Defines a AlwatrNitrobaseFile with the given configuration and initial data.
|
|
121
119
|
*
|
|
122
120
|
* @param stat nitrobase file stat
|
|
123
|
-
* @param
|
|
124
|
-
* @template TDoc document data type
|
|
121
|
+
* @param data initial data for the document
|
|
125
122
|
*/
|
|
126
|
-
newStoreFile_
|
|
123
|
+
newStoreFile_(stat: StoreFileStat, data?: DictionaryOpt): void;
|
|
127
124
|
/**
|
|
128
125
|
* Open a document with the given id and create and return a DocumentReference.
|
|
129
126
|
* If the document not exists or its not a document, an error is thrown.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alwatr-nitrobase.d.ts","sourceRoot":"","sources":["../src/alwatr-nitrobase.ts"],"names":[],"mappings":"AAIA,OAAO,EAAC,mBAAmB,EAAE,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AACnF,OAAO,EAIL,KAAK,aAAa,
|
|
1
|
+
{"version":3,"file":"alwatr-nitrobase.d.ts","sourceRoot":"","sources":["../src/alwatr-nitrobase.ts"],"names":[],"mappings":"AAIA,OAAO,EAAC,mBAAmB,EAAE,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AACnF,OAAO,EAIL,KAAK,aAAa,EAIlB,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,yBAAyB,CAAC;AAMjC;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;OAGG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACnC;AAED;;;;;GAKG;AACH,qBAAa,eAAe;IA0Cd,QAAQ,CAAC,MAAM,EAAE,qBAAqB;IAzClD;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,OAAO,SAAuB;IAE9C;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAMlC;IAEF;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC;IAEjB;;OAEG;IACH,OAAO,CAAC,iBAAiB,CAA8D;IAEvF;;;;;;;;;;;OAWG;gBACkB,MAAM,EAAE,qBAAqB;IAQlD;;;;;;;;;;;OAWG;IACH,QAAQ,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO;IAOvC;;;;;;;;;;;;;;;;;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C,aAAa,EAAE,WAAW,CAAC,CAAC,EAAE;CAInE"}
|
package/dist/main.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* @alwatr/nitrobase-engine v7.4
|
|
1
|
+
/* @alwatr/nitrobase-engine v7.5.4 */
|
|
2
2
|
"use strict";
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -35,7 +35,7 @@ var import_nitrobase_types = require("@alwatr/nitrobase-types");
|
|
|
35
35
|
|
|
36
36
|
// src/logger.ts
|
|
37
37
|
var import_nanolib = require("@alwatr/nanolib");
|
|
38
|
-
__dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-engine", "7.4
|
|
38
|
+
__dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-engine", "7.5.4");
|
|
39
39
|
var logger = /* @__PURE__ */ (0, import_nanolib.createLogger)("@alwatr/nitrobase-engine");
|
|
40
40
|
|
|
41
41
|
// src/alwatr-nitrobase.ts
|
|
@@ -44,7 +44,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
44
44
|
/**
|
|
45
45
|
* Constructs an AlwatrNitrobase instance with the provided configuration.
|
|
46
46
|
*
|
|
47
|
-
* @param
|
|
47
|
+
* @param config The configuration of the AlwatrNitrobase engine.
|
|
48
48
|
* @example
|
|
49
49
|
* ```typescript
|
|
50
50
|
* const alwatrStore = new AlwatrNitrobase({
|
|
@@ -53,16 +53,17 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
53
53
|
* });
|
|
54
54
|
* ```
|
|
55
55
|
*/
|
|
56
|
-
constructor(
|
|
57
|
-
this.
|
|
56
|
+
constructor(config) {
|
|
57
|
+
this.config = config;
|
|
58
58
|
/**
|
|
59
59
|
* Keep all loaded nitrobase file context loaded in memory.
|
|
60
60
|
*/
|
|
61
61
|
this.cacheReferences__ = {};
|
|
62
62
|
var _a;
|
|
63
|
-
logger.logMethodArgs?.("new",
|
|
64
|
-
(_a = this.
|
|
63
|
+
logger.logMethodArgs?.("new", config);
|
|
64
|
+
(_a = this.config).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
|
|
65
65
|
this.rootDb__ = this.loadRootDb__();
|
|
66
|
+
this.storeChanged_ = this.storeChanged_.bind(this);
|
|
66
67
|
(0, import_exit_hook.exitHook)(this.exitHook__.bind(this));
|
|
67
68
|
}
|
|
68
69
|
/**
|
|
@@ -88,7 +89,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
88
89
|
* If a document with the same ID already exists, an error is thrown.
|
|
89
90
|
*
|
|
90
91
|
* @param stat nitrobase file stat
|
|
91
|
-
* @param
|
|
92
|
+
* @param data initial data for the document
|
|
92
93
|
* @template TDoc document data type
|
|
93
94
|
* @example
|
|
94
95
|
* ```typescript
|
|
@@ -105,14 +106,14 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
105
106
|
* );
|
|
106
107
|
* ```
|
|
107
108
|
*/
|
|
108
|
-
newDocument(stat,
|
|
109
|
+
newDocument(stat, data) {
|
|
109
110
|
logger.logMethodArgs?.("newDocument", stat);
|
|
110
111
|
return this.newStoreFile_(
|
|
111
112
|
{
|
|
112
113
|
...stat,
|
|
113
114
|
type: import_nitrobase_types.StoreFileType.Document
|
|
114
115
|
},
|
|
115
|
-
|
|
116
|
+
data
|
|
116
117
|
);
|
|
117
118
|
}
|
|
118
119
|
/**
|
|
@@ -120,8 +121,6 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
120
121
|
* If a collection with the same ID already exists, an error is thrown.
|
|
121
122
|
*
|
|
122
123
|
* @param stat nitrobase file stat
|
|
123
|
-
* @param initialData initial data for the collection
|
|
124
|
-
* @template TItem collection item data type
|
|
125
124
|
* @example
|
|
126
125
|
* ```typescript
|
|
127
126
|
* await alwatrStore.newCollection<Order>(
|
|
@@ -133,31 +132,33 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
133
132
|
* );
|
|
134
133
|
* ```
|
|
135
134
|
*/
|
|
136
|
-
newCollection(stat
|
|
135
|
+
newCollection(stat) {
|
|
137
136
|
logger.logMethodArgs?.("newCollection", stat);
|
|
138
137
|
return this.newStoreFile_(
|
|
139
138
|
{
|
|
140
139
|
...stat,
|
|
141
140
|
type: import_nitrobase_types.StoreFileType.Collection
|
|
142
|
-
}
|
|
143
|
-
initialData
|
|
141
|
+
}
|
|
144
142
|
);
|
|
145
143
|
}
|
|
146
144
|
/**
|
|
147
145
|
* Defines a AlwatrNitrobaseFile with the given configuration and initial data.
|
|
148
146
|
*
|
|
149
147
|
* @param stat nitrobase file stat
|
|
150
|
-
* @param
|
|
151
|
-
* @template TDoc document data type
|
|
148
|
+
* @param data initial data for the document
|
|
152
149
|
*/
|
|
153
|
-
newStoreFile_(stat,
|
|
150
|
+
newStoreFile_(stat, data) {
|
|
154
151
|
logger.logMethodArgs?.("newStoreFile_", stat);
|
|
155
|
-
stat.changeDebounce ?? (stat.changeDebounce = this.
|
|
152
|
+
stat.changeDebounce ?? (stat.changeDebounce = this.config.defaultChangeDebounce);
|
|
156
153
|
let fileStoreRef;
|
|
157
154
|
if (stat.type === import_nitrobase_types.StoreFileType.Document) {
|
|
158
|
-
|
|
155
|
+
if (data === void 0) {
|
|
156
|
+
logger.accident("newStoreFile_", "document_data_required", stat);
|
|
157
|
+
throw new Error("document_data_required", { cause: stat });
|
|
158
|
+
}
|
|
159
|
+
fileStoreRef = import_nitrobase_reference.DocumentReference.newRefFromData(stat, data, this.storeChanged_);
|
|
159
160
|
} else if (stat.type === import_nitrobase_types.StoreFileType.Collection) {
|
|
160
|
-
fileStoreRef = import_nitrobase_reference.CollectionReference.newRefFromData(stat,
|
|
161
|
+
fileStoreRef = import_nitrobase_reference.CollectionReference.newRefFromData(stat, this.storeChanged_);
|
|
161
162
|
} else {
|
|
162
163
|
logger.accident("newStoreFile_", "store_file_type_not_supported", stat);
|
|
163
164
|
throw new Error("store_file_type_not_supported", { cause: stat });
|
|
@@ -208,7 +209,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
208
209
|
throw new Error("document_wrong_type", { cause: id });
|
|
209
210
|
}
|
|
210
211
|
const context = await this.readContext__(storeStat);
|
|
211
|
-
const docRef = import_nitrobase_reference.DocumentReference.newRefFromContext(context, this.storeChanged_
|
|
212
|
+
const docRef = import_nitrobase_reference.DocumentReference.newRefFromContext(context, this.storeChanged_);
|
|
212
213
|
this.cacheReferences__[id] = docRef;
|
|
213
214
|
return docRef;
|
|
214
215
|
}
|
|
@@ -250,7 +251,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
250
251
|
throw new Error("collection_not_found", { cause: id });
|
|
251
252
|
}
|
|
252
253
|
const context = await this.readContext__(storeStat);
|
|
253
|
-
const colRef = import_nitrobase_reference.CollectionReference.newRefFromContext(context, this.storeChanged_
|
|
254
|
+
const colRef = import_nitrobase_reference.CollectionReference.newRefFromContext(context, this.storeChanged_);
|
|
254
255
|
this.cacheReferences__[id] = colRef;
|
|
255
256
|
return colRef;
|
|
256
257
|
}
|
|
@@ -307,7 +308,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
307
308
|
this.rootDb__.removeItem(id_);
|
|
308
309
|
await import_nanolib2.delay.by(0);
|
|
309
310
|
try {
|
|
310
|
-
await (0, import_node_fs.unlink)((0, import_node_fs.resolve)(this.
|
|
311
|
+
await (0, import_node_fs.unlink)((0, import_node_fs.resolve)(this.config.rootPath, path));
|
|
311
312
|
} catch (error) {
|
|
312
313
|
logger.error("removeStore", "remove_file_failed", error, { id: storeId, path });
|
|
313
314
|
}
|
|
@@ -340,7 +341,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
340
341
|
if (typeof path !== "string") path = (0, import_nitrobase_helper.getStorePath)(path);
|
|
341
342
|
logger.logMethodArgs?.("readContext__", path);
|
|
342
343
|
logger.time?.(`readContext__time(${path})`);
|
|
343
|
-
const context = await (0, import_node_fs.readJson)((0, import_node_fs.resolve)(this.
|
|
344
|
+
const context = await (0, import_node_fs.readJson)((0, import_node_fs.resolve)(this.config.rootPath, path));
|
|
344
345
|
logger.timeEnd?.(`readContext__time(${path})`);
|
|
345
346
|
return context;
|
|
346
347
|
}
|
|
@@ -356,7 +357,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
356
357
|
writeContext__(path, context) {
|
|
357
358
|
if (typeof path !== "string") path = (0, import_nitrobase_helper.getStorePath)(path);
|
|
358
359
|
logger.logMethodArgs?.("writeContext__", path);
|
|
359
|
-
return (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.
|
|
360
|
+
return (0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config.rootPath, path), context);
|
|
360
361
|
}
|
|
361
362
|
/**
|
|
362
363
|
* Write nitrobase file context.
|
|
@@ -381,16 +382,16 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
381
382
|
*/
|
|
382
383
|
loadRootDb__() {
|
|
383
384
|
logger.logMethod?.("loadRootDb__");
|
|
384
|
-
const fullPath = (0, import_node_fs.resolve)(this.
|
|
385
|
+
const fullPath = (0, import_node_fs.resolve)(this.config.rootPath, (0, import_nitrobase_helper.getStorePath)(_AlwatrNitrobase.rootDbStat__));
|
|
385
386
|
if (!(0, import_node_fs.existsSync)(fullPath)) {
|
|
386
|
-
if (this.
|
|
387
|
+
if (this.config.errorWhenNotInitialized === true) {
|
|
387
388
|
throw new Error("store_not_found", { cause: "Nitrobase not initialized" });
|
|
388
389
|
}
|
|
389
390
|
logger.banner("Initialize new alwatr-nitrobase");
|
|
390
|
-
return import_nitrobase_reference.CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__,
|
|
391
|
+
return import_nitrobase_reference.CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__, this.storeChanged_);
|
|
391
392
|
}
|
|
392
393
|
const context = (0, import_node_fs.readJson)(fullPath, true);
|
|
393
|
-
return import_nitrobase_reference.CollectionReference.newRefFromContext(context, this.storeChanged_
|
|
394
|
+
return import_nitrobase_reference.CollectionReference.newRefFromContext(context, this.storeChanged_, "root-db");
|
|
394
395
|
}
|
|
395
396
|
/**
|
|
396
397
|
* Save all nitrobase files.
|
|
@@ -401,7 +402,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
401
402
|
logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);
|
|
402
403
|
if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {
|
|
403
404
|
logger.incident?.("exitHook__", "rescue_unsaved_context", { id: ref.id });
|
|
404
|
-
(0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.
|
|
405
|
+
(0, import_node_fs.writeJson)((0, import_node_fs.resolve)(this.config.rootPath, ref.path), ref.getFullContext_(), true);
|
|
405
406
|
ref.hasUnprocessedChanges_ = false;
|
|
406
407
|
}
|
|
407
408
|
}
|
|
@@ -427,7 +428,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
427
428
|
*
|
|
428
429
|
* Use for nitrobase file format version for check compatibility.
|
|
429
430
|
*/
|
|
430
|
-
_AlwatrNitrobase.version = "7.4
|
|
431
|
+
_AlwatrNitrobase.version = "7.5.4";
|
|
431
432
|
/**
|
|
432
433
|
* The root nitrobase file stat.
|
|
433
434
|
*/
|
package/dist/main.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/main.ts", "../src/alwatr-nitrobase.ts", "../src/logger.ts"],
|
|
4
|
-
"sourcesContent": ["export * from './alwatr-nitrobase.js';\n", "import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config__ The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(private readonly config__: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config__);\n this.config__.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<T extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: DocumentContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n initialData,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the collection\n * @template TItem collection item data type\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection<TItem extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: CollectionContext<TItem>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n },\n initialData,\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n */\n newStoreFile_<T extends JsonObject = JsonObject>(\n stat: StoreFileStat,\n initialData: DocumentContext<T>['data'] | CollectionContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config__.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n fileStoreRef = DocumentReference.newRefFromData(stat, initialData as DocumentContext['data'], this.storeChanged_.bind(this));\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, initialData as CollectionContext['data'], this.storeChanged_.bind(this));\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config__.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config__.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config__.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config__.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config__.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, null, this.storeChanged_.bind(this));\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this), 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config__.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAoB;AACpB,uBAAuB;AACvB,qBAA+D;AAC/D,8BAAuC;AACvC,iCAAqD;AACrD,6BAUO;;;ACfP,qBAA0C;AAE1C,aAAc,8BAAc,IAAI,4BAAkB,OAAmB;AAE9D,IAAM,SAAyB,iDAAa,0BAAgB;;;ADenE,aAAc,QAAO,gBAAgB,kBAAkB;AAgChD,IAAM,mBAAN,MAAM,iBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0C3B,
|
|
4
|
+
"sourcesContent": ["export * from './alwatr-nitrobase.js';\n", "import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(readonly config: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config);\n this.config.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n this.storeChanged_ = this.storeChanged_.bind(this);\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n data,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection(stat: Omit<StoreFileStat, 'type'>): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n }\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n */\n newStoreFile_(\n stat: StoreFileStat,\n data?: DictionaryOpt,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n if (data === undefined) {\n logger.accident('newStoreFile_', 'document_data_required', stat);\n throw new Error('document_data_required', {cause: stat});\n }\n fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_);\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_);\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, this.storeChanged_);\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_, 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAoB;AACpB,uBAAuB;AACvB,qBAA+D;AAC/D,8BAAuC;AACvC,iCAAqD;AACrD,6BAUO;;;ACfP,qBAA0C;AAE1C,aAAc,8BAAc,IAAI,4BAAkB,OAAmB;AAE9D,IAAM,SAAyB,iDAAa,0BAAgB;;;ADenE,aAAc,QAAO,gBAAgB,kBAAkB;AAgChD,IAAM,mBAAN,MAAM,iBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0C3B,YAAqB,QAA+B;AAA/B;AAdrB;AAAA;AAAA;AAAA,SAAQ,oBAA4E,CAAC;AA/EvF;AA8FI,WAAO,gBAAgB,OAAO,MAAM;AACpC,eAAK,QAAO,0BAAZ,GAAY,wBAA0B;AACtC,SAAK,WAAW,KAAK,aAAa;AAClC,SAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;AACjD,mCAAS,KAAK,WAAW,KAAK,IAAI,CAAC;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,SAAS,SAA+B;AACtC,UAAM,UAAM,oCAAW,OAAO;AAC9B,UAAM,SAAS,KAAK,SAAS,QAAQ,GAAG;AACxC,WA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*/
|
|
2
2
|
|
|
3
3
|
// src/alwatr-nitrobase.ts
|
|
4
4
|
import { delay } from "@alwatr/nanolib";
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
|
|
15
15
|
// src/logger.ts
|
|
16
16
|
import { createLogger, packageTracer } from "@alwatr/nanolib";
|
|
17
|
-
__dev_mode__: packageTracer.add("@alwatr/nitrobase-engine", "7.4
|
|
17
|
+
__dev_mode__: packageTracer.add("@alwatr/nitrobase-engine", "7.5.4");
|
|
18
18
|
var logger = /* @__PURE__ */ createLogger("@alwatr/nitrobase-engine");
|
|
19
19
|
|
|
20
20
|
// src/alwatr-nitrobase.ts
|
|
@@ -23,7 +23,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
23
23
|
/**
|
|
24
24
|
* Constructs an AlwatrNitrobase instance with the provided configuration.
|
|
25
25
|
*
|
|
26
|
-
* @param
|
|
26
|
+
* @param config The configuration of the AlwatrNitrobase engine.
|
|
27
27
|
* @example
|
|
28
28
|
* ```typescript
|
|
29
29
|
* const alwatrStore = new AlwatrNitrobase({
|
|
@@ -32,16 +32,17 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
32
32
|
* });
|
|
33
33
|
* ```
|
|
34
34
|
*/
|
|
35
|
-
constructor(
|
|
36
|
-
this.
|
|
35
|
+
constructor(config) {
|
|
36
|
+
this.config = config;
|
|
37
37
|
/**
|
|
38
38
|
* Keep all loaded nitrobase file context loaded in memory.
|
|
39
39
|
*/
|
|
40
40
|
this.cacheReferences__ = {};
|
|
41
41
|
var _a;
|
|
42
|
-
logger.logMethodArgs?.("new",
|
|
43
|
-
(_a = this.
|
|
42
|
+
logger.logMethodArgs?.("new", config);
|
|
43
|
+
(_a = this.config).defaultChangeDebounce ?? (_a.defaultChangeDebounce = 40);
|
|
44
44
|
this.rootDb__ = this.loadRootDb__();
|
|
45
|
+
this.storeChanged_ = this.storeChanged_.bind(this);
|
|
45
46
|
exitHook(this.exitHook__.bind(this));
|
|
46
47
|
}
|
|
47
48
|
/**
|
|
@@ -67,7 +68,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
67
68
|
* If a document with the same ID already exists, an error is thrown.
|
|
68
69
|
*
|
|
69
70
|
* @param stat nitrobase file stat
|
|
70
|
-
* @param
|
|
71
|
+
* @param data initial data for the document
|
|
71
72
|
* @template TDoc document data type
|
|
72
73
|
* @example
|
|
73
74
|
* ```typescript
|
|
@@ -84,14 +85,14 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
84
85
|
* );
|
|
85
86
|
* ```
|
|
86
87
|
*/
|
|
87
|
-
newDocument(stat,
|
|
88
|
+
newDocument(stat, data) {
|
|
88
89
|
logger.logMethodArgs?.("newDocument", stat);
|
|
89
90
|
return this.newStoreFile_(
|
|
90
91
|
{
|
|
91
92
|
...stat,
|
|
92
93
|
type: StoreFileType.Document
|
|
93
94
|
},
|
|
94
|
-
|
|
95
|
+
data
|
|
95
96
|
);
|
|
96
97
|
}
|
|
97
98
|
/**
|
|
@@ -99,8 +100,6 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
99
100
|
* If a collection with the same ID already exists, an error is thrown.
|
|
100
101
|
*
|
|
101
102
|
* @param stat nitrobase file stat
|
|
102
|
-
* @param initialData initial data for the collection
|
|
103
|
-
* @template TItem collection item data type
|
|
104
103
|
* @example
|
|
105
104
|
* ```typescript
|
|
106
105
|
* await alwatrStore.newCollection<Order>(
|
|
@@ -112,31 +111,33 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
112
111
|
* );
|
|
113
112
|
* ```
|
|
114
113
|
*/
|
|
115
|
-
newCollection(stat
|
|
114
|
+
newCollection(stat) {
|
|
116
115
|
logger.logMethodArgs?.("newCollection", stat);
|
|
117
116
|
return this.newStoreFile_(
|
|
118
117
|
{
|
|
119
118
|
...stat,
|
|
120
119
|
type: StoreFileType.Collection
|
|
121
|
-
}
|
|
122
|
-
initialData
|
|
120
|
+
}
|
|
123
121
|
);
|
|
124
122
|
}
|
|
125
123
|
/**
|
|
126
124
|
* Defines a AlwatrNitrobaseFile with the given configuration and initial data.
|
|
127
125
|
*
|
|
128
126
|
* @param stat nitrobase file stat
|
|
129
|
-
* @param
|
|
130
|
-
* @template TDoc document data type
|
|
127
|
+
* @param data initial data for the document
|
|
131
128
|
*/
|
|
132
|
-
newStoreFile_(stat,
|
|
129
|
+
newStoreFile_(stat, data) {
|
|
133
130
|
logger.logMethodArgs?.("newStoreFile_", stat);
|
|
134
|
-
stat.changeDebounce ?? (stat.changeDebounce = this.
|
|
131
|
+
stat.changeDebounce ?? (stat.changeDebounce = this.config.defaultChangeDebounce);
|
|
135
132
|
let fileStoreRef;
|
|
136
133
|
if (stat.type === StoreFileType.Document) {
|
|
137
|
-
|
|
134
|
+
if (data === void 0) {
|
|
135
|
+
logger.accident("newStoreFile_", "document_data_required", stat);
|
|
136
|
+
throw new Error("document_data_required", { cause: stat });
|
|
137
|
+
}
|
|
138
|
+
fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);
|
|
138
139
|
} else if (stat.type === StoreFileType.Collection) {
|
|
139
|
-
fileStoreRef = CollectionReference.newRefFromData(stat,
|
|
140
|
+
fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);
|
|
140
141
|
} else {
|
|
141
142
|
logger.accident("newStoreFile_", "store_file_type_not_supported", stat);
|
|
142
143
|
throw new Error("store_file_type_not_supported", { cause: stat });
|
|
@@ -187,7 +188,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
187
188
|
throw new Error("document_wrong_type", { cause: id });
|
|
188
189
|
}
|
|
189
190
|
const context = await this.readContext__(storeStat);
|
|
190
|
-
const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_
|
|
191
|
+
const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_);
|
|
191
192
|
this.cacheReferences__[id] = docRef;
|
|
192
193
|
return docRef;
|
|
193
194
|
}
|
|
@@ -229,7 +230,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
229
230
|
throw new Error("collection_not_found", { cause: id });
|
|
230
231
|
}
|
|
231
232
|
const context = await this.readContext__(storeStat);
|
|
232
|
-
const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_
|
|
233
|
+
const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_);
|
|
233
234
|
this.cacheReferences__[id] = colRef;
|
|
234
235
|
return colRef;
|
|
235
236
|
}
|
|
@@ -286,7 +287,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
286
287
|
this.rootDb__.removeItem(id_);
|
|
287
288
|
await delay.by(0);
|
|
288
289
|
try {
|
|
289
|
-
await unlink(resolve(this.
|
|
290
|
+
await unlink(resolve(this.config.rootPath, path));
|
|
290
291
|
} catch (error) {
|
|
291
292
|
logger.error("removeStore", "remove_file_failed", error, { id: storeId, path });
|
|
292
293
|
}
|
|
@@ -319,7 +320,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
319
320
|
if (typeof path !== "string") path = getStorePath(path);
|
|
320
321
|
logger.logMethodArgs?.("readContext__", path);
|
|
321
322
|
logger.time?.(`readContext__time(${path})`);
|
|
322
|
-
const context = await readJson(resolve(this.
|
|
323
|
+
const context = await readJson(resolve(this.config.rootPath, path));
|
|
323
324
|
logger.timeEnd?.(`readContext__time(${path})`);
|
|
324
325
|
return context;
|
|
325
326
|
}
|
|
@@ -335,7 +336,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
335
336
|
writeContext__(path, context) {
|
|
336
337
|
if (typeof path !== "string") path = getStorePath(path);
|
|
337
338
|
logger.logMethodArgs?.("writeContext__", path);
|
|
338
|
-
return writeJson(resolve(this.
|
|
339
|
+
return writeJson(resolve(this.config.rootPath, path), context);
|
|
339
340
|
}
|
|
340
341
|
/**
|
|
341
342
|
* Write nitrobase file context.
|
|
@@ -360,16 +361,16 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
360
361
|
*/
|
|
361
362
|
loadRootDb__() {
|
|
362
363
|
logger.logMethod?.("loadRootDb__");
|
|
363
|
-
const fullPath = resolve(this.
|
|
364
|
+
const fullPath = resolve(this.config.rootPath, getStorePath(_AlwatrNitrobase.rootDbStat__));
|
|
364
365
|
if (!existsSync(fullPath)) {
|
|
365
|
-
if (this.
|
|
366
|
+
if (this.config.errorWhenNotInitialized === true) {
|
|
366
367
|
throw new Error("store_not_found", { cause: "Nitrobase not initialized" });
|
|
367
368
|
}
|
|
368
369
|
logger.banner("Initialize new alwatr-nitrobase");
|
|
369
|
-
return CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__,
|
|
370
|
+
return CollectionReference.newRefFromData(_AlwatrNitrobase.rootDbStat__, this.storeChanged_);
|
|
370
371
|
}
|
|
371
372
|
const context = readJson(fullPath, true);
|
|
372
|
-
return CollectionReference.newRefFromContext(context, this.storeChanged_
|
|
373
|
+
return CollectionReference.newRefFromContext(context, this.storeChanged_, "root-db");
|
|
373
374
|
}
|
|
374
375
|
/**
|
|
375
376
|
* Save all nitrobase files.
|
|
@@ -380,7 +381,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
380
381
|
logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);
|
|
381
382
|
if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {
|
|
382
383
|
logger.incident?.("exitHook__", "rescue_unsaved_context", { id: ref.id });
|
|
383
|
-
writeJson(resolve(this.
|
|
384
|
+
writeJson(resolve(this.config.rootPath, ref.path), ref.getFullContext_(), true);
|
|
384
385
|
ref.hasUnprocessedChanges_ = false;
|
|
385
386
|
}
|
|
386
387
|
}
|
|
@@ -406,7 +407,7 @@ var _AlwatrNitrobase = class _AlwatrNitrobase {
|
|
|
406
407
|
*
|
|
407
408
|
* Use for nitrobase file format version for check compatibility.
|
|
408
409
|
*/
|
|
409
|
-
_AlwatrNitrobase.version = "7.4
|
|
410
|
+
_AlwatrNitrobase.version = "7.5.4";
|
|
410
411
|
/**
|
|
411
412
|
* The root nitrobase file stat.
|
|
412
413
|
*/
|
package/dist/main.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/alwatr-nitrobase.ts", "../src/logger.ts"],
|
|
4
|
-
"sourcesContent": ["import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config__ The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(private readonly config__: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config__);\n this.config__.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<T extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: DocumentContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n initialData,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the collection\n * @template TItem collection item data type\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection<TItem extends JsonObject = JsonObject>(\n stat: Omit<StoreFileStat, 'type'>,\n initialData: CollectionContext<TItem>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n },\n initialData,\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param initialData initial data for the document\n * @template TDoc document data type\n */\n newStoreFile_<T extends JsonObject = JsonObject>(\n stat: StoreFileStat,\n initialData: DocumentContext<T>['data'] | CollectionContext<T>['data'] | null = null,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config__.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n fileStoreRef = DocumentReference.newRefFromData(stat, initialData as DocumentContext['data'], this.storeChanged_.bind(this));\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, initialData as CollectionContext['data'], this.storeChanged_.bind(this));\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this));\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config__.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config__.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config__.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config__.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config__.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, null, this.storeChanged_.bind(this));\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_.bind(this), 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config__.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
|
|
5
|
-
"mappings": ";;;AAAA,SAAQ,aAAY;AACpB,SAAQ,gBAAe;AACvB,SAAQ,YAAY,UAAU,SAAS,QAAQ,iBAAgB;AAC/D,SAAQ,YAAY,oBAAmB;AACvC,SAAQ,qBAAqB,yBAAwB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;;;ACfP,SAAQ,cAAc,qBAAoB;AAE1C,aAAc,eAAc,IAAI,4BAAkB,OAAmB;AAE9D,IAAM,SAAyB,6BAAa,0BAAgB;;;ADenE,aAAc,QAAO,gBAAgB,kBAAkB;AAgChD,IAAM,mBAAN,MAAM,iBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0C3B,
|
|
4
|
+
"sourcesContent": ["import {delay} from '@alwatr/nanolib';\nimport {exitHook} from '@alwatr/nanolib/exit-hook';\nimport {existsSync, readJson, resolve, unlink, writeJson} from '@alwatr/nanolib/node-fs';\nimport {getStoreId, getStorePath} from '@alwatr/nitrobase-helper';\nimport {CollectionReference, DocumentReference} from '@alwatr/nitrobase-reference';\nimport {\n StoreFileType,\n StoreFileExtension,\n Region,\n type StoreFileStat,\n type StoreFileContext,\n type CollectionContext,\n type DocumentContext,\n type StoreFileId,\n type CollectionItem,\n} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\n__dev_mode__: logger.logFileModule?.('alwatr-nitrobase');\n\n/**\n * AlwatrNitrobase configuration.\n */\nexport interface AlwatrNitrobaseConfig {\n /**\n * The root path of the storage.\n * This is where the AlwatrNitrobase will nitrobase its data.\n */\n rootPath: string;\n\n /**\n * The save debounce timeout in milliseconds for minimal disk I/O usage.\n * This is used to limit the frequency of disk writes for performance reasons.\n * The recommended value is `40`.\n */\n defaultChangeDebounce?: number;\n\n /**\n * If true, an error will be thrown when trying to read or write to a nitrobase file that is not initialized (new storage).\n * The default value is `false` but highly recommended to set it to `true` in production to prevent data loss.\n */\n errorWhenNotInitialized?: boolean;\n}\n\n/**\n * AlwatrNitrobase engine.\n *\n * It provides methods to read, write, validate, and manage nitrobase files.\n * It also provides methods to interact with `documents` and `collections` in the nitrobase.\n */\nexport class AlwatrNitrobase {\n /**\n * The Alwatr Nitrobase version string.\n *\n * Use for nitrobase file format version for check compatibility.\n */\n static readonly version = __package_version__;\n\n /**\n * The root nitrobase file stat.\n */\n private static readonly rootDbStat__: StoreFileStat = {\n name: '.nitrobase',\n region: Region.Secret,\n type: StoreFileType.Collection,\n extension: StoreFileExtension.Json,\n changeDebounce: 40,\n };\n\n /**\n * `collectionReference` of all `storeFileStat`s.\n * This is the root nitrobase collection.\n */\n private rootDb__;\n\n /**\n * Keep all loaded nitrobase file context loaded in memory.\n */\n private cacheReferences__: DictionaryReq<DocumentReference | CollectionReference> = {};\n\n /**\n * Constructs an AlwatrNitrobase instance with the provided configuration.\n *\n * @param config The configuration of the AlwatrNitrobase engine.\n * @example\n * ```typescript\n * const alwatrStore = new AlwatrNitrobase({\n * rootPath: './db',\n * saveDebounce: 40,\n * });\n * ```\n */\n constructor(readonly config: AlwatrNitrobaseConfig) {\n logger.logMethodArgs?.('new', config);\n this.config.defaultChangeDebounce ??= 40;\n this.rootDb__ = this.loadRootDb__();\n this.storeChanged_ = this.storeChanged_.bind(this);\n exitHook(this.exitHook__.bind(this));\n }\n\n /**\n * Checks if a nitrobase file with the given ID exists.\n *\n * @param storeId - The ID of the nitrobase file to check.\n * @returns `true` if the nitrobase file exists, `false` otherwise.\n * @example\n * ```typescript\n * if (!alwatrStore.hasStore('user1/profile')) {\n * alwatrStore.defineDocument(...)\n * }\n * ```\n */\n hasStore(storeId: StoreFileId): boolean {\n const id_ = getStoreId(storeId);\n const exists = this.rootDb__.hasItem(id_);\n logger.logMethodFull?.('hasStore', id_, exists);\n return exists;\n }\n\n /**\n * Defines a new document with the given configuration and initial data.\n * If a document with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n * @template TDoc document data type\n * @example\n * ```typescript\n * await alwatrStore.newDocument<Order>(\n * {\n * name: 'profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * },\n * {\n * name: 'Ali',\n * email: 'ali@alwatr.io',\n * }\n * );\n * ```\n */\n newDocument<TDoc extends JsonObject = JsonObject>(stat: Omit<StoreFileStat, 'type'>, data: TDoc): void {\n logger.logMethodArgs?.('newDocument', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Document,\n },\n data,\n );\n }\n\n /**\n * Defines a new collection with the given configuration and initial data.\n * If a collection with the same ID already exists, an error is thrown.\n *\n * @param stat nitrobase file stat\n * @example\n * ```typescript\n * await alwatrStore.newCollection<Order>(\n * {\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * }\n * );\n * ```\n */\n newCollection(stat: Omit<StoreFileStat, 'type'>): void {\n logger.logMethodArgs?.('newCollection', stat);\n return this.newStoreFile_(\n {\n ...stat,\n type: StoreFileType.Collection,\n }\n );\n }\n\n /**\n * Defines a AlwatrNitrobaseFile with the given configuration and initial data.\n *\n * @param stat nitrobase file stat\n * @param data initial data for the document\n */\n newStoreFile_(\n stat: StoreFileStat,\n data?: DictionaryOpt,\n ): void {\n logger.logMethodArgs?.('newStoreFile_', stat);\n\n (stat.changeDebounce as number | undefined) ??= this.config.defaultChangeDebounce;\n\n let fileStoreRef: DocumentReference | CollectionReference;\n if (stat.type === StoreFileType.Document) {\n if (data === undefined) {\n logger.accident('newStoreFile_', 'document_data_required', stat);\n throw new Error('document_data_required', {cause: stat});\n }\n fileStoreRef = DocumentReference.newRefFromData(stat, data, this.storeChanged_);\n }\n else if (stat.type === StoreFileType.Collection) {\n fileStoreRef = CollectionReference.newRefFromData(stat, this.storeChanged_);\n }\n else {\n logger.accident('newStoreFile_', 'store_file_type_not_supported', stat);\n throw new Error('store_file_type_not_supported', {cause: stat});\n }\n\n if (this.rootDb__.hasItem(fileStoreRef.id)) {\n logger.accident('newStoreFile_', 'store_file_already_defined', stat);\n throw new Error('store_file_already_defined', {cause: stat});\n }\n\n this.rootDb__.addItem(fileStoreRef.id, stat);\n this.cacheReferences__[fileStoreRef.id] = fileStoreRef;\n\n // fileStoreRef.save();\n this.storeChanged_(fileStoreRef);\n }\n\n /**\n * Open a document with the given id and create and return a DocumentReference.\n * If the document not exists or its not a document, an error is thrown.\n *\n * @template TDoc document data type\n * @param documentId document id {@link StoreFileId}\n * @returns document reference {@link DocumentReference}\n * @example\n * ```typescript\n * const userProfile = await alwatrStore.openDocument<User>({\n * name: 'user1/profile',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * userProfile.update({name: 'ali'});\n * ```\n */\n async openDocument<TDoc extends JsonObject>(documentId: StoreFileId): Promise<DocumentReference<TDoc>> {\n const id = getStoreId(documentId);\n logger.logMethodArgs?.('openDocument', id);\n\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof DocumentReference)) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as DocumentReference<TDoc>;\n }\n\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openDocument', 'document_not_found', id);\n throw new Error('document_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Document) {\n logger.accident('openDocument', 'document_wrong_type', id);\n throw new Error('document_wrong_type', {cause: id});\n }\n\n const context = await this.readContext__<DocumentContext<TDoc>>(storeStat);\n const docRef = DocumentReference.newRefFromContext(context, this.storeChanged_);\n this.cacheReferences__[id] = docRef as unknown as DocumentReference;\n return docRef;\n }\n\n /**\n * Open a collection with the given id and create and return a CollectionReference.\n * If the collection not exists or its not a collection, an error is thrown.\n *\n * @template TItem collection item data type\n * @param collectionId collection id {@link StoreFileId}\n * @returns collection reference {@link CollectionReference}\n * @example\n * ```typescript\n * const orders = await alwatrStore.openCollection<Order>({\n * name: 'orders',\n * region: Region.PerUser,\n * ownerId: 'user1',\n * });\n * orders.append({name: 'order 1'});\n * ```\n */\n async openCollection<TItem extends JsonObject>(collectionId: StoreFileId): Promise<CollectionReference<TItem>> {\n const id = getStoreId(collectionId);\n logger.logMethodArgs?.('openCollection', id);\n\n // try to get from cache\n if (Object.hasOwn(this.cacheReferences__, id)) {\n const ref = this.cacheReferences__[id];\n if (!(ref instanceof CollectionReference)) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_wrong_type', {cause: id});\n }\n return this.cacheReferences__[id] as unknown as CollectionReference<TItem>;\n }\n\n // load and create new collection reference\n if (!this.rootDb__.hasItem(id)) {\n logger.accident('openCollection', 'collection_not_found', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const storeStat = this.rootDb__.getItemData(id);\n\n if (storeStat.type != StoreFileType.Collection) {\n logger.accident('openCollection', 'collection_wrong_type', id);\n throw new Error('collection_not_found', {cause: id});\n }\n\n const context = await this.readContext__<CollectionContext<TItem>>(storeStat);\n const colRef = CollectionReference.newRefFromContext(context, this.storeChanged_);\n this.cacheReferences__[id] = colRef as unknown as CollectionReference;\n return colRef;\n }\n\n /**\n * Unloads the nitrobase file with the given id from memory.\n *\n * @param storeId The unique identifier of the nitrobase file. {@link StoreFileId}\n * @example\n * ```typescript\n * alwatrStore.unloadStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // true\n * ```\n */\n unloadStore(storeId: StoreFileId): void {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('unloadStore', id_);\n const ref = this.cacheReferences__[id_];\n if (ref === undefined) return;\n if (ref.hasUnprocessedChanges_ === true) {\n ref.updateDelayed_ = false;\n this.storeChanged_(ref);\n }\n delete this.cacheReferences__[id_];\n }\n\n /**\n * Remove document or collection from nitrobase and delete the file from disk.\n * If the file is not found, an error is thrown.\n * If the file is not unloaded, it will be unloaded first.\n * You don't need to await this method to complete unless you want to make sure the file is deleted on disk.\n *\n * @param storeId The ID of the file to delete. {@link StoreFileId}\n * @returns A Promise that resolves when the file is deleted.\n * @example\n * ```typescript\n * alwatrStore.removeStore({name: 'user-list', region: Region.Secret});\n * alwatrStore.hasStore({name: 'user-list', region: Region.Secret}); // false\n * ```\n */\n async removeStore(storeId: StoreFileId): Promise<void> {\n const id_ = getStoreId(storeId);\n logger.logMethodArgs?.('removeStore', id_);\n if (!this.rootDb__.hasItem(id_)) {\n logger.accident('removeStore', 'document_not_found', id_);\n throw new Error('document_not_found', {cause: id_});\n }\n const ref = this.cacheReferences__[id_];\n if (ref !== undefined) {\n // direct unload to prevent save\n ref.freeze = true;\n ref.updateDelayed_ = false;\n ref.hasUnprocessedChanges_ = false;\n delete this.cacheReferences__[id_]; // unload\n }\n const path = getStorePath(this.rootDb__.getItemData(id_));\n this.rootDb__.removeItem(id_);\n await delay.by(0);\n try {\n await unlink(resolve(this.config.rootPath, path));\n }\n catch (error) {\n logger.error('removeStore', 'remove_file_failed', error, {id: storeId, path});\n }\n }\n\n /**\n * Saves all changes in the nitrobase.\n *\n * @returns A Promise that resolves when all changes are saved.\n * @example\n * ```typescript\n * await alwatrStore.saveAll();\n * ```\n */\n async saveAll(): Promise<void> {\n logger.logMethod?.('saveAll');\n for (const ref of Object.values(this.cacheReferences__)) {\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n ref.updateDelayed_ = false;\n await this.storeChanged_(ref);\n }\n }\n }\n\n /**\n * Reads the context from a given path or StoreFileStat object.\n *\n * @param path The path or StoreFileStat object from which to read the context.\n * @returns A promise that resolves to the context object.\n */\n private async readContext__<T extends StoreFileContext>(path: string | StoreFileStat): Promise<T> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('readContext__', path);\n logger.time?.(`readContext__time(${path})`);\n const context = (await readJson(resolve(this.config.rootPath, path))) as T;\n logger.timeEnd?.(`readContext__time(${path})`);\n return context;\n }\n\n /**\n * Writes the context to the specified path.\n *\n * @template T The type of the context.\n * @param path The path where the context will be written.\n * @param context The context to be written.\n * @param sync Indicates whether the write operation should be synchronous.\n * @returns A promise that resolves when the write operation is complete.\n */\n private writeContext__<T extends StoreFileContext>(path: string | StoreFileStat, context: T): Promise<void> {\n if (typeof path !== 'string') path = getStorePath(path);\n logger.logMethodArgs?.('writeContext__', path);\n return writeJson(resolve(this.config.rootPath, path), context);\n }\n\n /**\n * Write nitrobase file context.\n *\n * @param from nitrobase file reference\n * @returns A promise that resolves when the write operation is complete.\n */\n protected async storeChanged_<T extends JsonObject>(from: DocumentReference<T> | CollectionReference<T>): Promise<void> {\n logger.logMethodArgs?.('storeChanged__', from.id);\n const rev = from.getStoreMeta().rev;\n try {\n await this.writeContext__(from.path, from.getFullContext_());\n if (rev === from.getStoreMeta().rev) {\n // Context not changed during saving\n from.hasUnprocessedChanges_ = false;\n }\n }\n catch (error) {\n logger.error('storeChanged__', 'write_context_failed', {id: from.id, error});\n }\n }\n\n /**\n * Load storeFilesCollection or create new one.\n */\n private loadRootDb__(): CollectionReference<StoreFileStat> {\n logger.logMethod?.('loadRootDb__');\n const fullPath = resolve(this.config.rootPath, getStorePath(AlwatrNitrobase.rootDbStat__));\n if (!existsSync(fullPath)) {\n if (this.config.errorWhenNotInitialized === true) {\n throw new Error('store_not_found', {cause: 'Nitrobase not initialized'});\n }\n\n logger.banner('Initialize new alwatr-nitrobase');\n return CollectionReference.newRefFromData(AlwatrNitrobase.rootDbStat__, this.storeChanged_);\n }\n // else\n const context = readJson<CollectionContext<StoreFileStat>>(fullPath, true);\n return CollectionReference.newRefFromContext(context, this.storeChanged_, 'root-db');\n }\n\n /**\n * Save all nitrobase files.\n */\n private exitHook__(): void {\n logger.logMethod?.('exitHook__');\n for (const ref of Object.values(this.cacheReferences__)) {\n logger.logProperty?.(`StoreFile.${ref.id}.hasUnprocessedChanges`, ref.hasUnprocessedChanges_);\n if (ref.hasUnprocessedChanges_ === true && ref.freeze !== true) {\n logger.incident?.('exitHook__', 'rescue_unsaved_context', {id: ref.id});\n writeJson(resolve(this.config.rootPath, ref.path), ref.getFullContext_(), true);\n ref.hasUnprocessedChanges_ = false;\n }\n }\n }\n\n /**\n * Get all nitrobase files.\n *\n * @returns all nitrobase files.\n * @example\n * ```typescript\n * const storeList = alwatrStore.getStoreList();\n * for (const nitrobase of storeList) {\n * console.log(nitrobase.meta.id, nitrobase.data);\n * }\n */\n getStoreList(): CollectionItem<Omit<StoreFileStat, 'schemaVer'>>[] {\n logger.logMethod?.('getStoreList');\n return this.rootDb__.values();\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
|
|
5
|
+
"mappings": ";;;AAAA,SAAQ,aAAY;AACpB,SAAQ,gBAAe;AACvB,SAAQ,YAAY,UAAU,SAAS,QAAQ,iBAAgB;AAC/D,SAAQ,YAAY,oBAAmB;AACvC,SAAQ,qBAAqB,yBAAwB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;;;ACfP,SAAQ,cAAc,qBAAoB;AAE1C,aAAc,eAAc,IAAI,4BAAkB,OAAmB;AAE9D,IAAM,SAAyB,6BAAa,0BAAgB;;;ADenE,aAAc,QAAO,gBAAgB,kBAAkB;AAgChD,IAAM,mBAAN,MAAM,iBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;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A,EAaA,eAAmE;AACjE,WAAO,YAAY,cAAc;AACjC,WAAO,KAAK,SAAS,OAAO;AAAA,EAC9B;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAjca,iBAMK,UAAU;AAAA;AAAA;AAAA;AANf,iBAWa,eAA8B;AAAA,EACpD,MAAM;AAAA,EACN,QAAQ,OAAO;AAAA,EACf,MAAM,cAAc;AAAA,EACpB,WAAW,mBAAmB;AAAA,EAC9B,gBAAgB;AAClB;AAjBK,IAAM,kBAAN;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alwatr/nitrobase-engine",
|
|
3
|
-
"version": "7.4
|
|
3
|
+
"version": "7.5.4",
|
|
4
4
|
"description": "Nitrobase is a blazingly fast, lightweight database built on JSON. It stores data entirely in memory for lightning-quick access, while also providing a JSON file backup for persistence. You can easily serve your data over the web using our high-performance accelerated Nginx server.",
|
|
5
5
|
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
|
|
6
6
|
"keywords": [
|
|
@@ -61,17 +61,17 @@
|
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
63
|
"@alwatr/nanolib": "^5.2.1",
|
|
64
|
-
"@alwatr/nitrobase-helper": "^7.4
|
|
65
|
-
"@alwatr/nitrobase-reference": "^7.4
|
|
66
|
-
"@alwatr/nitrobase-types": "^7.4
|
|
64
|
+
"@alwatr/nitrobase-helper": "^7.5.4",
|
|
65
|
+
"@alwatr/nitrobase-reference": "^7.5.4",
|
|
66
|
+
"@alwatr/nitrobase-types": "^7.5.4"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
69
|
"@alwatr/nano-build": "^5.0.0",
|
|
70
70
|
"@alwatr/prettier-config": "^5.0.0",
|
|
71
71
|
"@alwatr/tsconfig-base": "^5.0.0",
|
|
72
72
|
"@alwatr/type-helper": "^5.0.0",
|
|
73
|
-
"@types/node": "^22.
|
|
74
|
-
"typescript": "^5.
|
|
73
|
+
"@types/node": "^22.10.5",
|
|
74
|
+
"typescript": "^5.7.3"
|
|
75
75
|
},
|
|
76
|
-
"gitHead": "
|
|
76
|
+
"gitHead": "a80d61632fce6c1e8ff9380aa58bfe9c9d5cb507"
|
|
77
77
|
}
|