@decohere/data-mikro-orm 0.0.0-stage → 0.0.1-dev.20261108.265

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/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025-2026 Typesmiths
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @decohere/data-mikro-orm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The MikroORM provider for [`@decohere/data`](../data/README.md): data's `IUnitOfWork` over MikroORM's own unit of work. MikroORM tracks the changes, keeps the identity map and orders the writes. This package adds Decohere's `Query<T>`, the outbox, and one rule: nothing is written before `commit()`. Each unit of work forks the entity manager with `flushMode: "commit"`, so a query never flushes pending changes.
4
+
5
+ ```ts
6
+ import { mikroOrm } from "@decohere/data-mikro-orm";
7
+
8
+ builder.use(
9
+ mikroOrm({
10
+ entities: [OrderSchema, LineSchema],
11
+ repositories: [OrderRepository],
12
+ bootstrap: postgres.bootstrap, // from @decohere/data-postgres
13
+ outbox: toOutboxMessage,
14
+ }),
15
+ );
16
+ ```
17
+
18
+ `mikroOrm()` reads the `database` config section, like `typeOrm()`. For each data source it:
19
+
20
+ - checks each data source's `auth` and `synchronize`, and creates its database, least-privilege roles and schema when the config asks, with the `bootstrap` you pass (`postgres.bootstrap` from `@decohere/data-postgres`);
21
+ - opens one MikroORM instance as the app role, named for the app in `application_name`;
22
+ - creates missing tables when `synchronize` is on (development only), never dropping any;
23
+ - runs `seed(orm)` when `seed` is on;
24
+ - registers a unit of work per request (`@injectUnitOfWork()`), the instance itself (`@injectMikroOrm()`) and a readiness check.
25
+
26
+ The container closes the instance when the app stops, after hosted services. Postgres only. Outside a plugin, `new MikroOrmUnitOfWork(orm.em, { outbox })` gives the same unit of work.
27
+
28
+ Map domain classes with `defineEntity({ class, … })` in infrastructure files, so the domain imports nothing from MikroORM. Map each child collection as a one-to-many with `orphanRemoval()`, so a child dropped from its aggregate is deleted.
29
+
30
+ Things to know:
31
+
32
+ - **MikroORM changes the classes it maps** at run time: field accessors, `toJSON` and a `__helper`. A loaded child also carries its parent. Map HTTP responses to DTOs rather than serialising entities. Don't map one class with two providers in one process.
33
+ - **Version fields** need a database default (`version int not null default 1`). MikroORM leaves the column to it on insert.
34
+ - **SQL a query can't express:** `uow.entityManager.getKysely()`, inside a repository.
@@ -0,0 +1,3 @@
1
+ export * from "./inject-mikro-orm.js";
2
+ export * from "./mikro-orm.module.js";
3
+ export * from "./mikro-orm.unit-of-work.js";
@@ -0,0 +1,17 @@
1
+ import { DEFAULT_DATA_SOURCE } from "@decohere/data";
2
+ import { inject } from "@decohere/crucible/decorators";
3
+ /** The MikroORM instance when `mikroOrm()` is used without `name`. */ export const MikroOrmToken = Symbol("MikroORM");
4
+ /**
5
+ * Container key for a data source's MikroORM instance. Distinct from the unit of work's key
6
+ * (the data source's name, or {@link DEFAULT_DATA_SOURCE}): the instance lives as long as the
7
+ * app, a unit of work as long as a request.
8
+ */ export function mikroOrmToken(name) {
9
+ if (name == null || name === DEFAULT_DATA_SOURCE) return MikroOrmToken;
10
+ return Symbol.for(`decohere:mikro-orm:${String(name)}`);
11
+ }
12
+ /**
13
+ * Inject the MikroORM instance, for work that outlives a request. Pass the same `name` as
14
+ * `mikroOrm({ name })`. Request work should use `injectUnitOfWork`.
15
+ */ export function injectMikroOrm(name) {
16
+ return inject(mikroOrmToken(name));
17
+ }
@@ -0,0 +1,101 @@
1
+ import { ReadinessCheckToken } from "@decohere/core/hosting";
2
+ import { DatabaseConfig, DataConfigurationError, dataSources } from "@decohere/data";
3
+ import { scribe } from "@decohere/scribe";
4
+ import { MikroORM } from "@mikro-orm/postgresql";
5
+ import { mikroOrmToken } from "./inject-mikro-orm.js";
6
+ import { MikroOrmUnitOfWork } from "./mikro-orm.unit-of-work.js";
7
+ export class MikroOrmModule {
8
+ /** Bootstraps and opens a MikroORM instance per data source. Returns the names it registered them under. */ async configure(options) {
9
+ const { applicationName, databaseConfig, moduleConfigurations, containerBuilder } = options;
10
+ const resolved = dataSources.resolve(databaseConfig, moduleConfigurations);
11
+ // Once, before any instance connects: data sources sharing a database must not race to create it.
12
+ await dataSources.prepare(resolved.map((r)=>r.connectionInfo), {
13
+ applicationName,
14
+ bootstrap: moduleConfigurations.find((m)=>m.bootstrap)?.bootstrap
15
+ });
16
+ return Promise.all(resolved.map(async ({ name, connectionInfo, module })=>{
17
+ const orm = await this.open(applicationName, name, connectionInfo, module);
18
+ containerBuilder.registerSingleton(mikroOrmToken(name), orm);
19
+ containerBuilder.registerRequestScoped(name, ()=>new MikroOrmUnitOfWork(orm.em, {
20
+ outbox: module.outbox
21
+ }));
22
+ containerBuilder.registerSingleton(ReadinessCheckToken, readinessCheck(name, orm));
23
+ for (const repository of module.repositories ?? []){
24
+ containerBuilder.registerRequestScoped(repository);
25
+ }
26
+ return name;
27
+ }));
28
+ }
29
+ async open(applicationName, name, connection, module) {
30
+ if (connection.provider !== "postgres") {
31
+ throw new DataConfigurationError(`Data source ${connection.name}: the MikroORM provider supports postgres, not ${connection.provider}`);
32
+ }
33
+ const log = scribe.logger(`MikroORM:${String(name)}`);
34
+ const orm = await MikroORM.init({
35
+ host: connection.host,
36
+ port: connection.port,
37
+ dbName: connection.database,
38
+ user: connection.username,
39
+ password: connection.password,
40
+ schema: connection.schema,
41
+ entities: module.entities,
42
+ driverOptions: {
43
+ application_name: applicationName
44
+ },
45
+ debug: [
46
+ "query",
47
+ "query-params"
48
+ ],
49
+ logger: (message)=>log.debug(message)
50
+ });
51
+ if (connection.synchronize) await synchronize(orm);
52
+ if (connection.seed) await module.seed?.(orm);
53
+ return orm;
54
+ }
55
+ }
56
+ /**
57
+ * Bring the tables up to the mappings, safely: add what they need, never drop what they don't name.
58
+ * MikroORM starts the update with `create schema`, which the app role may not run even when the
59
+ * schema exists; the bootstrap creates schemas, so those statements are left out.
60
+ */ async function synchronize(orm) {
61
+ const sql = await orm.schema.getUpdateSchemaSQL({
62
+ safe: true,
63
+ dropTables: false,
64
+ wrap: false
65
+ });
66
+ const statements = sql.split(/;\n/).map((statement)=>statement.trim().replace(/;$/, "")).filter((statement)=>statement.length > 0 && !/^create schema\b/i.test(statement));
67
+ for (const statement of statements)await orm.schema.execute(statement);
68
+ }
69
+ function readinessCheck(name, orm) {
70
+ return {
71
+ name: `mikro-orm:${String(name)}`,
72
+ async check () {
73
+ const status = await orm.checkConnection();
74
+ if ("reason" in status) throw new Error(status.reason, {
75
+ cause: status.error
76
+ });
77
+ }
78
+ };
79
+ }
80
+ /** Connect to the databases in the `database` config section with MikroORM. Requires `config(...)` on the builder. */ export function mikroOrm(config) {
81
+ return (builder)=>{
82
+ const names = [];
83
+ builder.registerPreBuildStep(async (configService, containerBuilder)=>{
84
+ const databaseConfig = await configService.get(DatabaseConfig);
85
+ names.push(...await new MikroOrmModule().configure({
86
+ applicationName: builder.applicationName,
87
+ databaseConfig,
88
+ moduleConfigurations: Array.isArray(config) ? config : [
89
+ config
90
+ ],
91
+ containerBuilder
92
+ }));
93
+ });
94
+ // The container disposes only what it handed out. Resolving each instance here makes the
95
+ // root container own it, as one of its first, so it closes last: after hosted services
96
+ // and the services that use it.
97
+ builder.registerPostBuildStep((container)=>{
98
+ for (const name of names)container.resolve(mikroOrmToken(name));
99
+ });
100
+ };
101
+ }
@@ -0,0 +1,122 @@
1
+ import { comparison, DataError, domainEvents, OptimisticLockError } from "@decohere/data";
2
+ import { FlushMode, LockMode, OptimisticLockError as MikroOptimisticLockError } from "@mikro-orm/core";
3
+ /**
4
+ * The MikroORM provider: data's unit of work over MikroORM's own. MikroORM tracks the changes,
5
+ * keeps the identity map and orders the writes; this adds Decohere's query, the outbox, and
6
+ * one rule: nothing is written before {@link commit}, so the entity manager never auto-flushes.
7
+ */ export class MikroOrmUnitOfWork {
8
+ options;
9
+ em;
10
+ failure;
11
+ disposed = false;
12
+ /** @param em the application's entity manager; each unit of work forks its own. */ constructor(em, options = {}){
13
+ this.options = options;
14
+ this.em = em.fork({
15
+ clear: true,
16
+ flushMode: FlushMode.COMMIT
17
+ });
18
+ }
19
+ /** The entity manager behind this unit of work, for SQL a query can't express (`em.getKysely()`), inside a repository. */ get entityManager() {
20
+ return this.em;
21
+ }
22
+ findById(type, key, include = []) {
23
+ this.assertUsable();
24
+ const where = key !== null && typeof key === "object" ? toFilter(key) : key;
25
+ return this.em.findOne(entityName(type), where, {
26
+ populate: include
27
+ });
28
+ }
29
+ async find(type, query = {}) {
30
+ this.assertUsable();
31
+ if (query.lock && !this.em.isInTransaction()) await this.em.begin();
32
+ const options = {
33
+ orderBy: query.orderBy,
34
+ limit: query.limit,
35
+ populate: query.include ?? [],
36
+ ...query.lock ? {
37
+ lockMode: LockMode.PESSIMISTIC_WRITE
38
+ } : {}
39
+ };
40
+ return this.em.find(entityName(type), toFilter(query.where ?? {}), options);
41
+ }
42
+ async findOne(type, query = {}) {
43
+ const [found] = await this.find(type, {
44
+ ...query,
45
+ limit: 1
46
+ });
47
+ return found ?? null;
48
+ }
49
+ add(entity) {
50
+ this.assertUsable();
51
+ this.em.persist(entity);
52
+ }
53
+ remove(entity) {
54
+ this.assertUsable();
55
+ this.em.remove(entity);
56
+ }
57
+ async beginTransaction() {
58
+ this.assertUsable();
59
+ if (!this.em.isInTransaction()) await this.em.begin();
60
+ }
61
+ async commit() {
62
+ this.assertUsable();
63
+ try {
64
+ if (this.options.outbox) {
65
+ const uow = this.em.getUnitOfWork();
66
+ const entities = [
67
+ ...uow.getIdentityMap().values(),
68
+ ...uow.getPersistStack()
69
+ ];
70
+ for (const row of domainEvents.collect(entities, this.options.outbox))this.em.persist(row);
71
+ }
72
+ // em.commit() flushes, then commits; outside a transaction, flush opens and commits its own.
73
+ if (this.em.isInTransaction()) await this.em.commit();
74
+ else await this.em.flush();
75
+ } catch (err) {
76
+ this.failure = err;
77
+ if (this.em.isInTransaction()) await this.em.rollback();
78
+ if (err instanceof MikroOptimisticLockError) {
79
+ throw new OptimisticLockError(err.message, {
80
+ cause: err
81
+ });
82
+ }
83
+ throw err;
84
+ }
85
+ }
86
+ async [Symbol.asyncDispose]() {
87
+ if (this.disposed) return;
88
+ this.disposed = true;
89
+ try {
90
+ if (this.em.isInTransaction()) await this.em.rollback();
91
+ } finally{
92
+ this.em.clear();
93
+ }
94
+ }
95
+ assertUsable() {
96
+ if (this.disposed) throw new DataError("This unit of work was disposed");
97
+ if (this.failure !== undefined) {
98
+ throw new DataError("A commit failed in this unit of work, so it was rolled back: start a new one", {
99
+ cause: this.failure
100
+ });
101
+ }
102
+ }
103
+ }
104
+ /** Decohere's entity class as MikroORM names it. The two describe the same constructor. */ function entityName(type) {
105
+ return type;
106
+ }
107
+ /** Decohere's conditions in MikroORM's operators: `{ in: [...] }` becomes `{ $in: [...] }`. */ function toFilter(where) {
108
+ return Object.fromEntries(Object.entries(where).map(([prop, condition])=>{
109
+ const operator = comparison.operatorOf(condition);
110
+ if (!operator) return [
111
+ prop,
112
+ condition
113
+ ];
114
+ const [op, operand] = operator;
115
+ return [
116
+ prop,
117
+ {
118
+ [`$${op}`]: operand
119
+ }
120
+ ];
121
+ }));
122
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@decohere/data-mikro-orm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1-dev.20261108.265",
4
+ "description": "MikroORM provider for @decohere/data: its own unit of work under data's contracts",
5
+ "keywords": [
6
+ "typescript",
7
+ "mikro-orm",
8
+ "postgres",
9
+ "data-access",
10
+ "decohere"
11
+ ],
12
+ "homepage": "https://github.com/typesmiths/decohere/tree/main/projects/data/data-mikro-orm#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/typesmiths/decohere/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/typesmiths/decohere.git",
19
+ "directory": "projects/data/data-mikro-orm"
20
+ },
21
+ "license": "ISC",
22
+ "author": "Typesmiths",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./types/src/index.d.ts",
27
+ "import": "./es6/src/index.js"
28
+ }
29
+ },
30
+ "scripts": {
31
+ "test": "echo \"Error: no test specified\" && exit 1"
32
+ },
33
+ "dependencies": {
34
+ "@decohere/core": "0.0.1-dev.20261108.265",
35
+ "@decohere/crucible": "0.0.1-dev.20261108.265",
36
+ "@decohere/data": "0.0.1-dev.20261108.265",
37
+ "@decohere/scribe": "0.0.1-dev.20261108.265",
38
+ "@mikro-orm/core": "^7.2.8",
39
+ "@mikro-orm/postgresql": "^7.2.8"
40
+ },
41
+ "devDependencies": {}
42
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./inject-mikro-orm.js";
2
+ export * from "./mikro-orm.module.js";
3
+ export * from "./mikro-orm.unit-of-work.js";
@@ -0,0 +1,13 @@
1
+ /** The MikroORM instance when `mikroOrm()` is used without `name`. */
2
+ export declare const MikroOrmToken: unique symbol;
3
+ /**
4
+ * Container key for a data source's MikroORM instance. Distinct from the unit of work's key
5
+ * (the data source's name, or {@link DEFAULT_DATA_SOURCE}): the instance lives as long as the
6
+ * app, a unit of work as long as a request.
7
+ */
8
+ export declare function mikroOrmToken(name?: string | symbol): symbol;
9
+ /**
10
+ * Inject the MikroORM instance, for work that outlives a request. Pass the same `name` as
11
+ * `mikroOrm({ name })`. Request work should use `injectUnitOfWork`.
12
+ */
13
+ export declare function injectMikroOrm(name?: string | symbol): (target: object, _propertyKey: string | symbol | undefined, idx: number) => void;
@@ -0,0 +1,31 @@
1
+ import type { BuilderPlugin } from "@decohere/core/hosting";
2
+ import type { Constructable } from "@decohere/core/reflection";
3
+ import type { ContainerBuilder } from "@decohere/crucible";
4
+ import { DatabaseConfig, type DataSourceBootstrap, type OutboxMapper } from "@decohere/data";
5
+ import { type Options, MikroORM } from "@mikro-orm/postgresql";
6
+ export type MikroOrmModuleConfig = {
7
+ /** The data source's name in the `database` config. Required when there is more than one. */
8
+ name?: string | symbol;
9
+ /** The mappings: `defineEntity({ class, … })` results or `EntitySchema`s. */
10
+ entities: NonNullable<Options["entities"]>;
11
+ repositories?: Constructable[];
12
+ /** Creates the database, roles and schema when the config asks: `postgres.bootstrap` from `@decohere/data-postgres`. */
13
+ bootstrap?: DataSourceBootstrap;
14
+ /** Writes the events aggregates raise to an outbox entity, in the same commit. */
15
+ outbox?: OutboxMapper;
16
+ /** Runs after connecting when the data source's `seed` is on. */
17
+ seed?: (orm: MikroORM) => Promise<void>;
18
+ };
19
+ export type MikroOrmModuleOptions = {
20
+ applicationName: string;
21
+ databaseConfig: DatabaseConfig;
22
+ moduleConfigurations: MikroOrmModuleConfig[];
23
+ containerBuilder: ContainerBuilder;
24
+ };
25
+ export declare class MikroOrmModule {
26
+ /** Bootstraps and opens a MikroORM instance per data source. Returns the names it registered them under. */
27
+ configure(options: MikroOrmModuleOptions): Promise<(string | symbol)[]>;
28
+ private open;
29
+ }
30
+ /** Connect to the databases in the `database` config section with MikroORM. Requires `config(...)` on the builder. */
31
+ export declare function mikroOrm(config: MikroOrmModuleConfig[] | MikroOrmModuleConfig): BuilderPlugin;
@@ -0,0 +1,30 @@
1
+ import { type EntityClass, type EntityKey, type Include, type IUnitOfWork, type OutboxMapper, type Query } from "@decohere/data";
2
+ import { type EntityManager } from "@mikro-orm/core";
3
+ export type MikroOrmUnitOfWorkOptions = {
4
+ /** Writes the events aggregates raise to an outbox entity, in the same commit. */
5
+ outbox?: OutboxMapper;
6
+ };
7
+ /**
8
+ * The MikroORM provider: data's unit of work over MikroORM's own. MikroORM tracks the changes,
9
+ * keeps the identity map and orders the writes; this adds Decohere's query, the outbox, and
10
+ * one rule: nothing is written before {@link commit}, so the entity manager never auto-flushes.
11
+ */
12
+ export declare class MikroOrmUnitOfWork implements IUnitOfWork {
13
+ private readonly options;
14
+ private readonly em;
15
+ private failure;
16
+ private disposed;
17
+ /** @param em the application's entity manager; each unit of work forks its own. */
18
+ constructor(em: EntityManager, options?: MikroOrmUnitOfWorkOptions);
19
+ /** The entity manager behind this unit of work, for SQL a query can't express (`em.getKysely()`), inside a repository. */
20
+ get entityManager(): EntityManager;
21
+ findById<T extends object>(type: EntityClass<T>, key: EntityKey<T>, include?: readonly Include<T>[]): Promise<T | null>;
22
+ find<T extends object>(type: EntityClass<T>, query?: Query<T>): Promise<T[]>;
23
+ findOne<T extends object>(type: EntityClass<T>, query?: Query<T>): Promise<T>;
24
+ add(entity: object): void;
25
+ remove(entity: object): void;
26
+ beginTransaction(): Promise<void>;
27
+ commit(): Promise<void>;
28
+ [Symbol.asyncDispose](): Promise<void>;
29
+ private assertUsable;
30
+ }