@cqrs-ddd/mikro-orm 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -274
- package/dist/cache/cache-entry.js +8 -14
- package/dist/cache/cache-entry.js.map +1 -1
- package/dist/cache/mikro-orm.cache.d.ts +1 -1
- package/dist/cache/mikro-orm.cache.d.ts.map +1 -1
- package/dist/cache/mikro-orm.cache.js +15 -19
- package/dist/cache/mikro-orm.cache.js.map +1 -1
- package/dist/concurrency/assert-autocommit.js +1 -4
- package/dist/concurrency/assert-autocommit.js.map +1 -1
- package/dist/concurrency/conditioned-write.js +4 -7
- package/dist/concurrency/conditioned-write.js.map +1 -1
- package/dist/concurrency/optimistic-delete.d.ts +3 -3
- package/dist/concurrency/optimistic-delete.d.ts.map +1 -1
- package/dist/concurrency/optimistic-delete.js +7 -10
- package/dist/concurrency/optimistic-delete.js.map +1 -1
- package/dist/concurrency/optimistic-update.d.ts +3 -3
- package/dist/concurrency/optimistic-update.d.ts.map +1 -1
- package/dist/concurrency/optimistic-update.js +7 -10
- package/dist/concurrency/optimistic-update.js.map +1 -1
- package/dist/errors/mikro-orm.dialect.js +3 -7
- package/dist/errors/mikro-orm.dialect.js.map +1 -1
- package/dist/errors/transient-error.js +4 -8
- package/dist/errors/transient-error.js.map +1 -1
- package/dist/helpers/sql-identifier.js +1 -4
- package/dist/helpers/sql-identifier.js.map +1 -1
- package/dist/index.d.ts +14 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -29
- package/dist/index.js.map +1 -1
- package/dist/interfaces/entity-manager-source.js +1 -2
- package/dist/interfaces/entity-manager-source.js.map +1 -1
- package/dist/mapping/root-entity.properties.d.ts +1 -1
- package/dist/mapping/root-entity.properties.d.ts.map +1 -1
- package/dist/mapping/root-entity.properties.js +5 -9
- package/dist/mapping/root-entity.properties.js.map +1 -1
- package/dist/mapping/unix-timestamp.type.d.ts +5 -2
- package/dist/mapping/unix-timestamp.type.d.ts.map +1 -1
- package/dist/mapping/unix-timestamp.type.js +2 -6
- package/dist/mapping/unix-timestamp.type.js.map +1 -1
- package/dist/repository/aggregate.repository.d.ts +1 -1
- package/dist/repository/aggregate.repository.d.ts.map +1 -1
- package/dist/repository/aggregate.repository.js +5 -9
- package/dist/repository/aggregate.repository.js.map +1 -1
- package/dist/tenancy/tenant-store.d.ts +1 -1
- package/dist/tenancy/tenant-store.d.ts.map +1 -1
- package/dist/tenancy/tenant-store.js +1 -5
- package/dist/tenancy/tenant-store.js.map +1 -1
- package/package.json +11 -3
package/README.md
CHANGED
|
@@ -8,21 +8,7 @@ authoritative aggregate loading, version-conditioned writes, the persistence dia
|
|
|
8
8
|
that maps unique violations and transient failures, a revision-fenced cache stored in
|
|
9
9
|
the database, and the `EntitySchema` mapping of `RootEntity`.
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
on no framework: it works in a plain Node service and in a NestJS application.
|
|
13
|
-
|
|
14
|
-
## Contents
|
|
15
|
-
|
|
16
|
-
- [Installation](#installation)
|
|
17
|
-
- [Entity manager source](#entity-manager-source)
|
|
18
|
-
- [Multi-tenant store](#multi-tenant-store)
|
|
19
|
-
- [Loading aggregates](#loading-aggregates)
|
|
20
|
-
- [Version-conditioned writes](#version-conditioned-writes)
|
|
21
|
-
- [Persistence errors](#persistence-errors)
|
|
22
|
-
- [Mapping a root entity](#mapping-a-root-entity)
|
|
23
|
-
- [The database cache](#the-database-cache)
|
|
24
|
-
- [SQL identifiers](#sql-identifiers)
|
|
25
|
-
- [License](#license)
|
|
11
|
+
**Documentation:** [guide](https://aristoteliss.github.io/nestjs-pipeline/packages/cqrs-ddd/mikro-orm/) · [API reference](https://aristoteliss.github.io/nestjs-pipeline/api/cqrs-ddd/mikro-orm/) · [all packages](https://aristoteliss.github.io/nestjs-pipeline/)
|
|
26
12
|
|
|
27
13
|
## Installation
|
|
28
14
|
|
|
@@ -30,267 +16,10 @@ on no framework: it works in a plain Node service and in a NestJS application.
|
|
|
30
16
|
pnpm add @cqrs-ddd/mikro-orm @cqrs-ddd/core @mikro-orm/core
|
|
31
17
|
```
|
|
32
18
|
|
|
33
|
-
Requires Node.js 22.17 or later, as MikroORM 7 does. `@cqrs-ddd/core` `^0.
|
|
19
|
+
Requires Node.js 22.17 or later, as MikroORM 7 does. `@cqrs-ddd/core` `^0.4.1` and `@mikro-orm/core` `^7.2.1` are peer
|
|
34
20
|
dependencies; add the MikroORM driver you use, such as `@mikro-orm/postgresql`.
|
|
35
21
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
The adapters take an `IEntityManagerSource`, an object with an `em` property, and read
|
|
39
|
-
`em` on every operation. A multi-tenant store can therefore hand out the current
|
|
40
|
-
tenant's manager; a single-database setup can pass `{ em: orm.em.fork() }`.
|
|
41
|
-
|
|
42
|
-
## Multi-tenant store
|
|
43
|
-
|
|
44
|
-
`TenantStore` is that source for a multi-tenant application. `em` and `transactional()`
|
|
45
|
-
act on the active tenant, which `tenant()` supplies; `orm(tenant)` returns the initialized
|
|
46
|
-
ORM holding its data. Both throw when there is no tenant or it is unknown: the store never
|
|
47
|
-
falls back to one.
|
|
48
|
-
|
|
49
|
-
```typescript
|
|
50
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
51
|
-
import { setPersistenceDialect } from '@cqrs-ddd/core/persistence';
|
|
52
|
-
import { CacheEntrySchema, MikroOrmDialect, TenantStore } from '@cqrs-ddd/mikro-orm';
|
|
53
|
-
import { MikroORM } from '@mikro-orm/core';
|
|
54
|
-
|
|
55
|
-
const requestTenant = new AsyncLocalStorage<string>();
|
|
56
|
-
const orms = new Map<string, MikroORM>();
|
|
57
|
-
for (const tenant of ['tenant_a', 'tenant_b']) {
|
|
58
|
-
orms.set(tenant, await MikroORM.init({ ...tenantOptions(tenant), entities: [UserSchema, CacheEntrySchema] }));
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const store = new TenantStore({
|
|
62
|
-
tenant: () => {
|
|
63
|
-
const tenant = requestTenant.getStore();
|
|
64
|
-
if (!tenant) throw new Error('No tenant in scope.');
|
|
65
|
-
return tenant;
|
|
66
|
-
},
|
|
67
|
-
orm: (tenant) => {
|
|
68
|
-
const orm = orms.get(tenant);
|
|
69
|
-
if (!orm) throw new Error(`Unknown tenant ${tenant}.`);
|
|
70
|
-
return orm;
|
|
71
|
-
},
|
|
72
|
-
isolation: 'database', // one ORM and database per tenant; 'schema': one ORM, a schema per tenant
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
const [first] = orms.values();
|
|
76
|
-
if (first) setPersistenceDialect(new MikroOrmDialect(first));
|
|
77
|
-
|
|
78
|
-
await requestTenant.run('tenant_a', () => store.em.findOne(User, { id }));
|
|
79
|
-
await requestTenant.run('tenant_a', () =>
|
|
80
|
-
store.transactional((em) => em.nativeDelete(CacheEntry, { key })),
|
|
81
|
-
);
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
With `'schema'` isolation, `orm` returns the same ORM for every tenant and each manager is
|
|
85
|
-
forked with `schema: tenant`; validate the tenant against a known list before it reaches
|
|
86
|
-
the store, for example with `isSqlIdentifier`.
|
|
87
|
-
|
|
88
|
-
- `em` reuses the contextual manager (a MikroORM `RequestContext` or an active
|
|
89
|
-
transaction) only when it belongs to the tenant's ORM, configuration, driver and schema,
|
|
90
|
-
and no other tenant used it first. Otherwise it forks one, with the tenant's schema under
|
|
91
|
-
`'schema'` isolation.
|
|
92
|
-
- `transactional()` always runs on a fork of its own; a missing or unknown tenant rejects
|
|
93
|
-
it.
|
|
94
|
-
- The tenant of each manager it hands out is kept in a `WeakMap`: MikroORM objects are
|
|
95
|
-
never modified.
|
|
96
|
-
|
|
97
|
-
## Loading aggregates
|
|
98
|
-
|
|
99
|
-
A command that mutates an aggregate loads it through core's
|
|
100
|
-
`IWriteSideAggregateRepository<TEntity>.findById(id)`. `AggregateRepository` implements
|
|
101
|
-
it: `findById()` reads with `{ refresh: true }`, never touches the cache, rehydrates
|
|
102
|
-
through the `hydrateFn` you pass, and translates driver failures with
|
|
103
|
-
`mapPersistenceError`.
|
|
104
|
-
|
|
105
|
-
```typescript
|
|
106
|
-
import type { ICache } from '@cqrs-ddd/core/application';
|
|
107
|
-
import { cacheKey, PersistedWrite } from '@cqrs-ddd/core/persistence';
|
|
108
|
-
import { AggregateRepository, type IEntityManagerSource, optimisticUpdate } from '@cqrs-ddd/mikro-orm';
|
|
109
|
-
|
|
110
|
-
export class UpdateUserRepository extends AggregateRepository<UserSnapshot, User, UserSnapshot> {
|
|
111
|
-
constructor(cache: ICache<UserSnapshot>, store: IEntityManagerSource) {
|
|
112
|
-
super(cache, store, User, User.aggregateName, User.fromJSON);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
@PersistedWrite<User>({
|
|
116
|
-
cache: { setKey: (user) => cacheKey(User.aggregateName, { id: user.id }) },
|
|
117
|
-
})
|
|
118
|
-
async save(user: User): Promise<UserSnapshot> {
|
|
119
|
-
const snapshot = user.toJSON();
|
|
120
|
-
await optimisticUpdate(
|
|
121
|
-
this.store.em,
|
|
122
|
-
User,
|
|
123
|
-
user,
|
|
124
|
-
{ username: snapshot.username, updatedAt: snapshot.updatedAt },
|
|
125
|
-
'User',
|
|
126
|
-
);
|
|
127
|
-
return snapshot;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const users = new UpdateUserRepository(cache, store);
|
|
132
|
-
const user = await users.findById(id); // always the database row, never the cache
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
## Version-conditioned writes
|
|
136
|
-
|
|
137
|
-
`optimisticUpdate` and `optimisticDelete` write `WHERE id = ? AND version = expected`,
|
|
138
|
-
check the affected rows, and raise core's `EntityNotFoundException` or
|
|
139
|
-
`ConcurrencyConflictError`. They, and every write whose success triggers acknowledgment
|
|
140
|
-
or cache work, call `assertAutocommit(em, operation)` first: a write inside an outer
|
|
141
|
-
transaction is rejected before any statement runs, because its success would not mean
|
|
142
|
-
durable persistence.
|
|
143
|
-
|
|
144
|
-
```typescript
|
|
145
|
-
import { ConcurrencyConflictError } from '@cqrs-ddd/core/domain';
|
|
146
|
-
import { optimisticDelete, optimisticUpdate } from '@cqrs-ddd/mikro-orm';
|
|
147
|
-
|
|
148
|
-
// UPDATE users SET department = ?, updated_at = ?, version = <user.version>
|
|
149
|
-
// WHERE id = <user.id> AND version = <user.getExpectedVersion()>
|
|
150
|
-
await optimisticUpdate(store.em, User, user, { department: 'Research', updatedAt: user.updatedAt }, 'User');
|
|
151
|
-
|
|
152
|
-
try {
|
|
153
|
-
await optimisticDelete(store.em, User, staleUser, 'User');
|
|
154
|
-
} catch (error) {
|
|
155
|
-
if (error instanceof ConcurrencyConflictError) {
|
|
156
|
-
// error.expectedVersion is the version staleUser was loaded at; reload and retry
|
|
157
|
-
}
|
|
158
|
-
throw error;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
await store.em.transactional((em) => optimisticUpdate(em, User, user, fields, 'User')); // rejected
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
- `data` holds the columns to write; `version` is set from `entity.version`, so a caller
|
|
165
|
-
lists every other changed column, `updatedAt` included.
|
|
166
|
-
- No matching row: a refreshed read tells a missing row (`EntityNotFoundException`) from a
|
|
167
|
-
diverged version (`ConcurrencyConflictError`). More than one matching row throws an
|
|
168
|
-
`Error`.
|
|
169
|
-
- Neither function touches the cache, acknowledges the aggregate or publishes events;
|
|
170
|
-
`@PersistedWrite`, `@Cache` and `CommandBaseHandler` do that.
|
|
171
|
-
|
|
172
|
-
## Persistence errors
|
|
173
|
-
|
|
174
|
-
`MikroOrmDialect` implements core's `IPersistenceDialect`. Register it once the ORM is
|
|
175
|
-
initialized, and `@MapPersistenceErrors` / `@PersistedWrite` map unique violations by
|
|
176
|
-
entity property:
|
|
177
|
-
|
|
178
|
-
```typescript
|
|
179
|
-
import { setPersistenceDialect } from '@cqrs-ddd/core/persistence';
|
|
180
|
-
import { MikroOrmDialect } from '@cqrs-ddd/mikro-orm';
|
|
181
|
-
|
|
182
|
-
const orm = await MikroORM.init(options);
|
|
183
|
-
setPersistenceDialect(new MikroOrmDialect(orm));
|
|
184
|
-
|
|
185
|
-
// in a repository
|
|
186
|
-
@PersistedWrite<User>({ unique: { email: (user) => new UniqueEmailException(user) } })
|
|
187
|
-
async save(user: User): Promise<UserSnapshot> {
|
|
188
|
-
const snapshot = user.toJSON();
|
|
189
|
-
await optimisticUpdate(this.store.em, User, user, { email: snapshot.email }, 'User');
|
|
190
|
-
return snapshot;
|
|
191
|
-
}
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
A multi-property constraint is keyed by its declared name, passed as the constraint type:
|
|
195
|
-
|
|
196
|
-
```typescript
|
|
197
|
-
const ROLE_NAME = 'roles_tenant_name_unique';
|
|
198
|
-
// schema: uniques: [{ name: ROLE_NAME, properties: ['tenantId', 'name'] }]
|
|
199
|
-
|
|
200
|
-
@PersistedWrite<Role, typeof ROLE_NAME>({
|
|
201
|
-
unique: { [ROLE_NAME]: (role) => new DuplicateRoleNameException(role) },
|
|
202
|
-
})
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
It reads each entity's unique constraints from the ORM metadata: `unique: true` or
|
|
206
|
-
`unique: 'name'` on a property, and `uniques: [{ name?, properties }]` on the schema. A
|
|
207
|
-
single-property constraint is keyed by that property; a multi-property one by its
|
|
208
|
-
`name`, which it must declare. For a `UniqueConstraintViolationException`, PostgreSQL's
|
|
209
|
-
reported constraint name is matched against the declared name, or the naming strategy's
|
|
210
|
-
`indexName` when none is declared, and SQLite's reported `table.column` list against the
|
|
211
|
-
constraint's columns. Anything else yields no match and the original error is rethrown.
|
|
212
|
-
Construction fails when two constraints of one entity cover the same columns, because
|
|
213
|
-
SQLite could not tell them apart. Declare constraint names in the mapping, never in a
|
|
214
|
-
repository.
|
|
215
|
-
|
|
216
|
-
`mapPersistenceError(error, operation)` is the `otherwise` translator for transient
|
|
217
|
-
failures: `isTransientPersistenceError` recognizes retryable PostgreSQL SQLSTATEs
|
|
218
|
-
(`40001`, `40P01`, `55P03`, `57P01`–`57P03`, classes `08` and `53`), Node network errors,
|
|
219
|
-
`SQLITE_BUSY`/`SQLITE_LOCKED` and timeouts, through the `cause` chain, and wraps them in
|
|
220
|
-
core's `TransientOperationError`. Any other error is returned unchanged.
|
|
221
|
-
|
|
222
|
-
## Mapping a root entity
|
|
223
|
-
|
|
224
|
-
`rootEntityProperties(columns?)` and `versionProperty(column?)` give the `EntitySchema`
|
|
225
|
-
properties every `RootEntity` needs, with timestamps stored as epoch milliseconds
|
|
226
|
-
through `UnixTimestampType`. That type throws a `TypeError` for a value with no valid
|
|
227
|
-
time instead of storing `NaN`. The properties use `accessor: true`, so MikroORM reads
|
|
228
|
-
and writes them through the entity's getters and private setters, and queries use the
|
|
229
|
-
public names.
|
|
230
|
-
|
|
231
|
-
```typescript
|
|
232
|
-
export const UserSchema = new EntitySchema<User, AggregateRoot>({
|
|
233
|
-
class: User as any,
|
|
234
|
-
tableName: 'users',
|
|
235
|
-
properties: {
|
|
236
|
-
...rootEntityProperties(),
|
|
237
|
-
version: versionProperty(),
|
|
238
|
-
username: { type: 'string', length: 255, accessor: true },
|
|
239
|
-
department: { type: 'string', length: 255, nullable: true, accessor: true },
|
|
240
|
-
email: { type: 'string', length: 320, unique: true },
|
|
241
|
-
},
|
|
242
|
-
});
|
|
243
|
-
```
|
|
244
|
-
|
|
245
|
-
`rootEntityProperties({ createdAt: 'created', updatedAt: 'modified' })` renames the
|
|
246
|
-
columns; the defaults are `id`, `created_at` and `updated_at`.
|
|
247
|
-
|
|
248
|
-
Map a subclass's fields the same way. An entity written without version checks has no
|
|
249
|
-
version column; map its inherited `version` as `{ type: 'number', persist: false }`.
|
|
250
|
-
|
|
251
|
-
## The database cache
|
|
252
|
-
|
|
253
|
-
`MikroOrmCache(store, { defaultTtlMs?, logger? })` implements core's `IVersionedCache`
|
|
254
|
-
with one database row per key; every write is a compare-and-set in its own transaction.
|
|
255
|
-
`store` provides `em` and `transactional(work)`. Register `CacheEntrySchema` (or
|
|
256
|
-
`createCacheEntrySchema(table)`) with the ORM, and create the table in a migration with
|
|
257
|
-
`createCacheTableSql(table?)`, which covers PostgreSQL and SQLite.
|
|
258
|
-
|
|
259
|
-
```typescript
|
|
260
|
-
import { CACHE_TOKEN } from '@cqrs-ddd/core/persistence';
|
|
261
|
-
import { createCacheTableSql, MikroOrmCache } from '@cqrs-ddd/mikro-orm';
|
|
262
|
-
|
|
263
|
-
// once, in a migration
|
|
264
|
-
await orm.em.getConnection().execute(createCacheTableSql());
|
|
265
|
-
|
|
266
|
-
const cache = new MikroOrmCache<UserSnapshot>(store, {
|
|
267
|
-
defaultTtlMs: 5 * 60_000, // 0 never expires
|
|
268
|
-
logger: { warn: (message) => console.warn(message) },
|
|
269
|
-
});
|
|
270
|
-
const users = new UpdateUserRepository(cache, store);
|
|
271
|
-
const reads = new GetUserRepository(cache, store);
|
|
272
|
-
|
|
273
|
-
// NestJS
|
|
274
|
-
{
|
|
275
|
-
provide: CACHE_TOKEN,
|
|
276
|
-
useFactory: (store: TenantStore) => new MikroOrmCache(store, { logger: new Logger('MikroOrmCache') }),
|
|
277
|
-
inject: [STORE],
|
|
278
|
-
}
|
|
279
|
-
```
|
|
280
|
-
|
|
281
|
-
- `store.transactional(work)` must run `work` on a manager of its own, never the caller's
|
|
282
|
-
request or transaction manager; `TenantStore` does, and so does
|
|
283
|
-
`{ em: orm.em, transactional: (work) => orm.em.fork().transactional(work) }`.
|
|
284
|
-
- With a `TenantStore`, each tenant's cache rows live in that tenant's database or schema.
|
|
285
|
-
- Reads bypass the identity map, a reader never deletes an expired row, and a corrupted
|
|
286
|
-
payload throws instead of reading as a miss.
|
|
287
|
-
- `set` and `invalidate` throw when their compare-and-set cannot settle after 16 attempts.
|
|
288
|
-
|
|
289
|
-
## SQL identifiers
|
|
290
|
-
|
|
291
|
-
`isSqlIdentifier(name, { qualified? })` accepts an unquoted SQL identifier, optionally
|
|
292
|
-
schema-qualified. Use it before interpolating a name, such as a tenant schema, into SQL
|
|
293
|
-
text, where it cannot be passed as a parameter.
|
|
22
|
+
Published as an ES module; a CommonJS application loads it with `require()`. Coming from 0.3.x, see [Upgrading from 0.3.x](https://aristoteliss.github.io/nestjs-pipeline/upgrading/from-0-3/).
|
|
294
23
|
|
|
295
24
|
## License
|
|
296
25
|
|
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
"use strict";
|
|
2
1
|
/* Copyright (C) 2026-present Aristotelis — see repository license. */
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
exports.createCacheTableSql = createCacheTableSql;
|
|
6
|
-
exports.createCacheEntrySchema = createCacheEntrySchema;
|
|
7
|
-
const core_1 = require("@mikro-orm/core");
|
|
8
|
-
const sql_identifier_1 = require("../helpers/sql-identifier");
|
|
2
|
+
import { EntitySchema } from '@mikro-orm/core';
|
|
3
|
+
import { isSqlIdentifier } from '../helpers/sql-identifier.js';
|
|
9
4
|
/**
|
|
10
5
|
* One row of the {@link MikroOrmCache} table.
|
|
11
6
|
*
|
|
@@ -13,15 +8,14 @@ const sql_identifier_1 = require("../helpers/sql-identifier");
|
|
|
13
8
|
* `expiresAt` is epoch milliseconds, or `null` for no expiry; `revision` is the
|
|
14
9
|
* decimal revision token that fences concurrent fills.
|
|
15
10
|
*/
|
|
16
|
-
class CacheEntry {
|
|
11
|
+
export class CacheEntry {
|
|
17
12
|
key;
|
|
18
13
|
value;
|
|
19
14
|
expiresAt;
|
|
20
15
|
revision;
|
|
21
16
|
}
|
|
22
|
-
exports.CacheEntry = CacheEntry;
|
|
23
17
|
function assertSafeTable(table) {
|
|
24
|
-
if (!
|
|
18
|
+
if (!isSqlIdentifier(table, { qualified: true })) {
|
|
25
19
|
throw new Error(`Invalid cache table name "${table}". ` +
|
|
26
20
|
'Use an unquoted identifier like "cache" or "schema.cache".');
|
|
27
21
|
}
|
|
@@ -42,7 +36,7 @@ function assertSafeTable(table) {
|
|
|
42
36
|
* await orm.em.getConnection().execute(createCacheTableSql());
|
|
43
37
|
* ```
|
|
44
38
|
*/
|
|
45
|
-
function createCacheTableSql(table = 'cache') {
|
|
39
|
+
export function createCacheTableSql(table = 'cache') {
|
|
46
40
|
const name = assertSafeTable(table);
|
|
47
41
|
const index = `${name.slice(name.lastIndexOf('.') + 1)}_expires_at_idx`;
|
|
48
42
|
return `CREATE TABLE IF NOT EXISTS ${name} (
|
|
@@ -62,10 +56,10 @@ CREATE INDEX IF NOT EXISTS ${index} ON ${name} (expires_at);`;
|
|
|
62
56
|
*
|
|
63
57
|
* @param table - Table name, optionally schema-qualified. Default `'cache'`.
|
|
64
58
|
*/
|
|
65
|
-
function createCacheEntrySchema(table = 'cache') {
|
|
59
|
+
export function createCacheEntrySchema(table = 'cache') {
|
|
66
60
|
const safe = assertSafeTable(table);
|
|
67
61
|
const index = `${safe.slice(safe.lastIndexOf('.') + 1)}_expires_at_idx`;
|
|
68
|
-
return new
|
|
62
|
+
return new EntitySchema({
|
|
69
63
|
class: CacheEntry,
|
|
70
64
|
tableName: safe,
|
|
71
65
|
properties: {
|
|
@@ -88,5 +82,5 @@ function createCacheEntrySchema(table = 'cache') {
|
|
|
88
82
|
});
|
|
89
83
|
}
|
|
90
84
|
/** {@link createCacheEntrySchema} for the default `cache` table. */
|
|
91
|
-
|
|
85
|
+
export const CacheEntrySchema = createCacheEntrySchema();
|
|
92
86
|
//# sourceMappingURL=cache-entry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-entry.js","sourceRoot":"","sources":["../../src/cache/cache-entry.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cache-entry.js","sourceRoot":"","sources":["../../src/cache/cache-entry.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAE/D;;;;;;GAMG;AACH,MAAM,OAAO,UAAU;IACrB,GAAG,CAAU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Q,EAAE,IAAI;aACf;YACD,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,EAAE;SAChE;QACD,OAAO,EAAE;YACP;gBACE,IAAI,EAAE,KAAK;gBACX,UAAU,EAAE,CAAC,WAAW,CAAC;aAC1B;SACF;KACF,CAAC,CAAC;AACL,CAAC;AAED,oEAAoE;AACpE,MAAM,CAAC,MAAM,gBAAgB,GAAG,sBAAsB,EAAE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type CacheFillOptions, type CacheSetOptions, type CacheStateEntry, type IVersionedCache } from '@cqrs-ddd/core/application';
|
|
2
2
|
import type { ICacheLogger } from '@cqrs-ddd/core/persistence';
|
|
3
3
|
import type { EntityManager } from '@mikro-orm/core';
|
|
4
|
-
import type { IEntityManagerSource } from '../interfaces/entity-manager-source';
|
|
4
|
+
import type { IEntityManagerSource } from '../interfaces/entity-manager-source.js';
|
|
5
5
|
/**
|
|
6
6
|
* An {@link IEntityManagerSource} that can also run work in a transaction.
|
|
7
7
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mikro-orm.cache.d.ts","sourceRoot":"","sources":["../../src/cache/mikro-orm.cache.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"mikro-orm.cache.d.ts","sourceRoot":"","sources":["../../src/cache/mikro-orm.cache.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KA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AAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,OAAO,CAAC,CAmDlB;IAED;;OAEG;IACG,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAG7C;IAED;;OAEG;IACG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAsDzE;IAED;;;OAGG;IACG,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEvC;CACF"}
|
|
@@ -1,16 +1,13 @@
|
|
|
1
|
-
"use strict";
|
|
2
1
|
/* Copyright (C) 2026-present Aristotelis — see repository license. */
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const persistence_1 = require("@cqrs-ddd/core/persistence");
|
|
7
|
-
const cache_entry_1 = require("./cache-entry");
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { consoleCacheLogger, safeWarn } from '@cqrs-ddd/core/persistence';
|
|
4
|
+
import { CacheEntry } from './cache-entry.js';
|
|
8
5
|
/**
|
|
9
6
|
* Reads the committed row inside a CAS transaction, bypassing the identity map
|
|
10
7
|
* so a concurrent writer's revision is always observed.
|
|
11
8
|
*/
|
|
12
9
|
function readCommittedEntry(em, key) {
|
|
13
|
-
return em.findOne(
|
|
10
|
+
return em.findOne(CacheEntry, { key }, { refresh: true, disableIdentityMap: true });
|
|
14
11
|
}
|
|
15
12
|
/**
|
|
16
13
|
* Upper bound on compare-and-set re-reads. Each iteration only repeats after a
|
|
@@ -46,7 +43,7 @@ class CacheCasExhaustedError extends Error {
|
|
|
46
43
|
* }
|
|
47
44
|
* ```
|
|
48
45
|
*/
|
|
49
|
-
class MikroOrmCache {
|
|
46
|
+
export class MikroOrmCache {
|
|
50
47
|
store;
|
|
51
48
|
isVersioned = true;
|
|
52
49
|
logger;
|
|
@@ -54,14 +51,14 @@ class MikroOrmCache {
|
|
|
54
51
|
constructor(store, options) {
|
|
55
52
|
this.store = store;
|
|
56
53
|
this.defaultTtlMs = options?.defaultTtlMs ?? 60_000;
|
|
57
|
-
this.logger = options?.logger ??
|
|
54
|
+
this.logger = options?.logger ?? consoleCacheLogger('MikroOrmCache');
|
|
58
55
|
}
|
|
59
56
|
/**
|
|
60
57
|
* Observes the current key state and its revision token.
|
|
61
58
|
* Reads bypass the identity map to guarantee authoritative persistence visibility.
|
|
62
59
|
*/
|
|
63
60
|
async readState(key) {
|
|
64
|
-
const entry = await this.store.em.findOne(
|
|
61
|
+
const entry = await this.store.em.findOne(CacheEntry, { key }, { disableIdentityMap: true });
|
|
65
62
|
if (!entry) {
|
|
66
63
|
return { status: 'miss', revision: '0' };
|
|
67
64
|
}
|
|
@@ -89,7 +86,7 @@ class MikroOrmCache {
|
|
|
89
86
|
if (!existing) {
|
|
90
87
|
// `onConflictAction: 'ignore'` keeps a lost insert race from aborting
|
|
91
88
|
// the surrounding transaction, so the loop can re-read and retry.
|
|
92
|
-
await em.upsert(
|
|
89
|
+
await em.upsert(CacheEntry, { key, value: '', expiresAt: null, revision: '1' }, { onConflictAction: 'ignore' });
|
|
93
90
|
const inserted = await readCommittedEntry(em, key);
|
|
94
91
|
if (inserted && (inserted.revision ?? '0').toString() === '1') {
|
|
95
92
|
return '1';
|
|
@@ -98,7 +95,7 @@ class MikroOrmCache {
|
|
|
98
95
|
}
|
|
99
96
|
const currentRev = (existing.revision ?? '0').toString();
|
|
100
97
|
const nextRevision = (BigInt(currentRev) + 1n).toString();
|
|
101
|
-
const affected = await em.nativeUpdate(
|
|
98
|
+
const affected = await em.nativeUpdate(CacheEntry, { key, revision: existing.revision }, {
|
|
102
99
|
value: '',
|
|
103
100
|
expiresAt: null,
|
|
104
101
|
revision: nextRevision,
|
|
@@ -123,14 +120,14 @@ class MikroOrmCache {
|
|
|
123
120
|
if (observedRevision === '0') {
|
|
124
121
|
const existing = await readCommittedEntry(em, key);
|
|
125
122
|
if (!existing) {
|
|
126
|
-
await em.upsert(
|
|
123
|
+
await em.upsert(CacheEntry, { key, value: serialized, expiresAt, revision: '1' }, { onConflictAction: 'ignore' });
|
|
127
124
|
const inserted = await readCommittedEntry(em, key);
|
|
128
125
|
// A competing writer won the insert; this fill observed revision 0
|
|
129
126
|
// and must not overwrite it.
|
|
130
127
|
return inserted !== null && inserted.value === serialized;
|
|
131
128
|
}
|
|
132
129
|
if ((existing.revision ?? '0').toString() === '0') {
|
|
133
|
-
const affected = await em.nativeUpdate(
|
|
130
|
+
const affected = await em.nativeUpdate(CacheEntry, { key, revision: existing.revision }, {
|
|
134
131
|
value: serialized,
|
|
135
132
|
expiresAt,
|
|
136
133
|
revision: '1',
|
|
@@ -139,7 +136,7 @@ class MikroOrmCache {
|
|
|
139
136
|
}
|
|
140
137
|
return false;
|
|
141
138
|
}
|
|
142
|
-
const affected = await em.nativeUpdate(
|
|
139
|
+
const affected = await em.nativeUpdate(CacheEntry, { key, revision: observedRevision }, {
|
|
143
140
|
value: serialized,
|
|
144
141
|
expiresAt,
|
|
145
142
|
revision: nextRevision,
|
|
@@ -166,7 +163,7 @@ class MikroOrmCache {
|
|
|
166
163
|
for (let attempt = 0; attempt < MAX_CAS_ATTEMPTS; attempt++) {
|
|
167
164
|
const existing = await readCommittedEntry(em, key);
|
|
168
165
|
if (!existing) {
|
|
169
|
-
await em.upsert(
|
|
166
|
+
await em.upsert(CacheEntry, { key, value: serialized, expiresAt, revision: '1' }, { onConflictAction: 'ignore' });
|
|
170
167
|
continue;
|
|
171
168
|
}
|
|
172
169
|
if (isNewer && existing.value) {
|
|
@@ -177,7 +174,7 @@ class MikroOrmCache {
|
|
|
177
174
|
}
|
|
178
175
|
catch {
|
|
179
176
|
// An unparsable entry is treated as absent so the CAS update can heal corrupted data.
|
|
180
|
-
|
|
177
|
+
safeWarn(this.logger, `Failed to parse cached value (key digest: ${createHash('sha256').update(key).digest('hex')}); treating as absent.`);
|
|
181
178
|
}
|
|
182
179
|
if (parsed !== undefined && isNewer(parsed, value)) {
|
|
183
180
|
return;
|
|
@@ -186,7 +183,7 @@ class MikroOrmCache {
|
|
|
186
183
|
}
|
|
187
184
|
const currentRev = (existing.revision ?? '0').toString();
|
|
188
185
|
const nextRevision = (BigInt(currentRev) + 1n).toString();
|
|
189
|
-
const affected = await em.nativeUpdate(
|
|
186
|
+
const affected = await em.nativeUpdate(CacheEntry, { key, revision: existing.revision }, {
|
|
190
187
|
value: serialized,
|
|
191
188
|
expiresAt,
|
|
192
189
|
revision: nextRevision,
|
|
@@ -205,5 +202,4 @@ class MikroOrmCache {
|
|
|
205
202
|
await this.invalidate(key);
|
|
206
203
|
}
|
|
207
204
|
}
|
|
208
|
-
exports.MikroOrmCache = MikroOrmCache;
|
|
209
205
|
//# sourceMappingURL=mikro-orm.cache.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mikro-orm.cache.js","sourceRoot":"","sources":["../../src/cache/mikro-orm.cache.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"mikro-orm.cache.js","sourceRoot":"","sources":["../../src/cache/mikro-orm.cache.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAQzC,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAG1E,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C;;;GAGG;AACH,SAAS,kBAAkB,CAAC,EAAiB,EAAE,GAAW;IACxD,OAAO,EAAE,CAAC,OAAO,CACf,UAAU,EACV,EAAE,GAAG,EAAE,EACP,EAAE,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAC5C,CAAC;AACJ,CAAC;AA0BD;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,0DAA0D;AAC1D,MAAM,sBAAuB,SAAQ,K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AC;wBACD,IAAI,MAAM,KAAK,SAAS,IAAI,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC;4BACnD,OAAO;wBACT,CAAC;oBACH,CAAC;gBACH,CAAC;gBAED,MAAM,UAAU,GAAG,CAAC,QAAQ,CAAC,QAAQ,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,CAAC;gBACzD,MAAM,YAAY,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;gBAC1D,MAAM,QAAQ,GAAG,MAAM,EAAE,CAAC,YAAY,CACpC,UAAU,EACV,EAAE,GAAG,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE,EACpC;oBACE,KAAK,EAAE,UAAU;oBACjB,SAAS;oBACT,QAAQ,EAAE,YAAY;iBACvB,CACF,CAAC;gBAEF,IAAI,QAAQ,GAAG,CAAC;oBAAE,OAAO;YAC3B,CAAC;YAED,MAAM,IAAI,sBAAsB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,MAAM,CAAC,GAAW;QACtB,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;CACF"}
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.assertAutocommit = assertAutocommit;
|
|
4
1
|
/**
|
|
5
2
|
* Rejects an externally active transaction before a write that reports durable
|
|
6
3
|
* success.
|
|
@@ -19,7 +16,7 @@ exports.assertAutocommit = assertAutocommit;
|
|
|
19
16
|
* @param operation Name used in the error message, e.g. `'optimisticDelete'`.
|
|
20
17
|
* @throws {Error} When `em` is inside an active transaction.
|
|
21
18
|
*/
|
|
22
|
-
function assertAutocommit(em, operation) {
|
|
19
|
+
export function assertAutocommit(em, operation) {
|
|
23
20
|
if (em.isInTransaction()) {
|
|
24
21
|
throw new Error(`${operation} requires autocommit; external transactions need commit hooks.`);
|
|
25
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert-autocommit.js","sourceRoot":"","sources":["../../src/concurrency/assert-autocommit.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"assert-autocommit.js","sourceRoot":"","sources":["../../src/concurrency/assert-autocommit.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,gBAAgB,CAAC,EAAiB,EAAE,SAAiB;IACnE,IAAI,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CACb,GAAG,SAAS,gEAAgE,CAC7E,CAAC;IACJ,CAAC;AACH,CAAC"}
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
"use strict";
|
|
2
1
|
/* Copyright (C) 2026-present Aristotelis — see repository license. */
|
|
3
|
-
|
|
4
|
-
exports.expectOneRow = expectOneRow;
|
|
5
|
-
const domain_1 = require("@cqrs-ddd/core/domain");
|
|
2
|
+
import { ConcurrencyConflictError, EntityNotFoundException, } from '@cqrs-ddd/core/domain';
|
|
6
3
|
/**
|
|
7
4
|
* Checks the row count of a write filtered on `{ id, version }`: one row is
|
|
8
5
|
* success; none is diagnosed with one refreshed read on the same manager as
|
|
@@ -12,14 +9,14 @@ const domain_1 = require("@cqrs-ddd/core/domain");
|
|
|
12
9
|
* @throws {ConcurrencyConflictError} No row matched because the version diverged.
|
|
13
10
|
* @throws {Error} More than one row was affected.
|
|
14
11
|
*/
|
|
15
|
-
async function expectOneRow(affected, em, entityType, { id, expectedVersion }, entityName, verb) {
|
|
12
|
+
export async function expectOneRow(affected, em, entityType, { id, expectedVersion }, entityName, verb) {
|
|
16
13
|
if (affected === 1)
|
|
17
14
|
return;
|
|
18
15
|
if (affected === 0) {
|
|
19
16
|
const existing = await em.findOne(entityType, { id }, { refresh: true });
|
|
20
17
|
if (!existing)
|
|
21
|
-
throw new
|
|
22
|
-
throw new
|
|
18
|
+
throw new EntityNotFoundException(entityName, id);
|
|
19
|
+
throw new ConcurrencyConflictError(entityName, id, expectedVersion, existing.version);
|
|
23
20
|
}
|
|
24
21
|
throw new Error(`Expected one ${verb} ${entityName}, received ${affected}.`);
|
|
25
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conditioned-write.js","sourceRoot":"","sources":["../../src/concurrency/conditioned-write.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"conditioned-write.js","sourceRoot":"","sources":["../../src/concurrency/conditioned-write.ts"],"names":[],"mappings":"AAAA,sEAAsE;AAEtE,OAAO,EACL,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,uBAAuB,CAAC;AAgB/B;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,QAAgB,EAChB,EAAiB,EACjB,UAA+B,EAC/B,EAAE,EAAE,EAAE,eAAe,EAAkB,EACvC,UAAkB,EAClB,IAA2B;IAE3B,IAAI,QAAQ,KAAK,CAAC;QAAE,OAAO;IAC3B,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;QACnB,MAAM,QAAQ,GAAG,MAAM,EAAE,CAAC,OAAO,CAC/B,UAAU,EACV,EAAE,EAAE,EAA0B,EAC9B,EAAE,OAAO,EAAE,IAAI,EAAE,CAClB,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,uBAAuB,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;QACjE,MAAM,IAAI,wBAAwB,CAChC,UAAU,EACV,EAAE,EACF,eAAe,EACf,QAAQ,CAAC,OAAO,CACjB,CAAC;IACJ,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,gBAAgB,IAAI,IAAI,UAAU,cAAc,QAAQ,GAAG,CAAC,CAAC;AAC/E,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EntityManager, EntityName } from '@mikro-orm/core';
|
|
2
|
-
import { type VersionedAggregate } from './conditioned-write';
|
|
2
|
+
import { type VersionedAggregate } from './conditioned-write.js';
|
|
3
3
|
/**
|
|
4
4
|
* Executes a single version-conditioned, autocommitted `DELETE` on an aggregate.
|
|
5
5
|
*
|
|
@@ -11,8 +11,8 @@ import { type VersionedAggregate } from './conditioned-write';
|
|
|
11
11
|
* modified since the aggregate was loaded is not removed;
|
|
12
12
|
* - one affected row is success;
|
|
13
13
|
* - zero rows runs one refreshed diagnostic read: an absent row is
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* `EntityNotFoundException`, a present row is
|
|
15
|
+
* `ConcurrencyConflictError`;
|
|
16
16
|
* - any other count is an invariant violation, since the filter includes a
|
|
17
17
|
* primary key.
|
|
18
18
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"optimistic-delete.d.ts","sourceRoot":"","sources":["../../src/concurrency/optimistic-delete.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAe,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EAAgB,KAAK,kBAAkB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"optimistic-delete.d.ts","sourceRoot":"","sources":["../../src/concurrency/optimistic-delete.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAe,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EAAgB,KAAK,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,SAAS,kBAAkB,EACvE,EAAE,EAAE,aAAa,EACjB,UAAU,EAAE,UAAU,CAAC,OAAO,CAAC,EAC/B,SAAS,EAAE,OAAO,EAClB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAWf"}
|