@ddd-ts/store-inmemory 0.0.0-compute-timeout-on-process.2 → 0.0.0-compute-timeout-on-process.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.
@@ -0,0 +1,22 @@
1
+ import { InMemoryDatabase, InMemoryUnderlyingTransaction } from "./store/in-memory.database.js";
2
+ import { TransactionPerformer } from "@ddd-ts/core";
3
+
4
+ //#region src/in-memory.transaction.d.ts
5
+ declare class InMemoryTransaction {
6
+ readonly transaction: InMemoryUnderlyingTransaction;
7
+ commitListeners: (() => void)[];
8
+ constructor(transaction: InMemoryUnderlyingTransaction);
9
+ counter: number;
10
+ increment(): number;
11
+ onCommit(callback: () => void): void;
12
+ executeCommitListeners(): Promise<void>;
13
+ }
14
+ declare class InMemoryTransactionPerformer extends TransactionPerformer<InMemoryTransaction> {
15
+ constructor(db: InMemoryDatabase);
16
+ }
17
+ declare class FakeInMemoryTransactionPerformer extends TransactionPerformer<InMemoryTransaction> {
18
+ constructor();
19
+ }
20
+ //#endregion
21
+ export { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer };
22
+ //# sourceMappingURL=in-memory.transaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.transaction.d.ts","names":[],"sources":["../src/in-memory.transaction.ts"],"mappings":";;;;cAMa,mBAAA;EAAA,SAGiB,WAAA,EAAa,6BAAA;EAFzC,eAAA;cAE4B,WAAA,EAAa,6BAAA;EAEzC,OAAA;EAEA,SAAA,CAAA;EAKA,QAAA,CAAS,QAAA;EAIH,sBAAA,CAAA,GAAsB,OAAA;AAAA;AAAA,cAKjB,4BAAA,SAAqC,oBAAA,CAAqB,mBAAA;cACzD,EAAA,EAAI,gBAAA;AAAA;AAAA,cAKL,gCAAA,SAAyC,oBAAA,CAAqB,mBAAA"}
@@ -0,0 +1,34 @@
1
+ import { TransactionPerformer } from "@ddd-ts/core";
2
+
3
+ //#region src/in-memory.transaction.ts
4
+ var InMemoryTransaction = class {
5
+ commitListeners = [];
6
+ constructor(transaction) {
7
+ this.transaction = transaction;
8
+ }
9
+ counter = -1;
10
+ increment() {
11
+ this.counter++;
12
+ return this.counter;
13
+ }
14
+ onCommit(callback) {
15
+ this.commitListeners.push(callback);
16
+ }
17
+ async executeCommitListeners() {
18
+ await Promise.all(this.commitListeners.map((cb) => cb()));
19
+ }
20
+ };
21
+ var InMemoryTransactionPerformer = class extends TransactionPerformer {
22
+ constructor(db) {
23
+ super((effect) => db.transactionally((trx) => effect(trx)));
24
+ }
25
+ };
26
+ var FakeInMemoryTransactionPerformer = class extends TransactionPerformer {
27
+ constructor() {
28
+ super((effect) => effect(new InMemoryTransaction(null)));
29
+ }
30
+ };
31
+
32
+ //#endregion
33
+ export { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer };
34
+ //# sourceMappingURL=in-memory.transaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.transaction.js","names":[],"sources":["../src/in-memory.transaction.ts"],"sourcesContent":["import { TransactionPerformer } from \"@ddd-ts/core\";\nimport {\n InMemoryDatabase,\n InMemoryUnderlyingTransaction,\n} from \"./store/in-memory.database\";\n\nexport class InMemoryTransaction {\n commitListeners: (() => void)[] = [];\n\n constructor(public readonly transaction: InMemoryUnderlyingTransaction) {}\n\n counter = -1;\n\n increment() {\n this.counter++;\n return this.counter;\n }\n\n onCommit(callback: () => void) {\n this.commitListeners.push(callback);\n }\n\n async executeCommitListeners() {\n await Promise.all(this.commitListeners.map((cb) => cb()));\n }\n}\n\nexport class InMemoryTransactionPerformer extends TransactionPerformer<InMemoryTransaction> {\n constructor(db: InMemoryDatabase) {\n super((effect) => db.transactionally((trx) => effect(trx)));\n }\n}\n\nexport class FakeInMemoryTransactionPerformer extends TransactionPerformer<InMemoryTransaction> {\n constructor() {\n super((effect) => effect(new InMemoryTransaction(null as any)));\n }\n}\n"],"mappings":";;;AAMA,IAAa,sBAAb,MAAiC;CAC/B,kBAAkC,EAAE;CAEpC,YAAY,AAAgB,aAA4C;EAA5C;;CAE5B,UAAU;CAEV,YAAY;AACV,OAAK;AACL,SAAO,KAAK;;CAGd,SAAS,UAAsB;AAC7B,OAAK,gBAAgB,KAAK,SAAS;;CAGrC,MAAM,yBAAyB;AAC7B,QAAM,QAAQ,IAAI,KAAK,gBAAgB,KAAK,OAAO,IAAI,CAAC,CAAC;;;AAI7D,IAAa,+BAAb,cAAkD,qBAA0C;CAC1F,YAAY,IAAsB;AAChC,SAAO,WAAW,GAAG,iBAAiB,QAAQ,OAAO,IAAI,CAAC,CAAC;;;AAI/D,IAAa,mCAAb,cAAsD,qBAA0C;CAC9F,cAAc;AACZ,SAAO,WAAW,OAAO,IAAI,oBAAoB,KAAY,CAAC,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { CannotReadAfterWrites, InMemoryDatabase, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes } from "./store/in-memory.database.js";
2
+ import { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer } from "./in-memory.transaction.js";
3
+ import { InMemoryStore } from "./store/in-memory.store.js";
4
+ export { CannotReadAfterWrites, FakeInMemoryTransactionPerformer, InMemoryDatabase, InMemoryStore, InMemoryTransaction, InMemoryTransactionPerformer, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer } from "./in-memory.transaction.js";
2
+ import { CannotReadAfterWrites, InMemoryDatabase, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes } from "./store/in-memory.database.js";
3
+ import { InMemoryStore } from "./store/in-memory.store.js";
4
+
5
+ export { CannotReadAfterWrites, FakeInMemoryTransactionPerformer, InMemoryDatabase, InMemoryStore, InMemoryTransaction, InMemoryTransactionPerformer, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
@@ -0,0 +1,32 @@
1
+ //#region src/store/in-memory.collection.d.ts
2
+ declare class Collection {
3
+ private data;
4
+ constructor(data?: Map<string, {
5
+ savedAt: bigint;
6
+ data: any;
7
+ }>);
8
+ clear(): void;
9
+ getLatestSnapshot(id: string): any;
10
+ clone(): Collection;
11
+ merge(other: Collection): Collection;
12
+ delete(id: string): void;
13
+ getRaw(id: string): {
14
+ savedAt: bigint;
15
+ data: any;
16
+ } | undefined;
17
+ countAll(): number;
18
+ get(id: string): any;
19
+ getAllRaw(): {
20
+ id: string;
21
+ data: {
22
+ savedAt: bigint;
23
+ data: any;
24
+ };
25
+ }[];
26
+ getAll(): any[];
27
+ save(id: string, data: any): void;
28
+ toPretty(): string;
29
+ }
30
+ //#endregion
31
+ export { Collection };
32
+ //# sourceMappingURL=in-memory.collection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.collection.d.ts","names":[],"sources":["../../src/store/in-memory.collection.ts"],"mappings":";cAOa,UAAA;EAAA,QAED,IAAA;cAAA,IAAA,GAAM,GAAA;IAAc,OAAA;IAAiB,IAAA;EAAA;EAG/C,KAAA,CAAA;EAIA,iBAAA,CAAkB,EAAA;EAOlB,KAAA,CAAA,GAAK,UAAA;EAQL,KAAA,CAAM,KAAA,EAAO,UAAA,GAAU,UAAA;EAWvB,MAAA,CAAO,EAAA;EAIP,MAAA,CAAO,EAAA;;;;EAIP,QAAA,CAAA;EAIA,GAAA,CAAI,EAAA;EAIJ,SAAA,CAAA;;;;;;;EAIA,MAAA,CAAA;EAIA,IAAA,CAAK,EAAA,UAAY,IAAA;EAIjB,QAAA,CAAA;AAAA"}
@@ -0,0 +1,65 @@
1
+ //#region src/store/in-memory.collection.ts
2
+ function now() {
3
+ if (typeof process === "object" && typeof process.hrtime === "function") return process.hrtime.bigint() / BigInt(1e3);
4
+ return BigInt(Date.now() * 1e3);
5
+ }
6
+ var Collection = class Collection {
7
+ constructor(data = /* @__PURE__ */ new Map()) {
8
+ this.data = data;
9
+ }
10
+ clear() {
11
+ this.data.clear();
12
+ }
13
+ getLatestSnapshot(id) {
14
+ return [...this.data.values()].filter((d) => d.data.id === id).sort((a, b) => b.savedAt > a.savedAt ? 1 : -1)[0]?.data;
15
+ }
16
+ clone() {
17
+ const clone = /* @__PURE__ */ new Map();
18
+ for (const [key, value] of this.data) clone.set(key, value);
19
+ return new Collection(clone);
20
+ }
21
+ merge(other) {
22
+ const merge = /* @__PURE__ */ new Map();
23
+ for (const [key, value] of this.data) merge.set(key, value);
24
+ for (const [key, value] of other.data) merge.set(key, value);
25
+ return new Collection(merge);
26
+ }
27
+ delete(id) {
28
+ this.data.delete(id);
29
+ }
30
+ getRaw(id) {
31
+ return this.data.get(id);
32
+ }
33
+ countAll() {
34
+ return this.data.size;
35
+ }
36
+ get(id) {
37
+ return this.data.get(id)?.data;
38
+ }
39
+ getAllRaw() {
40
+ return [...this.data.entries()].map(([id, data]) => ({
41
+ id,
42
+ data
43
+ }));
44
+ }
45
+ getAll() {
46
+ return [...this.data.entries()].map(([id, data]) => data.data);
47
+ }
48
+ save(id, data) {
49
+ this.data.set(id, {
50
+ savedAt: now(),
51
+ data
52
+ });
53
+ }
54
+ toPretty() {
55
+ return [...this.data.entries()].map(([id, data]) => `\t\t"${id}": ${JSON.stringify(data.data, replaceBigInt)}`).join(",\n");
56
+ }
57
+ };
58
+ function replaceBigInt(key, value) {
59
+ if (typeof value === "bigint") return value.toString();
60
+ return value;
61
+ }
62
+
63
+ //#endregion
64
+ export { Collection };
65
+ //# sourceMappingURL=in-memory.collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.collection.js","names":[],"sources":["../../src/store/in-memory.collection.ts"],"sourcesContent":["function now() {\n if (typeof process === \"object\" && typeof process.hrtime === \"function\") {\n return process.hrtime.bigint() / BigInt(1000);\n }\n return BigInt(Date.now() * 1_000);\n}\n\nexport class Collection {\n constructor(\n private data: Map<string, { savedAt: bigint; data: any }> = new Map(),\n ) {}\n\n clear() {\n this.data.clear();\n }\n\n getLatestSnapshot(id: string) {\n const data = [...this.data.values()];\n const sameId = data.filter((d) => d.data.id === id);\n const sorted = sameId.sort((a, b) => (b.savedAt > a.savedAt ? 1 : -1));\n return sorted[0]?.data;\n }\n\n clone() {\n const clone = new Map();\n for (const [key, value] of this.data) {\n clone.set(key, value);\n }\n return new Collection(clone);\n }\n\n merge(other: Collection) {\n const merge = new Map();\n for (const [key, value] of this.data) {\n merge.set(key, value);\n }\n for (const [key, value] of other.data) {\n merge.set(key, value);\n }\n return new Collection(merge);\n }\n\n delete(id: string): void {\n this.data.delete(id);\n }\n\n getRaw(id: string) {\n return this.data.get(id);\n }\n\n countAll() {\n return this.data.size;\n }\n\n get(id: string): any {\n return this.data.get(id)?.data;\n }\n\n getAllRaw() {\n return [...this.data.entries()].map(([id, data]) => ({ id, data }));\n }\n\n getAll(): any[] {\n return [...this.data.entries()].map(([id, data]) => data.data);\n }\n\n save(id: string, data: any): void {\n this.data.set(id, { savedAt: now(), data });\n }\n\n toPretty() {\n return [...this.data.entries()]\n .map(\n ([id, data]) =>\n `\\t\\t\"${id}\": ${JSON.stringify(data.data, replaceBigInt)}`,\n )\n .join(\",\\n\");\n }\n}\n\nfunction replaceBigInt(key: string, value: any) {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n}\n"],"mappings":";AAAA,SAAS,MAAM;AACb,KAAI,OAAO,YAAY,YAAY,OAAO,QAAQ,WAAW,WAC3D,QAAO,QAAQ,OAAO,QAAQ,GAAG,OAAO,IAAK;AAE/C,QAAO,OAAO,KAAK,KAAK,GAAG,IAAM;;AAGnC,IAAa,aAAb,MAAa,WAAW;CACtB,YACE,AAAQ,uBAAoD,IAAI,KAAK,EACrE;EADQ;;CAGV,QAAQ;AACN,OAAK,KAAK,OAAO;;CAGnB,kBAAkB,IAAY;AAI5B,SAHa,CAAC,GAAG,KAAK,KAAK,QAAQ,CAAC,CAChB,QAAQ,MAAM,EAAE,KAAK,OAAO,GAAG,CAC7B,MAAM,GAAG,MAA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+1,71 @@
1
+ import { Storage } from "./in-memory.storage.js";
2
+ import { InMemoryTransaction } from "../in-memory.transaction.js";
3
+ import "../index.js";
4
+ import { ConcurrencyError } from "@ddd-ts/core";
5
+
6
+ //#region src/store/in-memory.database.d.ts
7
+ declare class CannotReadAfterWrites extends Error {
8
+ constructor();
9
+ }
10
+ declare class TransactionCollidedTooManyTimes extends Error {
11
+ constructor(tries: number);
12
+ }
13
+ type ReadOperation = {
14
+ type: "read";
15
+ collectionName: string;
16
+ id: string;
17
+ savedAt: bigint | undefined;
18
+ };
19
+ type WriteOperation = {
20
+ type: "write";
21
+ collectionName: string;
22
+ id: string;
23
+ data: any;
24
+ };
25
+ type CreateOperation = {
26
+ type: "create";
27
+ collectionName: string;
28
+ id: string;
29
+ data: any;
30
+ };
31
+ type DeleteOperation = {
32
+ type: "delete";
33
+ collectionName: string;
34
+ id: string;
35
+ savedAt: bigint | undefined;
36
+ };
37
+ type TransactionOperation = ReadOperation | WriteOperation | DeleteOperation | CreateOperation;
38
+ declare class InMemoryUnderlyingTransaction {
39
+ readonly operations: TransactionOperation[];
40
+ readonly id: string;
41
+ private ensureNoWrites;
42
+ markRead(collectionName: string, id: string, savedAt: bigint | undefined): void;
43
+ markWritten(collectionName: string, id: any, data: any): void;
44
+ markCreated(collectionName: string, id: any, data: any): void;
45
+ markDeleted(collectionName: string, id: any, savedAt: bigint | undefined): void;
46
+ checkConsistency(storage: Storage): boolean;
47
+ }
48
+ declare class InMemoryDatabase {
49
+ storage: Storage;
50
+ clear(collectionName: string): void;
51
+ load(collectionName: string, id: string, trx?: InMemoryUnderlyingTransaction): any;
52
+ delete(collectionName: string, id: string, trx?: InMemoryUnderlyingTransaction): void;
53
+ countAll(collectionName: string): number;
54
+ loadAll(collectionName: string): {
55
+ id: string;
56
+ data: {
57
+ savedAt: bigint;
58
+ data: any;
59
+ };
60
+ }[];
61
+ loadLatestSnapshot(id: string): any;
62
+ save(collectionName: string, id: string, data: any, trx?: InMemoryUnderlyingTransaction): void;
63
+ create(collectionName: string, id: string, data: any, trx?: InMemoryUnderlyingTransaction): void;
64
+ private static transactionTries;
65
+ transactionally(fn: (trx: InMemoryTransaction) => any): Promise<any>;
66
+ private streamId;
67
+ print(): void;
68
+ }
69
+ //#endregion
70
+ export { CannotReadAfterWrites, InMemoryDatabase, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
71
+ //# sourceMappingURL=in-memory.database.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.database.d.ts","names":[],"sources":["../../src/store/in-memory.database.ts"],"mappings":";;;;;;cAIa,qBAAA,SAA8B,KAAA;EAAA,WAAA,CAAA;AAAA;AAAA,cAkB9B,+BAAA,SAAwC,KAAA;cACvC,KAAA;AAAA;AAAA,KAKT,aAAA;EACH,IAAA;EACA,cAAA;EACA,EAAA;EACA,OAAA;AAAA;AAAA,KAGG,cAAA;EACH,IAAA;EACA,cAAA;EACA,EAAA;EACA,IAAA;AAAA;AAAA,KAGG,eAAA;EACH,IAAA;EACA,cAAA;EACA,EAAA;EACA,IAAA;AAAA;AAAA,KAGG,eAAA;EACH,IAAA;EACA,cAAA;EACA,EAAA;EACA,OAAA;AAAA;AAAA,KAGG,oBAAA,GACD,aAAA,GACA,cAAA,GACA,eAAA,GACA,eAAA;AAAA,cAES,6BAAA;EAAA,SACK,UAAA,EAAY,oBAAA;EAAA,SAEZ,EAAA;EAAA,QAER,cAAA;EAaD,QAAA,CACL,cAAA,UACA,EAAA,UACA,OAAA;EAMK,WAAA,CAAY,cAAA,UAAwB,EAAA,OAAS,IAAA;EAI7C,WAAA,CAAY,cAAA,UAAwB,EAAA,OAAS,IAAA;EAI7C,WAAA,CACL,cAAA,UACA,EAAA,OACA,OAAA;EAKK,gBAAA,CAAiB,OAAA,EAAS,OAAA;AAAA;AAAA,cA6BtB,gBAAA;EACJ,OAAA,EAAO,OAAA;EAEd,KAAA,CAAM,cAAA;EAIN,IAAA,CACE,cAAA,UACA,EAAA,UACA,GAAA,GAAM,6BAAA;EAWR,MAAA,CACE,cAAA,UACA,EAAA,UACA,GAAA,GAAM,6BAAA;EAUR,QAAA,CAAS,cAAA;EAIT,OAAA,CAAQ,cAAA;;;;;;;EAIR,kBAAA,CAAmB,EAAA;EAInB,IAAA,CACE,cAAA,UACA,EAAA,UACA,IAAA,OACA,GAAA,GAAM,6BAAA;EASR,MAAA,CACE,cAAA,UACA,EAAA,UACA,IAAA,OACA,GAAA,GAAM,6BAAA;EAAA,eAYO,gBAAA;EAET,eAAA,CAAgB,EAAA,GAAK,GAAA,EAAK,mBAAA,WAA2B,OAAA;EAAA,QA2BnD,QAAA;EAqBR,KAAA,CAAA;AAAA"}
@@ -0,0 +1,153 @@
1
+ import { InMemoryTransaction } from "../in-memory.transaction.js";
2
+ import { Storage } from "./in-memory.storage.js";
3
+ import "../index.js";
4
+ import { ConcurrencyError } from "@ddd-ts/core";
5
+
6
+ //#region src/store/in-memory.database.ts
7
+ var CannotReadAfterWrites = class extends Error {
8
+ constructor() {
9
+ super("Cannot read after having written into a transaction");
10
+ }
11
+ };
12
+ var TransactionCollision = class extends Error {
13
+ constructor() {
14
+ super("Transaction has collided with other extern writes");
15
+ }
16
+ };
17
+ var DocumentAlreadyExists = class extends ConcurrencyError {
18
+ constructor() {
19
+ super("Document already exists");
20
+ }
21
+ };
22
+ var TransactionCollidedTooManyTimes = class extends Error {
23
+ constructor(tries) {
24
+ super(`Transaction collided too many times (${tries})`);
25
+ }
26
+ };
27
+ var InMemoryUnderlyingTransaction = class {
28
+ operations = [];
29
+ id = Math.random().toString().substring(2);
30
+ ensureNoWrites() {
31
+ if (this.operations.some((operation) => operation.type === "write" || operation.type === "create" || operation.type === "delete")) throw new CannotReadAfterWrites();
32
+ }
33
+ markRead(collectionName, id, savedAt) {
34
+ this.ensureNoWrites();
35
+ this.operations.push({
36
+ type: "read",
37
+ collectionName,
38
+ id,
39
+ savedAt
40
+ });
41
+ }
42
+ markWritten(collectionName, id, data) {
43
+ this.operations.push({
44
+ type: "write",
45
+ collectionName,
46
+ id,
47
+ data
48
+ });
49
+ }
50
+ markCreated(collectionName, id, data) {
51
+ this.operations.push({
52
+ type: "create",
53
+ collectionName,
54
+ id,
55
+ data
56
+ });
57
+ }
58
+ markDeleted(collectionName, id, savedAt) {
59
+ this.operations.push({
60
+ type: "delete",
61
+ collectionName,
62
+ id,
63
+ savedAt
64
+ });
65
+ }
66
+ checkConsistency(storage) {
67
+ for (const operation of this.operations) {
68
+ if (operation.type === "read") {
69
+ const collection = storage.getCollection(operation.collectionName);
70
+ if (!collection) return false;
71
+ if (operation.savedAt !== collection.getRaw(operation.id)?.savedAt) return false;
72
+ }
73
+ if (operation.type === "create") {
74
+ const collection = storage.getCollection(operation.collectionName);
75
+ if (collection && collection.getRaw(operation.id)?.savedAt !== void 0) throw new DocumentAlreadyExists();
76
+ }
77
+ }
78
+ return true;
79
+ }
80
+ };
81
+ var InMemoryDatabase = class InMemoryDatabase {
82
+ storage = new Storage();
83
+ clear(collectionName) {
84
+ this.storage.getCollection(collectionName).clear();
85
+ }
86
+ load(collectionName, id, trx) {
87
+ const collection = this.storage.getCollection(collectionName);
88
+ const data = collection.get(id);
89
+ if (trx) {
90
+ const doc = collection.getRaw(id);
91
+ trx.markRead(collectionName, id, doc?.savedAt);
92
+ }
93
+ return data;
94
+ }
95
+ delete(collectionName, id, trx) {
96
+ if (trx) {
97
+ const doc = this.storage.getCollection(collectionName).getRaw(id);
98
+ trx.markDeleted(collectionName, id, doc?.savedAt);
99
+ } else this.storage.getCollection(collectionName).delete(id);
100
+ }
101
+ countAll(collectionName) {
102
+ return this.storage.getCollection(collectionName).countAll();
103
+ }
104
+ loadAll(collectionName) {
105
+ return this.storage.getCollection(collectionName).getAllRaw();
106
+ }
107
+ loadLatestSnapshot(id) {
108
+ return this.storage.getCollection("snapshots").getLatestSnapshot(id);
109
+ }
110
+ save(collectionName, id, data, trx) {
111
+ if (trx) trx.markWritten(collectionName, id, data);
112
+ else this.storage.getCollection(collectionName).save(id, data);
113
+ }
114
+ create(collectionName, id, data, trx) {
115
+ if (trx) trx.markCreated(collectionName, id, data);
116
+ else {
117
+ if (this.storage.getCollection(collectionName).get(id)) throw new Error(`Document with id ${id} already exists`);
118
+ this.storage.getCollection(collectionName).save(id, data);
119
+ }
120
+ }
121
+ static transactionTries = 5;
122
+ async transactionally(fn) {
123
+ let trx = new InMemoryTransaction(new InMemoryUnderlyingTransaction());
124
+ let retry = InMemoryDatabase.transactionTries;
125
+ let latestReturnValue = void 0;
126
+ while (retry--) try {
127
+ latestReturnValue = await fn(trx);
128
+ this.streamId(trx);
129
+ break;
130
+ } catch (error) {
131
+ if (error instanceof TransactionCollision) trx = new InMemoryTransaction(new InMemoryUnderlyingTransaction());
132
+ else throw error;
133
+ }
134
+ if (retry === -1) throw new TransactionCollidedTooManyTimes(InMemoryDatabase.transactionTries);
135
+ return latestReturnValue;
136
+ }
137
+ streamId(trx) {
138
+ if (!trx.transaction.checkConsistency(this.storage)) throw new TransactionCollision();
139
+ for (const operation of trx.transaction.operations) {
140
+ if (operation.type === "read") continue;
141
+ if (operation.type === "write") this.save(operation.collectionName, operation.id, operation.data);
142
+ if (operation.type === "delete") this.delete(operation.collectionName, operation.id);
143
+ if (operation.type === "create") this.create(operation.collectionName, operation.id, operation.data);
144
+ }
145
+ }
146
+ print() {
147
+ console.log(["Database:", this.storage.toPretty()].join("\n"));
148
+ }
149
+ };
150
+
151
+ //#endregion
152
+ export { CannotReadAfterWrites, InMemoryDatabase, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
153
+ //# sourceMappingURL=in-memory.database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.database.js","names":[],"sources":["../../src/store/in-memory.database.ts"],"sourcesContent":["import { ConcurrencyError } from \"@ddd-ts/core\";\nimport { InMemoryTransaction } from \"..\";\nimport { Storage } from \"./in-memory.storage\";\n\nexport class CannotReadAfterWrites extends Error {\n constructor() {\n super(\"Cannot read after having written into a transaction\");\n }\n}\n\nexport class TransactionCollision extends Error {\n constructor() {\n super(\"Transaction has collided with other extern writes\");\n }\n}\n\nexport class DocumentAlreadyExists extends ConcurrencyError {\n constructor() {\n super(\"Document already exists\");\n }\n}\n\nexport class TransactionCollidedTooManyTimes extends Error {\n constructor(tries: number) {\n super(`Transaction collided too many times (${tries})`);\n }\n}\n\ntype ReadOperation = {\n type: \"read\";\n collectionName: string;\n id: string;\n savedAt: bigint | undefined;\n};\n\ntype WriteOperation = {\n type: \"write\";\n collectionName: string;\n id: string;\n data: any;\n};\n\ntype CreateOperation = {\n type: \"create\";\n collectionName: string;\n id: string;\n data: any;\n};\n\ntype DeleteOperation = {\n type: \"delete\";\n collectionName: string;\n id: string;\n savedAt: bigint | undefined;\n};\n\ntype TransactionOperation =\n | ReadOperation\n | WriteOperation\n | DeleteOperation\n | CreateOperation;\n\nexport class InMemoryUnderlyingTransaction {\n public readonly operations: TransactionOperation[] = [];\n\n public readonly id = Math.random().toString().substring(2);\n\n private ensureNoWrites() {\n if (\n this.operations.some(\n (operation) =>\n operation.type === \"write\" ||\n operation.type === \"create\" ||\n operation.type === \"delete\",\n )\n ) {\n throw new CannotReadAfterWrites();\n }\n }\n\n public markRead(\n collectionName: string,\n id: string,\n savedAt: bigint | undefined,\n ) {\n this.ensureNoWrites();\n this.operations.push({ type: \"read\", collectionName, id, savedAt });\n }\n\n public markWritten(collectionName: string, id: any, data: any) {\n this.operations.push({ type: \"write\", collectionName, id, data });\n }\n\n public markCreated(collectionName: string, id: any, data: any) {\n this.operations.push({ type: \"create\", collectionName, id, data });\n }\n\n public markDeleted(\n collectionName: string,\n id: any,\n savedAt: bigint | undefined,\n ) {\n this.operations.push({ type: \"delete\", collectionName, id, savedAt });\n }\n\n public checkConsistency(storage: Storage) {\n for (const operation of this.operations) {\n if (operation.type === \"read\") {\n const collection = storage.getCollection(operation.collectionName);\n\n if (!collection) {\n return false;\n }\n\n if (operation.savedAt !== collection.getRaw(operation.id)?.savedAt) {\n return false;\n }\n }\n\n if (operation.type === \"create\") {\n const collection = storage.getCollection(operation.collectionName);\n\n if (\n collection &&\n collection.getRaw(operation.id)?.savedAt !== undefined\n ) {\n throw new DocumentAlreadyExists();\n }\n }\n }\n return true;\n }\n}\n\nexport class InMemoryDatabase {\n public storage = new Storage();\n\n clear(collectionName: string) {\n this.storage.getCollection(collectionName).clear();\n }\n\n load(\n collectionName: string,\n id: string,\n trx?: InMemoryUnderlyingTransaction,\n ): any {\n const collection = this.storage.getCollection(collectionName);\n const data = collection.get(id);\n if (trx) {\n const doc = collection.getRaw(id);\n trx.markRead(collectionName, id, doc?.savedAt);\n }\n return data;\n }\n\n delete(\n collectionName: string,\n id: string,\n trx?: InMemoryUnderlyingTransaction,\n ): void {\n if (trx) {\n const doc = this.storage.getCollection(collectionName).getRaw(id);\n trx.markDeleted(collectionName, id, doc?.savedAt);\n } else {\n this.storage.getCollection(collectionName).delete(id);\n }\n }\n\n countAll(collectionName: string) {\n return this.storage.getCollection(collectionName).countAll();\n }\n\n loadAll(collectionName: string) {\n return this.storage.getCollection(collectionName).getAllRaw();\n }\n\n loadLatestSnapshot(id: string) {\n return this.storage.getCollection(\"snapshots\").getLatestSnapshot(id);\n }\n\n save(\n collectionName: string,\n id: string,\n data: any,\n trx?: InMemoryUnderlyingTransaction,\n ): void {\n if (trx) {\n trx.markWritten(collectionName, id, data);\n } else {\n this.storage.getCollection(collectionName).save(id, data);\n }\n }\n\n create(\n collectionName: string,\n id: string,\n data: any,\n trx?: InMemoryUnderlyingTransaction,\n ): void {\n if (trx) {\n trx.markCreated(collectionName, id, data);\n } else {\n if (this.storage.getCollection(collectionName).get(id)) {\n throw new Error(`Document with id ${id} already exists`);\n }\n this.storage.getCollection(collectionName).save(id, data);\n }\n }\n\n private static transactionTries = 5;\n\n async transactionally(fn: (trx: InMemoryTransaction) => any) {\n let trx = new InMemoryTransaction(new InMemoryUnderlyingTransaction());\n let retry = InMemoryDatabase.transactionTries;\n let latestReturnValue = undefined;\n while (retry--) {\n try {\n latestReturnValue = await fn(trx);\n this.streamId(trx);\n break;\n } catch (error) {\n if (error instanceof TransactionCollision) {\n trx = new InMemoryTransaction(new InMemoryUnderlyingTransaction());\n } else {\n throw error;\n }\n }\n }\n\n if (retry === -1) {\n throw new TransactionCollidedTooManyTimes(\n InMemoryDatabase.transactionTries,\n );\n }\n\n return latestReturnValue;\n }\n\n private streamId(trx: InMemoryTransaction) {\n if (!trx.transaction.checkConsistency(this.storage)) {\n throw new TransactionCollision();\n }\n\n for (const operation of trx.transaction.operations) {\n if (operation.type === \"read\") {\n continue;\n }\n if (operation.type === \"write\") {\n this.save(operation.collectionName, operation.id, operation.data);\n }\n if (operation.type === \"delete\") {\n this.delete(operation.collectionName, operation.id);\n }\n if (operation.type === \"create\") {\n this.create(operation.collectionName, operation.id, operation.data);\n }\n }\n }\n\n print() {\n console.log([\"Database:\", this.storage.toPretty()].join(\"\\n\"));\n }\n}\n"],"mappings":";;;;;;AAIA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,cAAc;AACZ,QAAM,sDAAsD;;;AAIhE,IAAa,uBAAb,cAA0C,MAAM;CAC9C,cAAc;AACZ,QAAM,oDAAoD;;;AAI9D,IAAa,wBAAb,cAA2C,iBAAiB;CAC1D,cAAc;AACZ,QAAM,0BAA0B;;;AAIpC,IAAa,kCAAb,cAAqD,MAAM;CACzD,YAAY,OAAe;AACzB,QAAM,wCAAwC,MAAM,GAAG;;;AAsC3D,IAAa,gCAAb,MAA2C;CACzC,AAAgB,aAAqC,EAAE;CAEvD,AAAgB,KAAK,KAAK,QAAQ,CAAC,UAAU,CAAC,UAAU,EAAE;CAE1D,AAAQ,iBAAiB;AACvB,MACE,KAAK,WAAW,MACb,cACC,UAAU,SAAS,WACnB,UAAU,SAAS,YACnB,UAAU,SAAS,SACtB,CAED,OAAM,IAAI,uBAAuB;;CAIrC,AAAO,SACL,gBACA,IACA,SACA;AACA,OAAK,gBAAgB;AACrB,OAAK,WAAW,KAAK;GAAE,MAAM;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IAAI,YAAY,YAAY;AAClD,OAAI,UAAU,SAAS,OACrB;AAEF,OAAI,UAAU,SAAS,QACrB,MAAK,KAAK,UAAU,gBAAgB,UAAU,IAAI,UAAU,KAAK;AAEnE,OAAI,UAAU,SAAS,SACrB,MAAK,OAAO,UAAU,gBAAgB,UAAU,GAAG;AAErD,OAAI,UAAU,SAAS,SACrB,MAAK,OAAO,UAAU,gBAAgB,UAAU,IAAI,UAAU,KAAK;;;CAKzE,QAAQ;AACN,UAAQ,IAAI,CAAC,aAAa,KAAK,QAAQ,UAAU,CAAC,CAAC,KAAK,KAAK,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { Collection } from "./in-memory.collection.js";
2
+
3
+ //#region src/store/in-memory.storage.d.ts
4
+ declare class Storage {
5
+ collections: Map<string, Collection>;
6
+ constructor(collections?: Map<string, Collection>);
7
+ clone(): Storage;
8
+ merge(other: Storage): Storage;
9
+ getCollection(collectionName: string): Collection;
10
+ toPretty(): string;
11
+ }
12
+ //#endregion
13
+ export { Storage };
14
+ //# sourceMappingURL=in-memory.storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.storage.d.ts","names":[],"sources":["../../src/store/in-memory.storage.ts"],"mappings":";;;cAEa,OAAA;EACQ,WAAA,EAAa,GAAA,SAAY,UAAA;cAAzB,WAAA,GAAa,GAAA,SAAY,UAAA;EAE5C,KAAA,CAAA,GAAK,OAAA;EASL,KAAA,CAAM,KAAA,EAAO,OAAA,GAAO,OAAA;EAWpB,aAAA,CAAc,cAAA,WAAyB,UAAA;EAMvC,QAAA,CAAA;AAAA"}
@@ -0,0 +1,32 @@
1
+ import { Collection } from "./in-memory.collection.js";
2
+
3
+ //#region src/store/in-memory.storage.ts
4
+ var Storage = class Storage {
5
+ constructor(collections = /* @__PURE__ */ new Map()) {
6
+ this.collections = collections;
7
+ }
8
+ clone() {
9
+ const clone = /* @__PURE__ */ new Map();
10
+ for (const [collectionName, collection] of this.collections) clone.set(collectionName, collection.clone());
11
+ return new Storage(clone);
12
+ }
13
+ merge(other) {
14
+ const collections = /* @__PURE__ */ new Map();
15
+ for (const [collectionName, collection] of other.collections) collections.set(collectionName, this.getCollection(collectionName).merge(collection));
16
+ return new Storage(collections);
17
+ }
18
+ getCollection(collectionName) {
19
+ const collection = this.collections.get(collectionName) || new Collection();
20
+ this.collections.set(collectionName, collection);
21
+ return collection;
22
+ }
23
+ toPretty() {
24
+ return [...this.collections.entries()].map(([collectionName, collection]) => {
25
+ return [`Collection: "${collectionName}"`, collection.toPretty()].join("\n");
26
+ }).join("\n");
27
+ }
28
+ };
29
+
30
+ //#endregion
31
+ export { Storage };
32
+ //# sourceMappingURL=in-memory.storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.storage.js","names":[],"sources":["../../src/store/in-memory.storage.ts"],"sourcesContent":["import { Collection } from \"./in-memory.collection\";\n\nexport class Storage {\n constructor(public collections: Map<string, Collection> = new Map()) {}\n\n clone() {\n const clone = new Map<string, Collection>();\n for (const [collectionName, collection] of this.collections) {\n clone.set(collectionName, collection.clone());\n }\n\n return new Storage(clone);\n }\n\n merge(other: Storage) {\n const collections = new Map<string, Collection>();\n for (const [collectionName, collection] of other.collections) {\n collections.set(\n collectionName,\n this.getCollection(collectionName).merge(collection),\n );\n }\n return new Storage(collections);\n }\n\n getCollection(collectionName: string): Collection {\n const collection = this.collections.get(collectionName) || new Collection();\n this.collections.set(collectionName, collection);\n return collection;\n }\n\n toPretty() {\n return [...this.collections.entries()]\n .map(([collectionName, collection]) => {\n return [`Collection: \"${collectionName}\"`, collection.toPretty()].join(\n \"\\n\",\n );\n })\n .join(\"\\n\");\n }\n}\n"],"mappings":";;;AAEA,IAAa,UAAb,MAAa,QAAQ;CACnB,YAAY,AAAO,8BAAuC,IAAI,KAAK,EAAE;EAAlD;;CAEnB,QAAQ;EACN,MAAM,wBAAQ,IAAI,KAAyB;AAC3C,OAAK,MAAM,CAAC,gBAAgB,eAAe,KAAK,YAC9C,OAAM,IAAI,gBAAgB,WAAW,OAAO,CAAC;AAG/C,SAAO,IAAI,QAAQ,MAAM;;CAG3B,MAAM,OAAgB;EACpB,MAAM,8BAAc,IAAI,KAAyB;AACjD,OAAK,MAAM,CAAC,gBAAgB,eAAe,MAAM,YAC/C,aAAY,IACV,gBACA,KAAK,cAAc,eAAe,CAAC,MAAM,WAAW,CACrD;AAEH,SAAO,IAAI,QAAQ,YAAY;;CAGjC,cAAc,gBAAoC;EAChD,MAAM,aAAa,KAAK,YAAY,IAAI,eAAe,IAAI,IAAI,YAAY;AAC3E,OAAK,YAAY,IAAI,gBAAgB,WAAW;AAChD,SAAO;;CAGT,WAAW;AACT,SAAO,CAAC,GAAG,KAAK,YAAY,SAAS,CAAC,CACnC,KAAK,CAAC,gBAAgB,gBAAgB;AACrC,UAAO,CAAC,gBAAgB,eAAe,IAAI,WAAW,UAAU,CAAC,CAAC,KAChE,KACD;IACD,CACD,KAAK,KAAK"}
@@ -0,0 +1,30 @@
1
+ import { InMemoryDatabase } from "./in-memory.database.js";
2
+ import { InMemoryTransaction } from "../in-memory.transaction.js";
3
+ import { IIdentifiable, ISerializer, Store } from "@ddd-ts/core";
4
+
5
+ //#region src/store/in-memory.store.d.ts
6
+ /**
7
+ * This in memory store is a copy store. It stores a copy of the actual model.
8
+ * It is the recommended inmemory store to use, as it reflects more closely the behaviour of a real store.
9
+ */
10
+ declare class InMemoryStore<M extends IIdentifiable> implements Store<M> {
11
+ readonly collection: string;
12
+ readonly database: InMemoryDatabase;
13
+ readonly serializer: ISerializer<M>;
14
+ readonly $name?: string | undefined;
15
+ constructor(collection: string, database: InMemoryDatabase, serializer: ISerializer<M>, $name?: string | undefined);
16
+ filter(predicate: (model: M) => boolean, trx?: InMemoryTransaction): Promise<M[]>;
17
+ clear(): void;
18
+ create(model: M, trx?: InMemoryTransaction): Promise<void>;
19
+ save(model: M, trx?: InMemoryTransaction): Promise<void>;
20
+ saveAll(models: M[], trx?: InMemoryTransaction): Promise<void>;
21
+ load(id: M["id"], trx?: InMemoryTransaction): Promise<M | undefined>;
22
+ loadAll(trx?: InMemoryTransaction): Promise<M[]>;
23
+ loadMany(ids: M["id"][], trx?: InMemoryTransaction): Promise<M[]>;
24
+ delete(id: M["id"], trx?: InMemoryTransaction): Promise<void>;
25
+ countAll(): Promise<number>;
26
+ streamAll(): AsyncIterable<M>;
27
+ }
28
+ //#endregion
29
+ export { InMemoryStore };
30
+ //# sourceMappingURL=in-memory.store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.store.d.ts","names":[],"sources":["../../src/store/in-memory.store.ts"],"mappings":";;;;;;;AAOA;;cAAa,aAAA,WAAwB,aAAA,aAA0B,KAAA,CAAM,CAAA;EAAA,SAEjD,UAAA;EAAA,SACA,QAAA,EAAU,gBAAA;EAAA,SACV,UAAA,EAAY,WAAA,CAAY,CAAA;EAAA,SACxB,KAAA;cAHA,UAAA,UACA,QAAA,EAAU,gBAAA,EACV,UAAA,EAAY,WAAA,CAAY,CAAA,GACxB,KAAA;EAGZ,MAAA,CACJ,SAAA,GAAY,KAAA,EAAO,CAAA,cACnB,GAAA,GAAM,mBAAA,GACL,OAAA,CAAQ,CAAA;EAiBX,KAAA,CAAA;EAIM,MAAA,CAAO,KAAA,EAAO,CAAA,EAAG,GAAA,GAAM,mBAAA,GAAsB,OAAA;EAU7C,IAAA,CAAK,KAAA,EAAO,CAAA,EAAG,GAAA,GAAM,mBAAA,GAAsB,OAAA;EAU3C,OAAA,CAAQ,MAAA,EAAQ,CAAA,IAAK,GAAA,GAAM,mBAAA,GAAsB,OAAA;EAIjD,IAAA,CAAK,EAAA,EAAI,CAAA,QAAS,GAAA,GAAM,mBAAA,GAAsB,OAAA,CAAQ,CAAA;EAiB5D,OAAA,CAAQ,GAAA,GAAM,mBAAA,GAAsB,OAAA,CAAQ,CAAA;EActC,QAAA,CAAS,GAAA,EAAK,CAAA,UAAW,GAAA,GAAM,mBAAA,GAAsB,OAAA,CAAQ,CAAA;EAK7D,MAAA,CAAO,EAAA,EAAI,CAAA,QAAS,GAAA,GAAM,mBAAA,GAAsB,OAAA;EAIhD,QAAA,CAAA,GAAQ,OAAA;EAIP,SAAA,CAAA,GAAa,aAAA,CAAc,CAAA;AAAA"}
@@ -0,0 +1,78 @@
1
+ //#region src/store/in-memory.store.ts
2
+ /**
3
+ * This in memory store is a copy store. It stores a copy of the actual model.
4
+ * It is the recommended inmemory store to use, as it reflects more closely the behaviour of a real store.
5
+ */
6
+ var InMemoryStore = class {
7
+ constructor(collection, database, serializer, $name) {
8
+ this.collection = collection;
9
+ this.database = database;
10
+ this.serializer = serializer;
11
+ this.$name = $name;
12
+ }
13
+ async filter(predicate, trx) {
14
+ return (await Promise.all(this.database.loadAll(this.collection).map(async (e) => {
15
+ const deserialized = await this.serializer.deserialize({
16
+ ...this.$name ? { $name: this.$name } : {},
17
+ ...e.data.data
18
+ });
19
+ if (!predicate(deserialized)) return;
20
+ trx?.transaction.markRead(this.collection, e.id, e.data.savedAt);
21
+ return deserialized;
22
+ }))).filter((e) => Boolean(e));
23
+ }
24
+ clear() {
25
+ this.database.clear(this.collection);
26
+ }
27
+ async create(model, trx) {
28
+ const serialized = await this.serializer.serialize(model);
29
+ await this.database.create(this.collection, model.id.serialize(), {
30
+ ...this.$name ? { $name: this.$name } : {},
31
+ ...serialized
32
+ }, trx?.transaction);
33
+ }
34
+ async save(model, trx) {
35
+ const serialized = await this.serializer.serialize(model);
36
+ await this.database.save(this.collection, model.id.serialize(), {
37
+ ...this.$name ? { $name: this.$name } : {},
38
+ ...serialized
39
+ }, trx?.transaction);
40
+ }
41
+ async saveAll(models, trx) {
42
+ await Promise.all(models.map((m) => this.save(m, trx)));
43
+ }
44
+ async load(id, trx) {
45
+ const serialized = await this.database.load(this.collection, id.serialize(), trx?.transaction);
46
+ if (!serialized) return;
47
+ return this.serializer.deserialize({
48
+ ...this.$name ? { $name: this.$name } : {},
49
+ ...serialized
50
+ });
51
+ }
52
+ loadAll(trx) {
53
+ const serialized = this.database.loadAll(this.collection);
54
+ return Promise.all(serialized.map(async (s) => {
55
+ trx?.transaction.markRead(this.collection, s.id, s.data.savedAt);
56
+ return this.serializer.deserialize({
57
+ ...this.$name ? { $name: this.$name } : {},
58
+ ...s.data.data
59
+ });
60
+ }));
61
+ }
62
+ async loadMany(ids, trx) {
63
+ return (await Promise.all(ids.map((id) => this.load(id, trx)))).filter((m) => m !== void 0);
64
+ }
65
+ async delete(id, trx) {
66
+ this.database.delete(this.collection, id.serialize(), trx?.transaction);
67
+ }
68
+ async countAll() {
69
+ return this.database.countAll(this.collection);
70
+ }
71
+ async *streamAll() {
72
+ for (const item of await this.filter(() => true)) yield item;
73
+ }
74
+ };
75
+
76
+ //#endregion
77
+ export { InMemoryStore };
78
+ //# sourceMappingURL=in-memory.store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.store.js","names":[],"sources":["../../src/store/in-memory.store.ts"],"sourcesContent":["import { ISerializer, Store, type IIdentifiable } from \"@ddd-ts/core\";\nimport { InMemoryDatabase } from \"./in-memory.database\";\nimport { InMemoryTransaction } from \"../in-memory.transaction\";\n/**\n * This in memory store is a copy store. It stores a copy of the actual model.\n * It is the recommended inmemory store to use, as it reflects more closely the behaviour of a real store.\n */\nexport class InMemoryStore<M extends IIdentifiable> implements Store<M> {\n constructor(\n public readonly collection: string,\n public readonly database: InMemoryDatabase,\n public readonly serializer: ISerializer<M>,\n public readonly $name?: string,\n ) {}\n\n async filter(\n predicate: (model: M) => boolean,\n trx?: InMemoryTransaction,\n ): Promise<M[]> {\n const filtered = await Promise.all(\n this.database.loadAll(this.collection).map(async (e) => {\n const deserialized = await this.serializer.deserialize({\n ...(this.$name ? { $name: this.$name } : {}),\n ...e.data.data,\n });\n if (!predicate(deserialized)) {\n return undefined;\n }\n trx?.transaction.markRead(this.collection, e.id, e.data.savedAt);\n return deserialized;\n }),\n );\n return filtered.filter((e): e is NonNullable<typeof e> => Boolean(e));\n }\n\n clear() {\n this.database.clear(this.collection);\n }\n\n async create(model: M, trx?: InMemoryTransaction): Promise<void> {\n const serialized = await this.serializer.serialize(model);\n await this.database.create(\n this.collection,\n model.id.serialize(),\n { ...(this.$name ? { $name: this.$name } : {}), ...serialized },\n trx?.transaction,\n );\n }\n\n async save(model: M, trx?: InMemoryTransaction): Promise<void> {\n const serialized = await this.serializer.serialize(model);\n await this.database.save(\n this.collection,\n model.id.serialize(),\n { ...(this.$name ? { $name: this.$name } : {}), ...serialized },\n trx?.transaction,\n );\n }\n\n async saveAll(models: M[], trx?: InMemoryTransaction): Promise<void> {\n await Promise.all(models.map((m) => this.save(m, trx)));\n }\n\n async load(id: M[\"id\"], trx?: InMemoryTransaction): Promise<M | undefined> {\n const serialized = await this.database.load(\n this.collection,\n id.serialize(),\n trx?.transaction,\n );\n\n if (!serialized) {\n return undefined;\n }\n\n return this.serializer.deserialize({\n ...(this.$name ? { $name: this.$name } : {}),\n ...serialized,\n });\n }\n\n loadAll(trx?: InMemoryTransaction): Promise<M[]> {\n const serialized = this.database.loadAll(this.collection);\n\n return Promise.all(\n serialized.map(async (s) => {\n trx?.transaction.markRead(this.collection, s.id, s.data.savedAt);\n return this.serializer.deserialize({\n ...(this.$name ? { $name: this.$name } : {}),\n ...s.data.data,\n });\n }),\n );\n }\n\n async loadMany(ids: M[\"id\"][], trx?: InMemoryTransaction): Promise<M[]> {\n const result = await Promise.all(ids.map((id) => this.load(id, trx)));\n return result.filter((m) => m !== undefined) as M[];\n }\n\n async delete(id: M[\"id\"], trx?: InMemoryTransaction): Promise<void> {\n this.database.delete(this.collection, id.serialize(), trx?.transaction);\n }\n\n async countAll() {\n return this.database.countAll(this.collection);\n }\n\n async *streamAll(): AsyncIterable<M> {\n for (const item of await this.filter(() => true)) {\n yield item;\n }\n }\n}\n"],"mappings":";;;;;AAOA,IAAa,gBAAb,MAAwE;CACtE,YACE,AAAgB,YAChB,AAAgB,UAChB,AAAgB,YAChB,AAAgB,OAChB;EAJgB;EACA;EACA;EACA;;C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,YAAY;GACjC,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,OAAO,GAAG,EAAE;GAC3C,GAAG;GACJ,CAAC;;CAGJ,QAAQ,KAAyC;EAC/C,MAAM,aAAa,KAAK,SAAS,QAAQ,KAAK,WAAW;AAEzD,SAAO,QAAQ,IACb,WAAW,IAAI,OAAO,MAAM;AAC1B,QAAK,YAAY,SAAS,KAAK,YAAY,EAAE,IAAI,EAAE,KAAK,QAAQ;AAChE,UAAO,KAAK,WAAW,YAAY;IACjC,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,OAAO,GAAG,EAAE;IAC3C,GAAG,EAAE,KAAK;IACX,CAAC;IACF,CACH;;CAGH,MAAM,SAAS,KAAgB,KAAyC;AAEtE,UADe,MAAM,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAK,IAAI,IAAI,CAAC,CAAC,EACvD,QAAQ,MAAM,MAAM,OAAU;;CAG9C,MAAM,OAAO,IAAa,KAA0C;AAClE,OAAK,SAAS,OAAO,KAAK,YAAY,GAAG,WAAW,EAAE,KAAK,YAAY;;CAGzE,MAAM,WAAW;AACf,SAAO,KAAK,SAAS,SAAS,KAAK,WAAW;;CAGhD,OAAO,YAA8B;AACnC,OAAK,MAAM,QAAQ,MAAM,KAAK,aAAa,KAAK,CAC9C,OAAM"}
package/package.json CHANGED
@@ -1,20 +1,23 @@
1
1
  {
2
2
  "name": "@ddd-ts/store-inmemory",
3
- "version": "0.0.0-compute-timeout-on-process.2",
3
+ "version": "0.0.0-compute-timeout-on-process.4",
4
4
  "types": "dist/index.d.ts",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "url": "git+https://github.com/ddd-ts/monorepo"
8
8
  },
9
+ "files": [
10
+ "dist"
11
+ ],
9
12
  "scripts": {
10
13
  "build": "tsdown --config node_modules/@ddd-ts/tools/tsdown.config.js"
11
14
  },
12
15
  "dependencies": {
13
- "@ddd-ts/core": "0.0.0-compute-timeout-on-process.2"
16
+ "@ddd-ts/core": "0.0.0-compute-timeout-on-process.4"
14
17
  },
15
18
  "devDependencies": {
16
- "@ddd-ts/tools": "0.0.0-compute-timeout-on-process.2",
17
- "@ddd-ts/types": "0.0.0-compute-timeout-on-process.2",
19
+ "@ddd-ts/tools": "0.0.0-compute-timeout-on-process.4",
20
+ "@ddd-ts/types": "0.0.0-compute-timeout-on-process.4",
18
21
  "@types/jest": "^29.5.1",
19
22
  "@types/node": "^20.12.4"
20
23
  },