@ddd-ts/store-inmemory 0.0.0-compute-timeout-on-process.7 → 0.0.0-compute-timeout-on-process.8

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.
@@ -1,5 +1,5 @@
1
- import "./store/in-memory.database.js";
2
- import { TransactionPerformer } from "@ddd-ts/core";
1
+ require('./store/in-memory.database.js');
2
+ let _ddd_ts_core = require("@ddd-ts/core");
3
3
 
4
4
  //#region src/in-memory.transaction.ts
5
5
  var InMemoryTransaction = class {
@@ -19,17 +19,18 @@ var InMemoryTransaction = class {
19
19
  await Promise.all(this.commitListeners.map((cb) => cb()));
20
20
  }
21
21
  };
22
- var InMemoryTransactionPerformer = class extends TransactionPerformer {
22
+ var InMemoryTransactionPerformer = class extends _ddd_ts_core.TransactionPerformer {
23
23
  constructor(db) {
24
24
  super((effect) => db.transactionally((trx) => effect(trx)));
25
25
  }
26
26
  };
27
- var FakeInMemoryTransactionPerformer = class extends TransactionPerformer {
27
+ var FakeInMemoryTransactionPerformer = class extends _ddd_ts_core.TransactionPerformer {
28
28
  constructor() {
29
29
  super((effect) => effect(new InMemoryTransaction(null)));
30
30
  }
31
31
  };
32
32
 
33
33
  //#endregion
34
- export { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer };
35
- //# sourceMappingURL=in-memory.transaction.js.map
34
+ exports.FakeInMemoryTransactionPerformer = FakeInMemoryTransactionPerformer;
35
+ exports.InMemoryTransaction = InMemoryTransaction;
36
+ exports.InMemoryTransactionPerformer = InMemoryTransactionPerformer;
@@ -0,0 +1,35 @@
1
+ import "./store/in-memory.database.mjs";
2
+ import { TransactionPerformer } from "@ddd-ts/core";
3
+
4
+ //#region src/in-memory.transaction.ts
5
+ var InMemoryTransaction = class {
6
+ commitListeners = [];
7
+ constructor(transaction) {
8
+ this.transaction = transaction;
9
+ }
10
+ counter = -1;
11
+ increment() {
12
+ this.counter++;
13
+ return this.counter;
14
+ }
15
+ onCommit(callback) {
16
+ this.commitListeners.push(callback);
17
+ }
18
+ async executeCommitListeners() {
19
+ await Promise.all(this.commitListeners.map((cb) => cb()));
20
+ }
21
+ };
22
+ var InMemoryTransactionPerformer = class extends TransactionPerformer {
23
+ constructor(db) {
24
+ super((effect) => db.transactionally((trx) => effect(trx)));
25
+ }
26
+ };
27
+ var FakeInMemoryTransactionPerformer = class extends TransactionPerformer {
28
+ constructor() {
29
+ super((effect) => effect(new InMemoryTransaction(null)));
30
+ }
31
+ };
32
+
33
+ //#endregion
34
+ export { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer };
35
+ //# sourceMappingURL=in-memory.transaction.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.transaction.mjs","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"}
package/dist/index.js CHANGED
@@ -1,5 +1,13 @@
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";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_in_memory_database = require('./store/in-memory.database.js');
3
+ const require_in_memory_transaction = require('./in-memory.transaction.js');
4
+ const require_in_memory_store = require('./store/in-memory.store.js');
4
5
 
5
- export { CannotReadAfterWrites, FakeInMemoryTransactionPerformer, InMemoryDatabase, InMemoryStore, InMemoryTransaction, InMemoryTransactionPerformer, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
6
+ exports.CannotReadAfterWrites = require_in_memory_database.CannotReadAfterWrites;
7
+ exports.FakeInMemoryTransactionPerformer = require_in_memory_transaction.FakeInMemoryTransactionPerformer;
8
+ exports.InMemoryDatabase = require_in_memory_database.InMemoryDatabase;
9
+ exports.InMemoryStore = require_in_memory_store.InMemoryStore;
10
+ exports.InMemoryTransaction = require_in_memory_transaction.InMemoryTransaction;
11
+ exports.InMemoryTransactionPerformer = require_in_memory_transaction.InMemoryTransactionPerformer;
12
+ exports.InMemoryUnderlyingTransaction = require_in_memory_database.InMemoryUnderlyingTransaction;
13
+ exports.TransactionCollidedTooManyTimes = require_in_memory_database.TransactionCollidedTooManyTimes;
package/dist/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ import { CannotReadAfterWrites, InMemoryDatabase, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes } from "./store/in-memory.database.mjs";
2
+ import { FakeInMemoryTransactionPerformer, InMemoryTransaction, InMemoryTransactionPerformer } from "./in-memory.transaction.mjs";
3
+ import { InMemoryStore } from "./store/in-memory.store.mjs";
4
+
5
+ export { CannotReadAfterWrites, FakeInMemoryTransactionPerformer, InMemoryDatabase, InMemoryStore, InMemoryTransaction, InMemoryTransactionPerformer, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
@@ -1,3 +1,4 @@
1
+
1
2
  //#region src/store/in-memory.collection.ts
2
3
  function now() {
3
4
  if (typeof process === "object" && typeof process.hrtime === "function") return process.hrtime.bigint() / BigInt(1e3);
@@ -61,5 +62,4 @@ function replaceBigInt(key, value) {
61
62
  }
62
63
 
63
64
  //#endregion
64
- export { Collection };
65
- //# sourceMappingURL=in-memory.collection.js.map
65
+ exports.Collection = Collection;
@@ -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.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.collection.mjs","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,MAAO,EAAE,UAAU,EAAE,UAAU,IAAI,GAAI,CACxD,IAAI;;CAGpB,QAAQ;EACN,MAAM,wBAAQ,IAAI,KAAK;AACvB,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,KAC9B,OAAM,IAAI,KAAK,MAAM;AAEvB,SAAO,IAAI,WAAW,MAAM;;CAG9B,MAAM,OAAmB;EACvB,MAAM,wBAAQ,IAAI,KAAK;AACvB,OAAK,MAAM,CAAC,KAAK,UAAU,KAAK,KAC9B,OAAM,IAAI,KAAK,MAAM;AAEvB,OAAK,MAAM,CAAC,KAAK,UAAU,MAAM,KAC/B,OAAM,IAAI,KAAK,MAAM;AAEvB,SAAO,IAAI,WAAW,MAAM;;CAG9B,OAAO,IAAkB;AACvB,OAAK,KAAK,OAAO,GAAG;;CAGtB,OAAO,IAAY;AACjB,SAAO,KAAK,KAAK,IAAI,GAAG;;CAG1B,WAAW;AACT,SAAO,KAAK,KAAK;;CAGnB,IAAI,IAAiB;AACnB,SAAO,KAAK,KAAK,IAAI,GAAG,EAAE;;CAG5B,YAAY;AACV,SAAO,CAAC,GAAG,KAAK,KAAK,SAAS,CAAC,CAAC,KAAK,CAAC,IAAI,WAAW;GAAE;GAAI;GAAM,EAAE;;CAGrE,SAAgB;AACd,SAAO,CAAC,GAAG,KAAK,KAAK,SAAS,CAAC,CAAC,KAAK,CAAC,IAAI,UAAU,KAAK,KAAK;;CAGhE,KAAK,IAAY,MAAiB;AAChC,OAAK,KAAK,IAAI,IAAI;GAAE,SAAS,KAAK;GAAE;GAAM,CAAC;;CAG7C,WAAW;AACT,SAAO,CAAC,GAAG,KAAK,KAAK,SAAS,CAAC,CAC5B,KACE,CAAC,IAAI,UACJ,QAAQ,GAAG,KAAK,KAAK,UAAU,KAAK,MAAM,cAAc,GAC3D,CACA,KAAK,MAAM;;;AAIlB,SAAS,cAAc,KAAa,OAAY;AAC9C,KAAI,OAAO,UAAU,SACnB,QAAO,MAAM,UAAU;AAEzB,QAAO"}
@@ -1,7 +1,5 @@
1
1
  import { Storage } from "./in-memory.storage.js";
2
2
  import { InMemoryTransaction } from "../in-memory.transaction.js";
3
- import "../index.js";
4
- import { ConcurrencyError } from "@ddd-ts/core";
5
3
 
6
4
  //#region src/store/in-memory.database.d.ts
7
5
  declare class CannotReadAfterWrites extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"in-memory.database.d.ts","names":[],"sources":["../../src/store/in-memory.database.ts"],"mappings":";;;;;;cAIa,qBAAA,SAA8B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nD,QAAA;EAqBR,KAAA,CAAA;AAAA"}
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"}
@@ -1,7 +1,7 @@
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";
1
+ const require_in_memory_storage = require('./in-memory.storage.js');
2
+ const require_in_memory_transaction = require('../in-memory.transaction.js');
3
+ require('../index.js');
4
+ let _ddd_ts_core = require("@ddd-ts/core");
5
5
 
6
6
  //#region src/store/in-memory.database.ts
7
7
  var CannotReadAfterWrites = class extends Error {
@@ -14,7 +14,7 @@ var TransactionCollision = class extends Error {
14
14
  super("Transaction has collided with other extern writes");
15
15
  }
16
16
  };
17
- var DocumentAlreadyExists = class extends ConcurrencyError {
17
+ var DocumentAlreadyExists = class extends _ddd_ts_core.ConcurrencyError {
18
18
  constructor() {
19
19
  super("Document already exists");
20
20
  }
@@ -79,7 +79,7 @@ var InMemoryUnderlyingTransaction = class {
79
79
  }
80
80
  };
81
81
  var InMemoryDatabase = class InMemoryDatabase {
82
- storage = new Storage();
82
+ storage = new require_in_memory_storage.Storage();
83
83
  clear(collectionName) {
84
84
  this.storage.getCollection(collectionName).clear();
85
85
  }
@@ -120,7 +120,7 @@ var InMemoryDatabase = class InMemoryDatabase {
120
120
  }
121
121
  static transactionTries = 5;
122
122
  async transactionally(fn) {
123
- let trx = new InMemoryTransaction(new InMemoryUnderlyingTransaction());
123
+ let trx = new require_in_memory_transaction.InMemoryTransaction(new InMemoryUnderlyingTransaction());
124
124
  let retry = InMemoryDatabase.transactionTries;
125
125
  let latestReturnValue = void 0;
126
126
  while (retry--) try {
@@ -128,7 +128,7 @@ var InMemoryDatabase = class InMemoryDatabase {
128
128
  this.streamId(trx);
129
129
  break;
130
130
  } catch (error) {
131
- if (error instanceof TransactionCollision) trx = new InMemoryTransaction(new InMemoryUnderlyingTransaction());
131
+ if (error instanceof TransactionCollision) trx = new require_in_memory_transaction.InMemoryTransaction(new InMemoryUnderlyingTransaction());
132
132
  else throw error;
133
133
  }
134
134
  if (retry === -1) throw new TransactionCollidedTooManyTimes(InMemoryDatabase.transactionTries);
@@ -149,5 +149,7 @@ var InMemoryDatabase = class InMemoryDatabase {
149
149
  };
150
150
 
151
151
  //#endregion
152
- export { CannotReadAfterWrites, InMemoryDatabase, InMemoryUnderlyingTransaction, TransactionCollidedTooManyTimes };
153
- //# sourceMappingURL=in-memory.database.js.map
152
+ exports.CannotReadAfterWrites = CannotReadAfterWrites;
153
+ exports.InMemoryDatabase = InMemoryDatabase;
154
+ exports.InMemoryUnderlyingTransaction = InMemoryUnderlyingTransaction;
155
+ exports.TransactionCollidedTooManyTimes = TransactionCollidedTooManyTimes;
@@ -0,0 +1,153 @@
1
+ import { Storage } from "./in-memory.storage.mjs";
2
+ import { InMemoryTransaction } from "../in-memory.transaction.mjs";
3
+ import "../index.mjs";
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.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.database.mjs","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,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,iBAClB;AAGH,SAAO;;CAGT,AAAQ,SAAS,KAA0B;AACzC,MAAI,CAAC,IAAI,YAAY,iBAAiB,KAAK,QAAQ,CACjD,OAAM,IAAI,sBAAsB;AAGlC,OAAK,MAAM,aAAa,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"}
@@ -1,4 +1,4 @@
1
- import { Collection } from "./in-memory.collection.js";
1
+ const require_in_memory_collection = require('./in-memory.collection.js');
2
2
 
3
3
  //#region src/store/in-memory.storage.ts
4
4
  var Storage = class Storage {
@@ -16,7 +16,7 @@ var Storage = class Storage {
16
16
  return new Storage(collections);
17
17
  }
18
18
  getCollection(collectionName) {
19
- const collection = this.collections.get(collectionName) || new Collection();
19
+ const collection = this.collections.get(collectionName) || new require_in_memory_collection.Collection();
20
20
  this.collections.set(collectionName, collection);
21
21
  return collection;
22
22
  }
@@ -28,5 +28,4 @@ var Storage = class Storage {
28
28
  };
29
29
 
30
30
  //#endregion
31
- export { Storage };
32
- //# sourceMappingURL=in-memory.storage.js.map
31
+ exports.Storage = Storage;
@@ -0,0 +1,32 @@
1
+ import { Collection } from "./in-memory.collection.mjs";
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.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.storage.mjs","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"}
@@ -1,6 +1,6 @@
1
- import "./in-memory.database.js";
2
- import "../in-memory.transaction.js";
3
- import { ISerializer, Store } from "@ddd-ts/core";
1
+ require('./in-memory.database.js');
2
+ require('../in-memory.transaction.js');
3
+ let _ddd_ts_core = require("@ddd-ts/core");
4
4
 
5
5
  //#region src/store/in-memory.store.ts
6
6
  /**
@@ -78,5 +78,4 @@ var InMemoryStore = class {
78
78
  };
79
79
 
80
80
  //#endregion
81
- export { InMemoryStore };
82
- //# sourceMappingURL=in-memory.store.js.map
81
+ exports.InMemoryStore = InMemoryStore;
@@ -0,0 +1,82 @@
1
+ import "./in-memory.database.mjs";
2
+ import "../in-memory.transaction.mjs";
3
+ import { ISerializer, Store } from "@ddd-ts/core";
4
+
5
+ //#region src/store/in-memory.store.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
+ var InMemoryStore = class {
11
+ constructor(collection, database, serializer, $name) {
12
+ this.collection = collection;
13
+ this.database = database;
14
+ this.serializer = serializer;
15
+ this.$name = $name;
16
+ }
17
+ async filter(predicate, trx) {
18
+ return (await Promise.all(this.database.loadAll(this.collection).map(async (e) => {
19
+ const deserialized = await this.serializer.deserialize({
20
+ ...this.$name ? { $name: this.$name } : {},
21
+ ...e.data.data
22
+ });
23
+ if (!predicate(deserialized)) return;
24
+ trx?.transaction.markRead(this.collection, e.id, e.data.savedAt);
25
+ return deserialized;
26
+ }))).filter((e) => Boolean(e));
27
+ }
28
+ clear() {
29
+ this.database.clear(this.collection);
30
+ }
31
+ async create(model, trx) {
32
+ const serialized = await this.serializer.serialize(model);
33
+ await this.database.create(this.collection, model.id.serialize(), {
34
+ ...this.$name ? { $name: this.$name } : {},
35
+ ...serialized
36
+ }, trx?.transaction);
37
+ }
38
+ async save(model, trx) {
39
+ const serialized = await this.serializer.serialize(model);
40
+ await this.database.save(this.collection, model.id.serialize(), {
41
+ ...this.$name ? { $name: this.$name } : {},
42
+ ...serialized
43
+ }, trx?.transaction);
44
+ }
45
+ async saveAll(models, trx) {
46
+ await Promise.all(models.map((m) => this.save(m, trx)));
47
+ }
48
+ async load(id, trx) {
49
+ const serialized = await this.database.load(this.collection, id.serialize(), trx?.transaction);
50
+ if (!serialized) return;
51
+ return this.serializer.deserialize({
52
+ ...this.$name ? { $name: this.$name } : {},
53
+ ...serialized
54
+ });
55
+ }
56
+ loadAll(trx) {
57
+ const serialized = this.database.loadAll(this.collection);
58
+ return Promise.all(serialized.map(async (s) => {
59
+ trx?.transaction.markRead(this.collection, s.id, s.data.savedAt);
60
+ return this.serializer.deserialize({
61
+ ...this.$name ? { $name: this.$name } : {},
62
+ ...s.data.data
63
+ });
64
+ }));
65
+ }
66
+ async loadMany(ids, trx) {
67
+ return (await Promise.all(ids.map((id) => this.load(id, trx)))).filter((m) => m !== void 0);
68
+ }
69
+ async delete(id, trx) {
70
+ this.database.delete(this.collection, id.serialize(), trx?.transaction);
71
+ }
72
+ async countAll() {
73
+ return this.database.countAll(this.collection);
74
+ }
75
+ async *streamAll() {
76
+ for (const item of await this.filter(() => true)) yield item;
77
+ }
78
+ };
79
+
80
+ //#endregion
81
+ export { InMemoryStore };
82
+ //# sourceMappingURL=in-memory.store.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-memory.store.mjs","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;;CAGlB,MAAM,OACJ,WACA,KACc;AAcd,UAbiB,MAAM,QAAQ,IAC7B,KAAK,SAAS,QAAQ,KAAK,WAAW,CAAC,IAAI,OAAO,MAAM;GACtD,MAAM,eAAe,MAAM,KAAK,WAAW,YAAY;IACrD,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,OAAO,GAAG,EAAE;IAC3C,GAAG,EAAE,KAAK;IACX,CAAC;AACF,OAAI,CAAC,UAAU,aAAa,CAC1B;AAEF,QAAK,YAAY,SAAS,KAAK,YAAY,EAAE,IAAI,EAA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E,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,6 +1,6 @@
1
1
  {
2
2
  "name": "@ddd-ts/store-inmemory",
3
- "version": "0.0.0-compute-timeout-on-process.7",
3
+ "version": "0.0.0-compute-timeout-on-process.8",
4
4
  "types": "dist/index.d.ts",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -10,16 +10,21 @@
10
10
  "dist"
11
11
  ],
12
12
  "dependencies": {
13
- "@ddd-ts/core": "0.0.0-compute-timeout-on-process.7"
13
+ "@ddd-ts/core": "0.0.0-compute-timeout-on-process.8"
14
14
  },
15
15
  "devDependencies": {
16
- "@ddd-ts/tools": "0.0.0-compute-timeout-on-process.7",
17
- "@ddd-ts/types": "0.0.0-compute-timeout-on-process.7",
16
+ "@ddd-ts/tools": "0.0.0-compute-timeout-on-process.8",
17
+ "@ddd-ts/types": "0.0.0-compute-timeout-on-process.8",
18
18
  "@types/jest": "^29.5.1",
19
19
  "@types/node": "^20.12.4"
20
20
  },
21
21
  "exports": {
22
- ".": "./dist/index.js",
22
+ ".": {
23
+ "default": "./dist/index.js",
24
+ "import": "./dist/index.mjs",
25
+ "require": "./dist/index.js",
26
+ "types": "./dist/index.d.ts"
27
+ },
23
28
  "./package.json": "./package.json"
24
29
  },
25
30
  "scripts": {
@@ -1 +0,0 @@
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"}
@@ -1 +0,0 @@
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,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AS,CAAC,CAC5B,KACE,CAAC,IAAI,UACJ,QAAQ,GAAG,KAAK,KAAK,UAAU,KAAK,MAAM,cAAc,GAC3D,CACA,KAAK,MAAM;;;AAIlB,SAAS,cAAc,KAAa,OAAY;AAC9C,KAAI,OAAO,UAAU,SACnB,QAAO,MAAM,UAAU;AAEzB,QAAO"}
@@ -1 +0,0 @@
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,QA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AI,+BAA+B,CAAC;EACtE,IAAI,QAAQ,iBAAiB;EAC7B,IAAI,oBAAoB;AACxB,SAAO,QACL,KAAI;AACF,uBAAoB,MAAM,GAAG,IAAI;AACjC,QAAK,SAAS,IAAI;AAClB;WACO,OAAO;AACd,OAAI,iBAAiB,qBACnB,OAAM,IAAI,oBAAoB,IAAI,+BAA+B,CAAC;OAElE,OAAM;;AAKZ,MAAI,UAAU,GACZ,OAAM,IAAI,gCACR,iBAAiB,iBAClB;AAGH,SAAO;;CAGT,AAAQ,SAAS,KAA0B;AACzC,MAAI,CAAC,IAAI,YAAY,iBAAiB,KAAK,QAAQ,CACjD,OAAM,IAAI,sBAAsB;AAGlC,OAAK,MAAM,aAAa,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"}
@@ -1 +0,0 @@
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"}
@@ -1 +0,0 @@
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;;CAGlB,MAAM,OACJ,WACA,KACc;AAcd,UAbiB,MAAM,QAAQ,IAC7B,KAAK,SAAS,QAAQ,KAAK,WAAW,CAAC,IAAI,OAAO,MAAM;GACtD,MAAM,eAAe,MAAM,KAAK,WAAW,YAAY;IACrD,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,OAAO,GAAG,EAAE;IAC3C,GAAG,EAAE,KAAK;IACX,CAAC;AACF,OAAI,CAAC,UAAU,aAAa,CAC1B;AAEF,QAAK,YAAY,SAAS,KAAK,YAAY,EAAE,IAAI,EAAE,KAAK,QAAQ;AAChE,UAAO;IACP,CACH,EACe,QAAQ,MAAkC,QAAQ,EAAE,CAAC;;CAGvE,QAAQ;AACN,OAAK,SAAS,MAAM,KAAK,WAAW;;CAGtC,MAAM,OAAO,OAAU,KAA0C;EAC/D,MAAM,aAAa,MAAM,KAAK,WAAW,UAAU,MAAM;AACzD,QAAM,KAAK,SAAS,OAClB,KAAK,YACL,MAAM,GAAG,WAAW,EACpB;GAAE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,OAAO,GAAG,EAAE;GAAG,GAAG;GAAY,EAC/D,KAAK,YACN;;CAGH,MAAM,KAAK,OAAU,KAA0C;EA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