Initial commit - Event Planner application

This commit is contained in:
mberlin
2026-03-18 14:55:56 -03:00
commit 86d779eb4d
7548 changed files with 1006324 additions and 0 deletions

21
node_modules/@mikro-orm/decorators/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Martin Adámek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

225
node_modules/@mikro-orm/decorators/README.md generated vendored Normal file
View File

@@ -0,0 +1,225 @@
<h1 align="center">
<a href="https://mikro-orm.io"><img src="https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true" alt="MikroORM" /></a>
</h1>
TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL, SQLite (including libSQL), MSSQL and Oracle databases.
> Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).
[![NPM version](https://img.shields.io/npm/v/@mikro-orm/core.svg)](https://npmx.dev/package/@mikro-orm/core)
[![NPM dev version](https://img.shields.io/npm/v/@mikro-orm/core/next.svg)](https://npmx.dev/package/@mikro-orm/core)
[![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
[![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://npmx.dev/package/@mikro-orm/core)
[![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
[![Build Status](https://github.com/mikro-orm/mikro-orm/workflows/tests/badge.svg?branch=master)](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
## Quick Start
Install a driver package for your database:
```sh
npm install @mikro-orm/postgresql # PostgreSQL
npm install @mikro-orm/mysql # MySQL
npm install @mikro-orm/mariadb # MariaDB
npm install @mikro-orm/sqlite # SQLite
npm install @mikro-orm/libsql # libSQL / Turso
npm install @mikro-orm/mongodb # MongoDB
npm install @mikro-orm/mssql # MS SQL Server
npm install @mikro-orm/oracledb # Oracle
```
> If you use additional packages like `@mikro-orm/cli`, `@mikro-orm/migrations`, or `@mikro-orm/entity-generator`, install `@mikro-orm/core` explicitly as well. See the [quick start guide](https://mikro-orm.io/docs/quick-start) for details.
### Define Entities
The recommended way to define entities is using [`defineEntity`](https://mikro-orm.io/docs/define-entity) with `setClass`:
```typescript
import { defineEntity, p, MikroORM } from '@mikro-orm/postgresql';
const AuthorSchema = defineEntity({
name: 'Author',
properties: {
id: p.integer().primary(),
name: p.string(),
email: p.string(),
born: p.datetime().nullable(),
books: () => p.oneToMany(Book).mappedBy('author'),
},
});
export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);
const BookSchema = defineEntity({
name: 'Book',
properties: {
id: p.integer().primary(),
title: p.string(),
author: () => p.manyToOne(Author).inversedBy('books'),
},
});
export class Book extends BookSchema.class {}
BookSchema.setClass(Book);
```
You can also define entities using [decorators](https://mikro-orm.io/docs/defining-entities) or [`EntitySchema`](https://mikro-orm.io/docs/entity-schema). See the [defining entities guide](https://mikro-orm.io/docs/defining-entities) for all options.
### Initialize and Use
```typescript
import { MikroORM, RequestContext } from '@mikro-orm/postgresql';
const orm = await MikroORM.init({
entities: [Author, Book],
dbName: 'my-db',
});
// Create new entities
const author = orm.em.create(Author, {
name: 'Jon Snow',
email: 'snow@wall.st',
});
const book = orm.em.create(Book, {
title: 'My Life on The Wall',
author,
});
// Flush persists all tracked changes in a single transaction
await orm.em.flush();
```
### Querying
```typescript
// Find with relations
const authors = await orm.em.findAll(Author, {
populate: ['books'],
orderBy: { name: 'asc' },
});
// Type-safe QueryBuilder
const qb = orm.em.createQueryBuilder(Author);
const result = await qb
.select('*')
.where({ books: { title: { $like: '%Wall%' } } })
.getResult();
```
### Request Context
In web applications, use `RequestContext` to isolate the identity map per request:
```typescript
const app = express();
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
```
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
## Unit of Work
> Unit of Work maintains a list of objects (_entities_) affected by a business transaction
> and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
When you call `em.flush()`, all computed changes are queried inside a database transaction. This means you can control transaction boundaries simply by making changes to your entities and calling `flush()` when ready.
```typescript
const author = await em.findOneOrFail(Author, 1, {
populate: ['books'],
});
author.name = 'Jon Snow II';
author.books.getItems().forEach(book => book.title += ' (2nd ed.)');
author.books.add(orm.em.create(Book, { title: 'New Book', author }));
// Flush computes change sets and executes them in a single transaction
await em.flush();
```
The above flush will execute:
```sql
begin;
update "author" set "name" = 'Jon Snow II' where "id" = 1;
update "book"
set "title" = case
when ("id" = 1) then 'My Life on The Wall (2nd ed.)'
when ("id" = 2) then 'Another Book (2nd ed.)'
else "title" end
where "id" in (1, 2);
insert into "book" ("title", "author_id") values ('New Book', 1);
commit;
```
## Core Features
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities) — decorators, `EntitySchema`, or `defineEntity`
- [Identity Map](https://mikro-orm.io/docs/identity-map) and [Unit of Work](https://mikro-orm.io/docs/unit-of-work) — automatic change tracking
- [Entity References](https://mikro-orm.io/docs/entity-references) and [Collections](https://mikro-orm.io/docs/collections)
- [QueryBuilder](https://mikro-orm.io/docs/query-builder) and [Kysely Integration](https://mikro-orm.io/docs/kysely)
- [Transactions](https://mikro-orm.io/docs/transactions) and [Cascading](https://mikro-orm.io/docs/cascading)
- [Populating Relations](https://mikro-orm.io/docs/populating-relations) and [Loading Strategies](https://mikro-orm.io/docs/loading-strategies)
- [Filters](https://mikro-orm.io/docs/filters) and [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
- [Schema Generator](https://mikro-orm.io/docs/schema-generator) and [Migrations](https://mikro-orm.io/docs/migrations)
- [Entity Generator](https://mikro-orm.io/docs/entity-generator) and [Seeding](https://mikro-orm.io/docs/seeding)
- [Embeddables](https://mikro-orm.io/docs/embeddables), [Custom Types](https://mikro-orm.io/docs/custom-types), and [Serialization](https://mikro-orm.io/docs/serializing)
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
- [Entity Constructors](https://mikro-orm.io/docs/entity-constructors) and [Property Validation](https://mikro-orm.io/docs/property-validation)
- [Modelling Relationships](https://mikro-orm.io/docs/relationships) and [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
## Documentation
MikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
## Example Integrations
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
### TypeScript Examples
- [Express + MongoDB](https://github.com/mikro-orm/express-ts-example-app)
- [Nest + MySQL](https://github.com/mikro-orm/nestjs-example-app)
- [RealWorld example app (Nest + MySQL)](https://github.com/mikro-orm/nestjs-realworld-example-app)
- [Koa + SQLite](https://github.com/mikro-orm/koa-ts-example-app)
- [GraphQL + PostgreSQL](https://github.com/driescroons/mikro-orm-graphql-example)
- [Inversify + PostgreSQL](https://github.com/PodaruDragos/inversify-example-app)
- [NextJS + MySQL](https://github.com/jonahallibone/mikro-orm-nextjs)
- [Accounts.js REST and GraphQL authentication + SQLite](https://github.com/darkbasic/mikro-orm-accounts-example)
- [Nest + Shopify + PostgreSQL + GraphQL](https://github.com/Cloudshelf/Shopify_CSConnector)
- [Elysia.js + libSQL + Bun](https://github.com/mikro-orm/elysia-bun-example-app)
- [Electron.js + PostgreSQL](https://github.com/adnanlah/electron-mikro-orm-example-app)
### JavaScript Examples
- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
## Contributing
Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
## Authors
**Martin Adámek**
- Twitter: [@B4nan](https://twitter.com/B4nan)
- Github: [@b4nan](https://github.com/b4nan)
See also the list of contributors who [participated](https://github.com/mikro-orm/mikro-orm/contributors) in this project.
## Show Your Support
Please star this repository if this project helped you!
> If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
## License
Copyright © 2018-present [Martin Adámek](https://github.com/b4nan).
This project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.

5
node_modules/@mikro-orm/decorators/es/Check.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { type CheckConstraint } from '@mikro-orm/core';
/** Defines a database check constraint on a property (TC39 decorator). */
export declare function Check<T>(
options: CheckConstraint<T>,
): (value: unknown, context: ClassFieldDecoratorContext<T>) => void;

9
node_modules/@mikro-orm/decorators/es/Check.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/** Defines a database check constraint on a property (TC39 decorator). */
export function Check(options) {
return function (value, context) {
const meta = context.metadata;
meta.checks ??= [];
options.property ??= context.name;
meta.checks.push(options);
};
}

View File

@@ -0,0 +1,16 @@
import { type ContextProvider } from '../utils.js';
/** Wraps an async method in a new RequestContext, forking the EntityManager (TC39 decorator). */
export declare function CreateRequestContext<T extends object>(
contextProvider?: ContextProvider<T>,
respectExistingContext?: boolean,
): (
value: (this: T, ...args: any) => any,
context: ClassMethodDecoratorContext<T>,
) => (this: T, ...args: any[]) => Promise<any>;
/** Like `@CreateRequestContext`, but reuses an existing RequestContext if one is available (TC39 decorator). */
export declare function EnsureRequestContext<T extends object>(
context?: ContextProvider<T>,
): (
value: (this: T, ...args: any) => any,
context: ClassMethodDecoratorContext<T>,
) => (this: T, ...args: any[]) => Promise<any>;

View File

@@ -0,0 +1,33 @@
import { RequestContext, TransactionContext } from '@mikro-orm/core';
import { resolveContextProvider } from '../utils.js';
/** Wraps an async method in a new RequestContext, forking the EntityManager (TC39 decorator). */
export function CreateRequestContext(contextProvider, respectExistingContext = false) {
return function (value, context) {
const name = respectExistingContext ? 'EnsureRequestContext' : 'CreateRequestContext';
if (value.constructor.name !== 'AsyncFunction') {
throw new Error(`@${name}() should be use with async functions`);
}
return async function (...args) {
const em = await resolveContextProvider(this, contextProvider);
if (!em) {
throw new Error(
`@${name}() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@${name}(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`,
);
}
// reuse existing context if available for given respect `contextName`
if (respectExistingContext && RequestContext.getEntityManager(em.name)) {
return value.apply(this, args);
}
// Otherwise, the outer tx context would be preferred.
const txContext = TransactionContext.currentTransactionContext();
const provider = txContext ? TransactionContext : RequestContext;
return txContext
? provider.create(em.fork({ useContext: true }), () => value.apply(this, args))
: provider.create(em, () => value.apply(this, args));
};
};
}
/** Like `@CreateRequestContext`, but reuses an existing RequestContext if one is available (TC39 decorator). */
export function EnsureRequestContext(context) {
return CreateRequestContext(context, true);
}

View File

@@ -0,0 +1,5 @@
import { type Constructor, type EmbeddableOptions, type EntityClass } from '@mikro-orm/core';
/** Marks a class as an embeddable type (TC39 decorator). */
export declare function Embeddable<Owner extends EntityClass<unknown> & Constructor>(
options?: EmbeddableOptions<Owner>,
): (target: Owner, context: ClassDecoratorContext<Owner>) => Owner;

14
node_modules/@mikro-orm/decorators/es/Embeddable.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { Utils } from '@mikro-orm/core';
import { getMetadataFromDecorator } from '../utils.js';
/** Marks a class as an embeddable type (TC39 decorator). */
export function Embeddable(options = {}) {
return function (target, context) {
const meta = getMetadataFromDecorator(target);
const metadata = { ...context.metadata };
Utils.mergeConfig(meta, metadata, options);
meta.class = target;
meta.name = meta.class.name;
meta.embeddable = true;
return target;
};
}

6
node_modules/@mikro-orm/decorators/es/Embedded.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type EntityName, type EmbeddedOptions } from '@mikro-orm/core';
/** Defines an embedded property on an entity (TC39 decorator). */
export declare function Embedded<Owner extends object, Target>(
type?: EmbeddedOptions<Owner, Target> | (() => EntityName<Target> | EntityName[]),
options?: EmbeddedOptions<Owner, Target>,
): (value: unknown, context: ClassFieldDecoratorContext<Owner>) => void;

15
node_modules/@mikro-orm/decorators/es/Embedded.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { ReferenceKind, Utils } from '@mikro-orm/core';
import { prepareMetadataContext } from '../utils.js';
/** Defines an embedded property on an entity (TC39 decorator). */
export function Embedded(type = {}, options = {}) {
return function (value, context) {
const meta = prepareMetadataContext(context, ReferenceKind.EMBEDDED);
options = type instanceof Function ? { entity: type, ...options } : { ...type, ...options };
Utils.defaultValue(options, 'prefix', true);
meta.properties[context.name] = {
name: context.name,
kind: ReferenceKind.EMBEDDED,
...options,
};
};
}

5
node_modules/@mikro-orm/decorators/es/Entity.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { type Constructor, type EntityOptions, type EntityClass } from '@mikro-orm/core';
/** Marks a class as a MikroORM entity (TC39 decorator). */
export declare function Entity<Owner extends EntityClass<unknown> & Constructor>(
options?: EntityOptions<Owner>,
): (target: Owner, context: ClassDecoratorContext<Owner>) => void;

14
node_modules/@mikro-orm/decorators/es/Entity.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { Utils } from '@mikro-orm/core';
import { getMetadataFromDecorator } from '../utils.js';
/** Marks a class as a MikroORM entity (TC39 decorator). */
export function Entity(options = {}) {
return function (target, context) {
const meta = getMetadataFromDecorator(target);
const metadata = { ...context.metadata };
Utils.mergeConfig(meta, metadata, options);
meta.class = target;
if (!options.abstract || meta.discriminatorColumn) {
meta.name = context.name;
}
};
}

5
node_modules/@mikro-orm/decorators/es/Enum.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { type EnumOptions, type AnyEntity, type Dictionary } from '@mikro-orm/core';
/** Defines an enum property on an entity (TC39 decorator). */
export declare function Enum<Owner extends object>(
options?: EnumOptions<AnyEntity> | (() => Dictionary),
): (target: unknown, context: ClassFieldDecoratorContext<Owner>) => void;

15
node_modules/@mikro-orm/decorators/es/Enum.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { ReferenceKind } from '@mikro-orm/core';
import { prepareMetadataContext } from '../utils.js';
/** Defines an enum property on an entity (TC39 decorator). */
export function Enum(options = {}) {
return function (target, context) {
const meta = prepareMetadataContext(context);
options = options instanceof Function ? { items: options } : options;
meta.properties[context.name] = {
name: context.name,
kind: ReferenceKind.SCALAR,
enum: true,
...options,
};
};
}

3
node_modules/@mikro-orm/decorators/es/Filter.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import { type FilterDef, type EntityClass } from '@mikro-orm/core';
/** Registers a named filter on an entity class (TC39 decorator). */
export declare function Filter<T extends EntityClass<unknown>>(options: FilterDef<T>): (target: T) => void;

8
node_modules/@mikro-orm/decorators/es/Filter.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { getMetadataFromDecorator } from '../utils.js';
/** Registers a named filter on an entity class (TC39 decorator). */
export function Filter(options) {
return function (target) {
const meta = getMetadataFromDecorator(target);
meta.filters[options.name] = options;
};
}

6
node_modules/@mikro-orm/decorators/es/Formula.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type FormulaCallback, type PropertyOptions } from '@mikro-orm/core';
/** Defines a computed SQL formula property on an entity (TC39 decorator). */
export declare function Formula<Owner extends object>(
formula: string | FormulaCallback<Owner>,
options?: PropertyOptions<Owner>,
): (value: unknown, context: ClassFieldDecoratorContext<Owner>) => void;

14
node_modules/@mikro-orm/decorators/es/Formula.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { ReferenceKind } from '@mikro-orm/core';
import { prepareMetadataContext } from '../utils.js';
/** Defines a computed SQL formula property on an entity (TC39 decorator). */
export function Formula(formula, options = {}) {
return function (value, context) {
const meta = prepareMetadataContext(context);
meta.properties[context.name] = {
name: context.name,
kind: ReferenceKind.SCALAR,
formula,
...options,
};
};
}

9
node_modules/@mikro-orm/decorators/es/Indexed.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { type IndexOptions, type UniqueOptions, type Constructor } from '@mikro-orm/core';
/** Defines a database index on a property or entity class (TC39 decorator). */
export declare function Index<T extends object, H extends string>(
options?: IndexOptions<T, H>,
): (value: unknown, context: ClassDecoratorContext<T & Constructor> | ClassFieldDecoratorContext<T>) => any;
/** Defines a unique constraint on a property or entity class (TC39 decorator). */
export declare function Unique<T extends object, H extends string>(
options?: UniqueOptions<T, H>,
): (value: unknown, context: ClassDecoratorContext<T & Constructor> | ClassFieldDecoratorContext<T>) => any;

19
node_modules/@mikro-orm/decorators/es/Indexed.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
function createDecorator(options, unique) {
return function (value, context) {
const meta = context.metadata;
if (context.kind === 'field') {
options.properties ??= context.name;
}
const key = unique ? 'uniques' : 'indexes';
meta[key] ??= [];
meta[key].push(options);
};
}
/** Defines a database index on a property or entity class (TC39 decorator). */
export function Index(options = {}) {
return createDecorator(options, false);
}
/** Defines a unique constraint on a property or entity class (TC39 decorator). */
export function Unique(options = {}) {
return createDecorator(options, true);
}

View File

@@ -0,0 +1,7 @@
import { type EntityName, type ManyToManyOptions, type Collection } from '@mikro-orm/core';
/** Defines a many-to-many relationship (TC39 decorator). */
export declare function ManyToMany<Target extends object, Owner extends object>(
entity?: ManyToManyOptions<Owner, Target> | string | (() => EntityName<Target>),
mappedBy?: (string & keyof Target) | ((e: Target) => any),
options?: Partial<ManyToManyOptions<Owner, Target>>,
): (_: unknown, context: ClassFieldDecoratorContext<Owner, Collection<Target> | undefined>) => void;

12
node_modules/@mikro-orm/decorators/es/ManyToMany.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import { ReferenceKind, Utils } from '@mikro-orm/core';
import { prepareMetadataContext, processDecoratorParameters } from '../utils.js';
/** Defines a many-to-many relationship (TC39 decorator). */
export function ManyToMany(entity, mappedBy, options = {}) {
return function (_, context) {
const meta = prepareMetadataContext(context, ReferenceKind.MANY_TO_MANY);
options = processDecoratorParameters({ entity, mappedBy, options });
const property = { name: context.name, kind: ReferenceKind.MANY_TO_MANY };
meta.properties[context.name] ??= {};
Utils.mergeConfig(meta.properties[context.name], property, options);
};
}

6
node_modules/@mikro-orm/decorators/es/ManyToOne.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type ManyToOneOptions, type EntityName, type Ref } from '@mikro-orm/core';
/** Defines a many-to-one relationship (TC39 decorator). */
export declare function ManyToOne<Target extends object, Owner extends object>(
entity?: ManyToOneOptions<Owner, Target> | ((e?: Owner) => EntityName<Target> | EntityName[]),
options?: Partial<ManyToOneOptions<Owner, Target>>,
): (_: unknown, context: ClassFieldDecoratorContext<Owner, Target | undefined | null | Ref<Target>>) => void;

11
node_modules/@mikro-orm/decorators/es/ManyToOne.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import { ReferenceKind, Utils } from '@mikro-orm/core';
import { prepareMetadataContext, processDecoratorParameters } from '../utils.js';
/** Defines a many-to-one relationship (TC39 decorator). */
export function ManyToOne(entity = {}, options = {}) {
return function (_, context) {
const meta = prepareMetadataContext(context, ReferenceKind.MANY_TO_ONE);
options = processDecoratorParameters({ entity, options });
const property = { name: context.name, kind: ReferenceKind.MANY_TO_ONE };
meta.properties[context.name] = Utils.mergeConfig(meta.properties[context.name] ?? {}, property, options);
};
}

10
node_modules/@mikro-orm/decorators/es/OneToMany.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { type Collection, type EntityName, type OneToManyOptions } from '@mikro-orm/core';
/** Defines a one-to-many relationship (TC39 decorator). */
export declare function OneToMany<Target extends object, Owner extends object>(
entity: string | ((e?: Owner) => EntityName<Target>),
mappedBy: (string & keyof Target) | ((e: Target) => any),
options?: Partial<OneToManyOptions<Owner, Target>>,
): (value: unknown, context: ClassFieldDecoratorContext<Owner, Collection<Target> | undefined>) => void;
export declare function OneToMany<Target extends object, Owner extends object>(
options: OneToManyOptions<Owner, Target>,
): (value: unknown, context: ClassFieldDecoratorContext<Owner, Collection<Target> | undefined>) => void;

11
node_modules/@mikro-orm/decorators/es/OneToMany.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import { ReferenceKind, Utils } from '@mikro-orm/core';
import { prepareMetadataContext, processDecoratorParameters } from '../utils.js';
export function OneToMany(entity, mappedBy, options = {}) {
return function (value, context) {
const meta = prepareMetadataContext(context, ReferenceKind.ONE_TO_MANY);
options = processDecoratorParameters({ entity, mappedBy, options });
const property = { name: context.name, kind: ReferenceKind.ONE_TO_MANY };
meta.properties[context.name] ??= {};
Utils.mergeConfig(meta.properties[context.name], property, options);
};
}

7
node_modules/@mikro-orm/decorators/es/OneToOne.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { type EntityName, type OneToOneOptions, type Ref } from '@mikro-orm/core';
/** Defines a one-to-one relationship (TC39 decorator). */
export declare function OneToOne<Target extends object, Owner extends object>(
entity?: OneToOneOptions<Owner, Target> | string | ((e: Owner) => EntityName<Target> | EntityName[]),
mappedByOrOptions?: (string & keyof Target) | ((e: Target) => any) | Partial<OneToOneOptions<Owner, Target>>,
options?: Partial<OneToOneOptions<Owner, Target>>,
): (_: unknown, context: ClassFieldDecoratorContext<Owner, Target | Ref<Target> | null | undefined>) => void;

13
node_modules/@mikro-orm/decorators/es/OneToOne.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { ReferenceKind } from '@mikro-orm/core';
import { prepareMetadataContext, processDecoratorParameters } from '../utils.js';
/** Defines a one-to-one relationship (TC39 decorator). */
export function OneToOne(entity, mappedByOrOptions, options = {}) {
const mappedBy = typeof mappedByOrOptions === 'object' ? mappedByOrOptions.mappedBy : mappedByOrOptions;
options = typeof mappedByOrOptions === 'object' ? { ...mappedByOrOptions, ...options } : options;
return function (_, context) {
const meta = prepareMetadataContext(context, ReferenceKind.ONE_TO_ONE);
options = processDecoratorParameters({ entity, mappedBy, options });
const property = { name: context.name, kind: ReferenceKind.ONE_TO_ONE };
meta.properties[context.name] = Object.assign(meta.properties[context.name] ?? {}, property, options);
};
}

View File

@@ -0,0 +1,9 @@
import { type PrimaryKeyOptions, type SerializedPrimaryKeyOptions } from '@mikro-orm/core';
/** Marks a property as the primary key of an entity (TC39 decorator). */
export declare function PrimaryKey<T extends object>(
options?: PrimaryKeyOptions<T>,
): (value: unknown, context: ClassFieldDecoratorContext<T>) => void;
/** Marks a property as the serialized form of the primary key, e.g. for MongoDB ObjectId (TC39 decorator). */
export declare function SerializedPrimaryKey<T extends object>(
options?: SerializedPrimaryKeyOptions<T>,
): (value: unknown, context: ClassFieldDecoratorContext<T>) => void;

22
node_modules/@mikro-orm/decorators/es/PrimaryKey.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import { ReferenceKind } from '@mikro-orm/core';
import { prepareMetadataContext } from '../utils.js';
function createDecorator(options, serialized) {
return function (value, context) {
const meta = prepareMetadataContext(context, ReferenceKind.SCALAR);
const key = serialized ? 'serializedPrimaryKey' : 'primary';
options[key] = true;
meta.properties[context.name] = {
name: context.name,
kind: ReferenceKind.SCALAR,
...options,
};
};
}
/** Marks a property as the primary key of an entity (TC39 decorator). */
export function PrimaryKey(options = {}) {
return createDecorator(options, false);
}
/** Marks a property as the serialized form of the primary key, e.g. for MongoDB ObjectId (TC39 decorator). */
export function SerializedPrimaryKey(options = {}) {
return createDecorator(options, true);
}

13
node_modules/@mikro-orm/decorators/es/Property.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { type PropertyOptions } from '@mikro-orm/core';
/** Defines a scalar property on an entity (TC39 decorator). */
export declare function Property<T extends object>(
options?: PropertyOptions<T>,
): (
value: unknown,
context:
| ClassFieldDecoratorContext<T>
| ClassGetterDecoratorContext<T>
| ClassSetterDecoratorContext<T>
| ClassAccessorDecoratorContext<T>
| ClassMethodDecoratorContext<T>,
) => void;

42
node_modules/@mikro-orm/decorators/es/Property.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
import { ReferenceKind, Utils } from '@mikro-orm/core';
import { prepareMetadataContext } from '../utils.js';
/** Defines a scalar property on an entity (TC39 decorator). */
export function Property(options = {}) {
return function (value, context) {
const meta = prepareMetadataContext(context, ReferenceKind.SCALAR);
const { check, ...opts } = options;
const prop = { kind: ReferenceKind.SCALAR, ...opts };
const name = options.name ?? context.name;
meta.checks ??= [];
if (context.name !== name) {
Utils.renameKey(options, 'name', 'fieldName');
}
if (context.kind === 'field') {
prop.name = context.name;
prop.getter = false;
prop.setter = false;
} else if (context.kind === 'getter') {
prop.name = context.name;
prop.getter = true;
prop.setter = false;
} else if (context.kind === 'setter') {
prop.name = context.name;
prop.getter = false;
prop.setter = true;
} else if (context.kind === 'accessor') {
prop.name = context.name;
prop.getter = true;
prop.setter = true;
} else if (context.kind === 'method') {
prop.getter = true;
prop.persist = false;
prop.type = 'method';
prop.getterName = context.name;
prop.name = name;
}
if (check) {
meta.checks.push({ property: prop.name, expression: check });
}
meta.properties[prop.name] = prop;
};
}

View File

@@ -0,0 +1,20 @@
import { type TransactionOptions } from '@mikro-orm/core';
import { type ContextProvider } from '../utils.js';
type TransactionalOptions<T> = TransactionOptions & {
context?: ContextProvider<T>;
contextName?: string;
};
/**
* This decorator wraps the method with `em.transactional()`, so you can provide `TransactionOptions` just like with `em.transactional()`.
* The difference is that you can specify the context in which the transaction begins by providing `context` option,
* and if omitted, the transaction will begin in the current context implicitly.
* It works on async functions and can be nested with `em.transactional()`.
* Unlike `em.transactional()`, this decorator uses `REQUIRED` propagation by default, which means it will join existing transactions.
*/
export declare function Transactional<
Owner extends object,
Value extends (this: Owner, ...args: any) => any = (this: Owner, ...args: any) => any,
>(
options?: TransactionalOptions<Owner>,
): (value: Value, context: ClassMethodDecoratorContext<Owner, Value>) => (this: Owner, ...args: any) => Promise<any>;
export {};

30
node_modules/@mikro-orm/decorators/es/Transactional.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
import { RequestContext, TransactionContext, TransactionPropagation } from '@mikro-orm/core';
import { resolveContextProvider } from '../utils.js';
/**
* This decorator wraps the method with `em.transactional()`, so you can provide `TransactionOptions` just like with `em.transactional()`.
* The difference is that you can specify the context in which the transaction begins by providing `context` option,
* and if omitted, the transaction will begin in the current context implicitly.
* It works on async functions and can be nested with `em.transactional()`.
* Unlike `em.transactional()`, this decorator uses `REQUIRED` propagation by default, which means it will join existing transactions.
*/
export function Transactional(options = {}) {
return function (value, context) {
if (value.constructor.name !== 'AsyncFunction') {
throw new Error('@Transactional() should be use with async functions');
}
return async function (...args) {
const { context, contextName, ...txOptions } = options;
txOptions.propagation ??= TransactionPropagation.REQUIRED;
const em =
(await resolveContextProvider(this, context)) ||
TransactionContext.getEntityManager(contextName) ||
RequestContext.getEntityManager(contextName);
if (!em) {
throw new Error(
`@Transactional() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@Transactional(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`,
);
}
return em.transactional(() => value.apply(this, args), txOptions);
};
};
}

48
node_modules/@mikro-orm/decorators/es/hooks.d.ts generated vendored Normal file
View File

@@ -0,0 +1,48 @@
/** Called before a new entity is persisted to the database (TC39 decorator). */
export declare function BeforeCreate(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/** Called after a new entity has been persisted to the database (TC39 decorator). */
export declare function AfterCreate(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/** Called before an existing entity is updated in the database (TC39 decorator). */
export declare function BeforeUpdate(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/** Called after an existing entity has been updated in the database (TC39 decorator). */
export declare function AfterUpdate(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/** Called before an entity is upserted (TC39 decorator). */
export declare function BeforeUpsert(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/** Called after an entity has been upserted (TC39 decorator). */
export declare function AfterUpsert(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/** Called when an entity is instantiated by the EntityManager (TC39 decorator). */
export declare function OnInit(): (value: (...args: any[]) => unknown, context: ClassMethodDecoratorContext) => void;
/** Called after an entity is loaded from the database (TC39 decorator). */
export declare function OnLoad(): (value: (...args: any[]) => unknown, context: ClassMethodDecoratorContext) => void;
/**
* Called before deleting entity, but only when providing initialized entity to EM#remove()
*/
export declare function BeforeDelete(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;
/**
* Called after deleting entity, but only when providing initialized entity to EM#remove()
*/
export declare function AfterDelete(): (
value: (...args: any[]) => unknown,
context: ClassMethodDecoratorContext,
) => void;

53
node_modules/@mikro-orm/decorators/es/hooks.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
import { EventType } from '@mikro-orm/core';
function hook(type) {
return function (value, context) {
const meta = context.metadata;
meta.hooks ??= {};
meta.hooks[type] ??= [];
meta.hooks[type].push(value);
};
}
/** Called before a new entity is persisted to the database (TC39 decorator). */
export function BeforeCreate() {
return hook(EventType.beforeCreate);
}
/** Called after a new entity has been persisted to the database (TC39 decorator). */
export function AfterCreate() {
return hook(EventType.afterCreate);
}
/** Called before an existing entity is updated in the database (TC39 decorator). */
export function BeforeUpdate() {
return hook(EventType.beforeUpdate);
}
/** Called after an existing entity has been updated in the database (TC39 decorator). */
export function AfterUpdate() {
return hook(EventType.afterUpdate);
}
/** Called before an entity is upserted (TC39 decorator). */
export function BeforeUpsert() {
return hook(EventType.beforeUpsert);
}
/** Called after an entity has been upserted (TC39 decorator). */
export function AfterUpsert() {
return hook(EventType.afterUpsert);
}
/** Called when an entity is instantiated by the EntityManager (TC39 decorator). */
export function OnInit() {
return hook(EventType.onInit);
}
/** Called after an entity is loaded from the database (TC39 decorator). */
export function OnLoad() {
return hook(EventType.onLoad);
}
/**
* Called before deleting entity, but only when providing initialized entity to EM#remove()
*/
export function BeforeDelete() {
return hook(EventType.beforeDelete);
}
/**
* Called after deleting entity, but only when providing initialized entity to EM#remove()
*/
export function AfterDelete() {
return hook(EventType.afterDelete);
}

17
node_modules/@mikro-orm/decorators/es/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
export * from './PrimaryKey.js';
export * from './Entity.js';
export * from './OneToOne.js';
export * from './ManyToOne.js';
export * from './ManyToMany.js';
export * from './OneToMany.js';
export * from './Property.js';
export * from './Check.js';
export * from './Enum.js';
export * from './Formula.js';
export * from './Indexed.js';
export * from './Embeddable.js';
export * from './Embedded.js';
export * from './Filter.js';
export * from './CreateRequestContext.js';
export * from './hooks.js';
export * from './Transactional.js';

17
node_modules/@mikro-orm/decorators/es/index.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
export * from './PrimaryKey.js';
export * from './Entity.js';
export * from './OneToOne.js';
export * from './ManyToOne.js';
export * from './ManyToMany.js';
export * from './OneToMany.js';
export * from './Property.js';
export * from './Check.js';
export * from './Enum.js';
export * from './Formula.js';
export * from './Indexed.js';
export * from './Embeddable.js';
export * from './Embedded.js';
export * from './Filter.js';
export * from './CreateRequestContext.js';
export * from './hooks.js';
export * from './Transactional.js';

5
node_modules/@mikro-orm/decorators/legacy/Check.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { type CheckConstraint, type EntityClass } from '@mikro-orm/core';
/** Defines a database check constraint on a property or entity class (legacy TypeScript decorator). */
export declare function Check<T>(
options: CheckConstraint<T>,
): (target: T, propertyName?: T extends EntityClass<unknown> ? undefined : keyof T) => any;

13
node_modules/@mikro-orm/decorators/legacy/Check.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { getMetadataFromDecorator } from '../utils.js';
/** Defines a database check constraint on a property or entity class (legacy TypeScript decorator). */
export function Check(options) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(propertyName ? target.constructor : target);
options.property ??= propertyName;
meta.checks.push(options);
if (!propertyName) {
return target;
}
return undefined;
};
}

View File

@@ -0,0 +1,8 @@
import { type ContextProvider } from '../utils.js';
/** Wraps an async method in a new RequestContext, forking the EntityManager (legacy TypeScript decorator). */
export declare function CreateRequestContext<T extends object>(
context?: ContextProvider<T>,
respectExistingContext?: boolean,
): MethodDecorator;
/** Like `@CreateRequestContext`, but reuses an existing RequestContext if one is available (legacy TypeScript decorator). */
export declare function EnsureRequestContext<T extends object>(context?: ContextProvider<T>): MethodDecorator;

View File

@@ -0,0 +1,35 @@
import { RequestContext, TransactionContext } from '@mikro-orm/core';
import { resolveContextProvider } from '../utils.js';
/** Wraps an async method in a new RequestContext, forking the EntityManager (legacy TypeScript decorator). */
export function CreateRequestContext(context, respectExistingContext = false) {
return function (target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
const name = respectExistingContext ? 'EnsureRequestContext' : 'CreateRequestContext';
if (originalMethod.constructor.name !== 'AsyncFunction') {
throw new Error(`@${name}() should be use with async functions`);
}
descriptor.value = async function (...args) {
const em = await resolveContextProvider(this, context);
if (!em) {
throw new Error(
`@${name}() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@${name}(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`,
);
}
// reuse existing context if available for given respect `contextName`
if (respectExistingContext && RequestContext.getEntityManager(em.name)) {
return originalMethod.apply(this, args);
}
// Otherwise, the outer tx context would be preferred.
const txContext = TransactionContext.currentTransactionContext();
const provider = txContext ? TransactionContext : RequestContext;
return txContext
? provider.create(em.fork({ useContext: true }), () => originalMethod.apply(this, args))
: provider.create(em, () => originalMethod.apply(this, args));
};
return descriptor;
};
}
/** Like `@CreateRequestContext`, but reuses an existing RequestContext if one is available (legacy TypeScript decorator). */
export function EnsureRequestContext(context) {
return CreateRequestContext(context, true);
}

View File

@@ -0,0 +1,3 @@
import { type EmbeddableOptions } from '@mikro-orm/core';
/** Marks a class as an embeddable type (legacy TypeScript decorator). */
export declare function Embeddable<T>(options?: EmbeddableOptions<T>): (target: T) => T;

View File

@@ -0,0 +1,12 @@
import { getMetadataFromDecorator } from '../utils.js';
/** Marks a class as an embeddable type (legacy TypeScript decorator). */
export function Embeddable(options = {}) {
return function (target) {
const meta = getMetadataFromDecorator(target);
meta.class = target;
meta.name = meta.class.name;
meta.embeddable = true;
Object.assign(meta, options);
return target;
};
}

View File

@@ -0,0 +1,6 @@
import { type AnyEntity, type EntityName, type EmbeddedOptions } from '@mikro-orm/core';
/** Defines an embedded property on an entity (legacy TypeScript decorator). */
export declare function Embedded<Owner extends object, Target>(
type?: EmbeddedOptions<Owner, Target> | (() => EntityName<Target> | EntityName[]),
options?: EmbeddedOptions<Owner, Target>,
): (target: AnyEntity, propertyName: string) => void;

16
node_modules/@mikro-orm/decorators/legacy/Embedded.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import { ReferenceKind, Utils } from '@mikro-orm/core';
import { validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
/** Defines an embedded property on an entity (legacy TypeScript decorator). */
export function Embedded(type = {}, options = {}) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(target.constructor);
validateSingleDecorator(meta, propertyName, ReferenceKind.EMBEDDED);
options = type instanceof Function ? { entity: type, ...options } : { ...type, ...options };
Utils.defaultValue(options, 'prefix', true);
meta.properties[propertyName] = {
name: propertyName,
kind: ReferenceKind.EMBEDDED,
...options,
};
};
}

View File

@@ -0,0 +1,3 @@
import { type EntityClass, type EntityOptions } from '@mikro-orm/core';
/** Marks a class as a MikroORM entity (legacy TypeScript decorator). */
export declare function Entity<T extends EntityClass<unknown>>(options?: EntityOptions<T>): (target: T) => void;

13
node_modules/@mikro-orm/decorators/legacy/Entity.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { Utils } from '@mikro-orm/core';
import { getMetadataFromDecorator } from '../utils.js';
/** Marks a class as a MikroORM entity (legacy TypeScript decorator). */
export function Entity(options = {}) {
return function (target) {
const meta = getMetadataFromDecorator(target);
Utils.mergeConfig(meta, options);
meta.class = target;
if (!options.abstract || meta.discriminatorColumn) {
meta.name = target.name;
}
};
}

5
node_modules/@mikro-orm/decorators/legacy/Enum.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { type EnumOptions, type AnyEntity, type Dictionary } from '@mikro-orm/core';
/** Defines an enum property on an entity (legacy TypeScript decorator). */
export declare function Enum<T extends object>(
options?: EnumOptions<AnyEntity> | (() => Dictionary),
): (target: T, propertyName: string) => void;

15
node_modules/@mikro-orm/decorators/legacy/Enum.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { ReferenceKind } from '@mikro-orm/core';
import { getMetadataFromDecorator } from '../utils.js';
/** Defines an enum property on an entity (legacy TypeScript decorator). */
export function Enum(options = {}) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(target.constructor);
options = options instanceof Function ? { items: options } : options;
meta.properties[propertyName] = {
name: propertyName,
kind: ReferenceKind.SCALAR,
enum: true,
...options,
};
};
}

View File

@@ -0,0 +1,3 @@
import { type FilterDef, type EntityClass } from '@mikro-orm/core';
/** Registers a named filter on an entity class (legacy TypeScript decorator). */
export declare function Filter<T extends EntityClass<unknown>>(options: FilterDef<T>): (target: T) => void;

8
node_modules/@mikro-orm/decorators/legacy/Filter.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { getMetadataFromDecorator } from '../utils.js';
/** Registers a named filter on an entity class (legacy TypeScript decorator). */
export function Filter(options) {
return function (target) {
const meta = getMetadataFromDecorator(target);
meta.filters[options.name] = options;
};
}

View File

@@ -0,0 +1,6 @@
import { type FormulaCallback, type PropertyOptions } from '@mikro-orm/core';
/** Defines a computed SQL formula property on an entity (legacy TypeScript decorator). */
export declare function Formula<T extends object>(
formula: string | FormulaCallback<T>,
options?: PropertyOptions<T>,
): (target: T, propertyName: string) => void;

14
node_modules/@mikro-orm/decorators/legacy/Formula.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { ReferenceKind } from '@mikro-orm/core';
import { getMetadataFromDecorator } from '../utils.js';
/** Defines a computed SQL formula property on an entity (legacy TypeScript decorator). */
export function Formula(formula, options = {}) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(target.constructor);
meta.properties[propertyName] = {
name: propertyName,
kind: ReferenceKind.SCALAR,
formula,
...options,
};
};
}

View File

@@ -0,0 +1,9 @@
import { type EntityClass, type IndexOptions, type UniqueOptions } from '@mikro-orm/core';
/** Defines a database index on a property or entity class (legacy TypeScript decorator). */
export declare function Index<T extends object, H extends string>(
options?: IndexOptions<T, H>,
): (target: T, propertyName?: T extends EntityClass<unknown> ? undefined : keyof T) => any;
/** Defines a unique constraint on a property or entity class (legacy TypeScript decorator). */
export declare function Unique<T extends object, H extends string>(
options?: UniqueOptions<T, H>,
): (target: T, propertyName?: T extends EntityClass<unknown> ? undefined : keyof T) => any;

21
node_modules/@mikro-orm/decorators/legacy/Indexed.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { getMetadataFromDecorator } from '../utils.js';
function createDecorator(options, unique) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(propertyName ? target.constructor : target);
options.properties ??= propertyName;
const key = unique ? 'uniques' : 'indexes';
meta[key].push(options);
if (!propertyName) {
return target;
}
return undefined;
};
}
/** Defines a database index on a property or entity class (legacy TypeScript decorator). */
export function Index(options = {}) {
return createDecorator(options, false);
}
/** Defines a unique constraint on a property or entity class (legacy TypeScript decorator). */
export function Unique(options = {}) {
return createDecorator(options, true);
}

View File

@@ -0,0 +1,11 @@
import { type EntityName, type ManyToManyOptions } from '@mikro-orm/core';
/** Defines a many-to-many relationship (legacy TypeScript decorator). */
export declare function ManyToMany<Target extends object, Owner extends object>(
entity: () => EntityName<Target>,
mappedBy?: (string & keyof Target) | ((e: Target) => any),
options?: Partial<ManyToManyOptions<Owner, Target>>,
): (target: Owner, propertyName: keyof Owner) => void;
export declare function ManyToMany<Target extends object, Owner extends object>(entity: string, options?: any): never;
export declare function ManyToMany<Target extends object, Owner extends object>(
options?: ManyToManyOptions<Owner, Target>,
): (target: Owner, propertyName: keyof Owner) => void;

View File

@@ -0,0 +1,11 @@
import { ReferenceKind } from '@mikro-orm/core';
import { processDecoratorParameters, validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
export function ManyToMany(entity, mappedBy, options = {}) {
return function (target, propertyName) {
options = processDecoratorParameters({ entity, mappedBy, options });
const meta = getMetadataFromDecorator(target.constructor);
validateSingleDecorator(meta, propertyName, ReferenceKind.MANY_TO_MANY);
const property = { name: propertyName, kind: ReferenceKind.MANY_TO_MANY };
meta.properties[propertyName] = Object.assign(meta.properties[propertyName] ?? {}, property, options);
};
}

View File

@@ -0,0 +1,10 @@
import { type ManyToOneOptions, type EntityName } from '@mikro-orm/core';
/** Defines a many-to-one relationship (legacy TypeScript decorator). */
export declare function ManyToOne<Target extends object, Owner extends object>(
entity: (e?: any) => EntityName<Target> | EntityName[],
options?: Partial<ManyToOneOptions<Owner, Target>>,
): (target: Owner, propertyName: string) => void;
export declare function ManyToOne<Target extends object, Owner extends object>(entity: string, options?: any): never;
export declare function ManyToOne<Target extends object, Owner extends object>(
options?: ManyToOneOptions<Owner, Target>,
): (target: Owner, propertyName: string) => void;

11
node_modules/@mikro-orm/decorators/legacy/ManyToOne.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import { ReferenceKind } from '@mikro-orm/core';
import { processDecoratorParameters, validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
export function ManyToOne(entity = {}, options = {}) {
return function (target, propertyName) {
options = processDecoratorParameters({ entity, options });
const meta = getMetadataFromDecorator(target.constructor);
validateSingleDecorator(meta, propertyName, ReferenceKind.MANY_TO_ONE);
const property = { name: propertyName, kind: ReferenceKind.MANY_TO_ONE };
meta.properties[propertyName] = Object.assign(meta.properties[propertyName] ?? {}, property, options);
};
}

View File

@@ -0,0 +1,10 @@
import { type EntityName, type OneToManyOptions } from '@mikro-orm/core';
/** Defines a one-to-many relationship (legacy TypeScript decorator). */
export declare function OneToMany<Target extends object, Owner extends object>(
entity: (e?: any) => EntityName<Target>,
mappedBy: (string & keyof Target) | ((e: Target) => any),
options?: Partial<OneToManyOptions<Owner, Target>>,
): (target: Owner, propertyName: string) => void;
export declare function OneToMany<Target extends object, Owner extends object>(
options: OneToManyOptions<Owner, Target>,
): (target: Owner, propertyName: string) => void;

11
node_modules/@mikro-orm/decorators/legacy/OneToMany.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import { ReferenceKind } from '@mikro-orm/core';
import { processDecoratorParameters, validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
export function OneToMany(entity, mappedBy, options = {}) {
return function (target, propertyName) {
options = processDecoratorParameters({ entity, mappedBy, options });
const meta = getMetadataFromDecorator(target.constructor);
validateSingleDecorator(meta, propertyName, ReferenceKind.ONE_TO_MANY);
const property = { name: propertyName, kind: ReferenceKind.ONE_TO_MANY };
meta.properties[propertyName] = Object.assign(meta.properties[propertyName] ?? {}, property, options);
};
}

View File

@@ -0,0 +1,10 @@
import { type EntityName, type OneToOneOptions } from '@mikro-orm/core';
/** Defines a one-to-one relationship (legacy TypeScript decorator). */
export declare function OneToOne<Target, Owner>(
entity: (e: Owner) => EntityName<Target> | EntityName[],
mappedByOrOptions?: (string & keyof Target) | ((e: Target) => any) | Partial<OneToOneOptions<Owner, Target>>,
options?: Partial<OneToOneOptions<Owner, Target>>,
): (target: Owner, propertyName: string) => void;
export declare function OneToOne<Target, Owner>(
entity?: OneToOneOptions<Owner, Target>,
): (target: Owner, propertyName: string) => void;

13
node_modules/@mikro-orm/decorators/legacy/OneToOne.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { ReferenceKind } from '@mikro-orm/core';
import { processDecoratorParameters, validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
export function OneToOne(entity, mappedByOrOptions, options = {}) {
const mappedBy = typeof mappedByOrOptions === 'object' ? mappedByOrOptions.mappedBy : mappedByOrOptions;
options = typeof mappedByOrOptions === 'object' ? { ...mappedByOrOptions, ...options } : options;
return function (target, propertyName) {
options = processDecoratorParameters({ entity, mappedBy, options });
const meta = getMetadataFromDecorator(target.constructor);
validateSingleDecorator(meta, propertyName, ReferenceKind.ONE_TO_ONE);
const property = { name: propertyName, kind: ReferenceKind.ONE_TO_ONE };
meta.properties[propertyName] = Object.assign(meta.properties[propertyName] ?? {}, property, options);
};
}

View File

@@ -0,0 +1,9 @@
import { type PrimaryKeyOptions, type SerializedPrimaryKeyOptions } from '@mikro-orm/core';
/** Marks a property as the primary key of an entity (legacy TypeScript decorator). */
export declare function PrimaryKey<T extends object>(
options?: PrimaryKeyOptions<T>,
): (target: T, propertyName: string) => void;
/** Marks a property as the serialized form of the primary key, e.g. for MongoDB ObjectId (legacy TypeScript decorator). */
export declare function SerializedPrimaryKey<T extends object>(
options?: SerializedPrimaryKeyOptions<T>,
): (target: T, propertyName: string) => void;

View File

@@ -0,0 +1,23 @@
import { ReferenceKind } from '@mikro-orm/core';
import { validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
function createDecorator(options, serialized) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(target.constructor);
validateSingleDecorator(meta, propertyName, ReferenceKind.SCALAR);
const k = serialized ? 'serializedPrimaryKey' : 'primary';
options[k] = true;
meta.properties[propertyName] = {
name: propertyName,
kind: ReferenceKind.SCALAR,
...options,
};
};
}
/** Marks a property as the primary key of an entity (legacy TypeScript decorator). */
export function PrimaryKey(options = {}) {
return createDecorator(options, false);
}
/** Marks a property as the serialized form of the primary key, e.g. for MongoDB ObjectId (legacy TypeScript decorator). */
export function SerializedPrimaryKey(options = {}) {
return createDecorator(options, true);
}

View File

@@ -0,0 +1,5 @@
import { type PropertyOptions } from '@mikro-orm/core';
/** Defines a scalar property on an entity (legacy TypeScript decorator). */
export declare function Property<T extends object>(
options?: PropertyOptions<T>,
): (target: T, propertyName: string) => void;

30
node_modules/@mikro-orm/decorators/legacy/Property.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
import { Utils, ReferenceKind } from '@mikro-orm/core';
import { validateSingleDecorator, getMetadataFromDecorator } from '../utils.js';
/** Defines a scalar property on an entity (legacy TypeScript decorator). */
export function Property(options = {}) {
return function (target, propertyName) {
const meta = getMetadataFromDecorator(target.constructor);
const desc = Object.getOwnPropertyDescriptor(target, propertyName) || {};
validateSingleDecorator(meta, propertyName, ReferenceKind.SCALAR);
const name = options.name || propertyName;
if (propertyName !== name && !(desc.value instanceof Function)) {
Utils.renameKey(options, 'name', 'fieldName');
}
options.name = propertyName;
const { check, ...opts } = options;
const prop = { kind: ReferenceKind.SCALAR, ...opts };
prop.getter = !!desc.get;
prop.setter = !!desc.set;
if (desc.value instanceof Function) {
prop.getter = true;
prop.persist = false;
prop.type = 'method';
prop.getterName = propertyName;
prop.name = name;
}
if (check) {
meta.checks.push({ property: prop.name, expression: check });
}
meta.properties[prop.name] = prop;
};
}

View File

@@ -0,0 +1,7 @@
import 'reflect-metadata';
import { type EntityMetadata, type EntityProperty, MetadataProvider } from '@mikro-orm/core';
/** Metadata provider that uses `reflect-metadata` to infer property types from TypeScript's emitted design:type metadata. */
export declare class ReflectMetadataProvider extends MetadataProvider {
loadEntityMetadata(meta: EntityMetadata): void;
protected initPropertyType(meta: EntityMetadata, prop: EntityProperty): void;
}

View File

@@ -0,0 +1,54 @@
import 'reflect-metadata';
import { EntitySchema, MetadataProvider, ReferenceKind, Utils } from '@mikro-orm/core';
/** Metadata provider that uses `reflect-metadata` to infer property types from TypeScript's emitted design:type metadata. */
export class ReflectMetadataProvider extends MetadataProvider {
loadEntityMetadata(meta) {
// load types and column names
for (const prop of meta.props) {
/* v8 ignore next */
if (typeof prop.entity === 'string') {
throw new Error(
`Relation target needs to be an entity class or EntitySchema instance, '${prop.entity}' given instead for ${meta.className}.${prop.name}.`,
);
} else if (prop.entity) {
const tmp = prop.entity();
prop.type = Array.isArray(tmp)
? tmp
.map(t => Utils.className(t))
.sort()
.join(' | ')
: Utils.className(tmp);
prop.target = EntitySchema.is(tmp) ? tmp.meta.class : tmp;
} else {
this.initPropertyType(meta, prop);
}
}
}
initPropertyType(meta, prop) {
const type = Reflect.getMetadata('design:type', meta.prototype, prop.name);
if (
!prop.type &&
(!type || (type === Object && prop.kind !== ReferenceKind.SCALAR)) &&
!(prop.enum && (prop.items?.length ?? 0) > 0)
) {
throw new Error(
`Please provide either 'type' or 'entity' attribute in ${meta.className}.${prop.name}. Make sure you have 'emitDecoratorMetadata' enabled in your tsconfig.json.`,
);
}
// Force mapping to UnknownType which is a string when we see just `Object`, as that often means failed inference.
// This is to prevent defaulting to JSON column type, which can often be hard to revert and cause hard to understand issues with PKs.
// If there are explicitly provided `columnTypes`, we use those instead for the inference, this way
// we can have things like `columnType: 'timestamp'` be respected as `type: 'Date'`.
if (prop.kind === ReferenceKind.SCALAR && type === Object && !prop.columnTypes) {
prop.type ??= 'any';
return;
}
let typeName = type?.name;
if (typeName && ['string', 'number', 'boolean', 'array', 'object'].includes(typeName.toLowerCase())) {
typeName = typeName.toLowerCase();
}
prop.type ??= typeName;
prop.runtimeType ??= typeName;
prop.target = type;
}
}

View File

@@ -0,0 +1,15 @@
import { type TransactionOptions } from '@mikro-orm/core';
import { type ContextProvider } from '../utils.js';
type TransactionalOptions<T> = TransactionOptions & {
context?: ContextProvider<T>;
contextName?: string;
};
/**
* This decorator wraps the method with `em.transactional()`, so you can provide `TransactionOptions` just like with `em.transactional()`.
* The difference is that you can specify the context in which the transaction begins by providing `context` option,
* and if omitted, the transaction will begin in the current context implicitly.
* It works on async functions and can be nested with `em.transactional()`.
* Unlike `em.transactional()`, this decorator uses `REQUIRED` propagation by default, which means it will join existing transactions.
*/
export declare function Transactional<T extends object>(options?: TransactionalOptions<T>): MethodDecorator;
export {};

View File

@@ -0,0 +1,32 @@
import { TransactionPropagation, RequestContext, TransactionContext } from '@mikro-orm/core';
import { resolveContextProvider } from '../utils.js';
/**
* This decorator wraps the method with `em.transactional()`, so you can provide `TransactionOptions` just like with `em.transactional()`.
* The difference is that you can specify the context in which the transaction begins by providing `context` option,
* and if omitted, the transaction will begin in the current context implicitly.
* It works on async functions and can be nested with `em.transactional()`.
* Unlike `em.transactional()`, this decorator uses `REQUIRED` propagation by default, which means it will join existing transactions.
*/
export function Transactional(options = {}) {
return function (target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
if (originalMethod.constructor.name !== 'AsyncFunction') {
throw new Error('@Transactional() should be use with async functions');
}
descriptor.value = async function (...args) {
const { context, contextName, ...txOptions } = options;
txOptions.propagation ??= TransactionPropagation.REQUIRED;
const em =
(await resolveContextProvider(this, context)) ||
TransactionContext.getEntityManager(contextName) ||
RequestContext.getEntityManager(contextName);
if (!em) {
throw new Error(
`@Transactional() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@Transactional(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`,
);
}
return em.transactional(() => originalMethod.apply(this, args), txOptions);
};
return descriptor;
};
}

24
node_modules/@mikro-orm/decorators/legacy/hooks.d.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
/** Called before a new entity is persisted to the database (legacy TypeScript decorator). */
export declare function BeforeCreate(): (target: any, method: string) => void;
/** Called after a new entity has been persisted to the database (legacy TypeScript decorator). */
export declare function AfterCreate(): (target: any, method: string) => void;
/** Called before an existing entity is updated in the database (legacy TypeScript decorator). */
export declare function BeforeUpdate(): (target: any, method: string) => void;
/** Called after an existing entity has been updated in the database (legacy TypeScript decorator). */
export declare function AfterUpdate(): (target: any, method: string) => void;
/** Called before an entity is upserted (legacy TypeScript decorator). */
export declare function BeforeUpsert(): (target: any, method: string) => void;
/** Called after an entity has been upserted (legacy TypeScript decorator). */
export declare function AfterUpsert(): (target: any, method: string) => void;
/** Called when an entity is instantiated by the EntityManager (legacy TypeScript decorator). */
export declare function OnInit(): (target: any, method: string) => void;
/** Called after an entity is loaded from the database (legacy TypeScript decorator). */
export declare function OnLoad(): (target: any, method: string) => void;
/**
* Called before deleting entity, but only when providing initialized entity to EM#remove()
*/
export declare function BeforeDelete(): (target: any, method: string) => void;
/**
* Called after deleting entity, but only when providing initialized entity to EM#remove()
*/
export declare function AfterDelete(): (target: any, method: string) => void;

53
node_modules/@mikro-orm/decorators/legacy/hooks.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
import { EventType } from '@mikro-orm/core';
import { getMetadataFromDecorator } from '../utils.js';
function hook(type) {
return function (target, method) {
const meta = getMetadataFromDecorator(target.constructor);
meta.hooks[type] ??= [];
meta.hooks[type].push(method);
};
}
/** Called before a new entity is persisted to the database (legacy TypeScript decorator). */
export function BeforeCreate() {
return hook(EventType.beforeCreate);
}
/** Called after a new entity has been persisted to the database (legacy TypeScript decorator). */
export function AfterCreate() {
return hook(EventType.afterCreate);
}
/** Called before an existing entity is updated in the database (legacy TypeScript decorator). */
export function BeforeUpdate() {
return hook(EventType.beforeUpdate);
}
/** Called after an existing entity has been updated in the database (legacy TypeScript decorator). */
export function AfterUpdate() {
return hook(EventType.afterUpdate);
}
/** Called before an entity is upserted (legacy TypeScript decorator). */
export function BeforeUpsert() {
return hook(EventType.beforeUpsert);
}
/** Called after an entity has been upserted (legacy TypeScript decorator). */
export function AfterUpsert() {
return hook(EventType.afterUpsert);
}
/** Called when an entity is instantiated by the EntityManager (legacy TypeScript decorator). */
export function OnInit() {
return hook(EventType.onInit);
}
/** Called after an entity is loaded from the database (legacy TypeScript decorator). */
export function OnLoad() {
return hook(EventType.onLoad);
}
/**
* Called before deleting entity, but only when providing initialized entity to EM#remove()
*/
export function BeforeDelete() {
return hook(EventType.beforeDelete);
}
/**
* Called after deleting entity, but only when providing initialized entity to EM#remove()
*/
export function AfterDelete() {
return hook(EventType.afterDelete);
}

18
node_modules/@mikro-orm/decorators/legacy/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
export * from './PrimaryKey.js';
export * from './Entity.js';
export * from './OneToOne.js';
export * from './ManyToOne.js';
export * from './ManyToMany.js';
export * from './OneToMany.js';
export * from './Property.js';
export * from './Check.js';
export * from './Enum.js';
export * from './Formula.js';
export * from './Indexed.js';
export * from './Embeddable.js';
export * from './Embedded.js';
export * from './Filter.js';
export * from './CreateRequestContext.js';
export * from './hooks.js';
export * from './Transactional.js';
export * from './ReflectMetadataProvider.js';

18
node_modules/@mikro-orm/decorators/legacy/index.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
export * from './PrimaryKey.js';
export * from './Entity.js';
export * from './OneToOne.js';
export * from './ManyToOne.js';
export * from './ManyToMany.js';
export * from './OneToMany.js';
export * from './Property.js';
export * from './Check.js';
export * from './Enum.js';
export * from './Formula.js';
export * from './Indexed.js';
export * from './Embeddable.js';
export * from './Embedded.js';
export * from './Filter.js';
export * from './CreateRequestContext.js';
export * from './hooks.js';
export * from './Transactional.js';
export * from './ReflectMetadataProvider.js';

66
node_modules/@mikro-orm/decorators/package.json generated vendored Normal file
View File

@@ -0,0 +1,66 @@
{
"name": "@mikro-orm/decorators",
"version": "7.0.2",
"description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
"keywords": [
"data-mapper",
"ddd",
"entity",
"identity-map",
"javascript",
"js",
"mariadb",
"mikro-orm",
"mongo",
"mongodb",
"mysql",
"orm",
"postgresql",
"sqlite",
"sqlite3",
"ts",
"typescript",
"unit-of-work"
],
"homepage": "https://mikro-orm.io",
"bugs": {
"url": "https://github.com/mikro-orm/mikro-orm/issues"
},
"license": "MIT",
"author": "Martin Adámek",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/mikro-orm/mikro-orm.git"
},
"funding": "https://github.com/sponsors/b4nan",
"type": "module",
"exports": {
"./package.json": "./package.json",
"./es": "./es/index.js",
"./legacy": "./legacy/index.js"
},
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "yarn compile && yarn copy",
"clean": "yarn run -T rimraf ./dist",
"compile": "yarn run -T tsc -p tsconfig.build.json",
"copy": "node ../../scripts/copy.mjs"
},
"devDependencies": {
"@mikro-orm/core": "^7.0.2"
},
"peerDependencies": {
"@mikro-orm/core": "7.0.2",
"reflect-metadata": "^0.1.0 || ^0.2.0"
},
"peerDependenciesMeta": {
"reflect-metadata": {
"optional": true
}
},
"engines": {
"node": ">= 22.17.0"
}
}

75
node_modules/@mikro-orm/decorators/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import {
type Dictionary,
EntityManager,
type EntityMetadata,
EntityRepository,
type MaybePromise,
MetadataStorage,
MikroORM,
type ReferenceKind,
} from '@mikro-orm/core';
/**
* The type of context that the user intends to inject.
*/
export type ContextProvider<T> =
| MaybePromise<MikroORM>
| ((type: T) => MaybePromise<
| MikroORM
| EntityManager
| EntityRepository<any>
| {
getEntityManager(): EntityManager;
}
>);
/**
* Find `EntityManager` in provided context, or else in instance's `orm` or `em` properties.
*/
export declare function resolveContextProvider<T>(
caller: T & {
orm?: MaybePromise<MikroORM>;
em?: MaybePromise<EntityManager>;
},
provider?: ContextProvider<T>,
): Promise<EntityManager | undefined>;
/**
* Relation decorators allow using two signatures
* - using first parameter as options object
* - using all parameters
*
* This function validates those two ways are not mixed and returns the final options object.
* If the second way is used, we always consider the last parameter as options object.
* @internal
*/
export declare function processDecoratorParameters<T>(params: Dictionary): T;
/**
* Validate there is only one property decorator. This disallows using `@Property()` together with e.g. `@ManyToOne()`
* on the same property. One should use only `@ManyToOne()` in such case.
* We allow the existence of the property in metadata if the reference kind is the same, this should allow things like HMR to work.
*/
export declare function validateSingleDecorator(meta: EntityMetadata, propertyName: string, kind: ReferenceKind): void;
/**
* Prepares and returns a metadata context for an entity, ensuring default structure and validating proper usage of a single decorator.
* We need to use the `Object.hasOwn` here, since the metadata object respects inheritance, and the `properties` object might already
* exist for some base entity.
*/
export declare function prepareMetadataContext<T>(
context:
| ClassFieldDecoratorContext<T>
| ClassGetterDecoratorContext<T>
| ClassSetterDecoratorContext<T>
| ClassAccessorDecoratorContext<T>
| ClassMethodDecoratorContext<T>,
kind?: ReferenceKind,
): EntityMetadata<T>;
/**
* Uses some dark magic to get source path to caller where decorator is used.
* Analyzes stack trace of error created inside the function call.
*/
export declare function lookupPathFromDecorator(name: string, stack?: string[]): string;
/** Retrieves or creates the metadata object for a decorated entity class. */
export declare function getMetadataFromDecorator<T = any>(
target: T &
Dictionary & {
[MetadataStorage.PATH_SYMBOL]?: string;
},
): EntityMetadata<T>;

131
node_modules/@mikro-orm/decorators/utils.js generated vendored Normal file
View File

@@ -0,0 +1,131 @@
import { EntityManager, EntityRepository, MetadataError, MetadataStorage, MikroORM, Utils } from '@mikro-orm/core';
function getEntityManager(caller, context) {
if (context instanceof EntityManager) {
return context;
}
if (context instanceof EntityRepository) {
return context.getEntityManager();
}
if (context instanceof MikroORM) {
return context.em;
}
if (caller.em instanceof EntityManager) {
return caller.em;
}
if (caller.orm instanceof MikroORM) {
return caller.orm.em;
}
return undefined;
}
/**
* Find `EntityManager` in provided context, or else in instance's `orm` or `em` properties.
*/
export async function resolveContextProvider(caller, provider) {
const context = typeof provider === 'function' ? await provider(caller) : await provider;
return getEntityManager({ orm: await caller.orm, em: await caller.em }, context);
}
/**
* Relation decorators allow using two signatures
* - using first parameter as options object
* - using all parameters
*
* This function validates those two ways are not mixed and returns the final options object.
* If the second way is used, we always consider the last parameter as options object.
* @internal
*/
export function processDecoratorParameters(params) {
const keys = Object.keys(params);
const values = Object.values(params);
if (!Utils.isPlainObject(values[0])) {
const lastKey = keys[keys.length - 1];
const last = params[lastKey];
delete params[lastKey];
return { ...last, ...params };
}
// validate only first parameter is used if its an option object
const empty = v => v == null || (Utils.isPlainObject(v) && !Utils.hasObjectKeys(v));
if (values.slice(1).some(v => !empty(v))) {
throw new Error(
'Mixing first decorator parameter as options object with other parameters is forbidden. ' +
'If you want to use the options parameter at first position, provide all options inside it.',
);
}
return values[0];
}
/**
* Validate there is only one property decorator. This disallows using `@Property()` together with e.g. `@ManyToOne()`
* on the same property. One should use only `@ManyToOne()` in such case.
* We allow the existence of the property in metadata if the reference kind is the same, this should allow things like HMR to work.
*/
export function validateSingleDecorator(meta, propertyName, kind) {
if (meta.properties[propertyName] && meta.properties[propertyName].kind !== kind) {
throw MetadataError.multipleDecorators(meta.className, propertyName);
}
}
/**
* Prepares and returns a metadata context for an entity, ensuring default structure and validating proper usage of a single decorator.
* We need to use the `Object.hasOwn` here, since the metadata object respects inheritance, and the `properties` object might already
* exist for some base entity.
*/
export function prepareMetadataContext(context, kind) {
const meta = context.metadata;
if (!Object.hasOwn(meta, 'properties')) {
meta.properties = { ...meta.properties };
}
if (kind) {
validateSingleDecorator(meta, context.name, kind);
}
return meta;
}
/**
* Uses some dark magic to get source path to caller where decorator is used.
* Analyzes stack trace of error created inside the function call.
*/
export function lookupPathFromDecorator(name, stack) {
// use some dark magic to get source path to caller
stack = stack || new Error().stack.split('\n');
// In some situations (e.g. swc 1.3.4+), the presence of a source map can obscure the call to
// __decorate(), replacing it with the constructor name. To support these cases we look for
// Reflect.decorate() as well. Also when babel is used, we need to check
// the `_applyDecoratedDescriptor` method instead.
let line = stack.findIndex(line => /__decorate|Reflect\.decorate|_applyDecoratedDescriptor/.exec(line));
// bun does not have those lines at all, only the DecorateProperty/DecorateConstructor,
// but those are also present in node, so we need to check this only if they weren't found.
if (line === -1) {
// here we handle bun which stack is different from nodejs so we search for reflect-metadata
// Different bun versions might have different stack traces. The "last index" works for both 1.2.6 and 1.2.7.
const reflectLine = stack.findLastIndex(line =>
line.replace(/\\/g, '/').includes('node_modules/reflect-metadata/Reflect.js'),
);
if (reflectLine === -1 || reflectLine + 2 >= stack.length || !stack[reflectLine + 1].includes('bun:wrap')) {
return name;
}
line = reflectLine + 2;
}
if (stack[line].includes('Reflect.decorate')) {
line++;
}
// Skip decorator runtime helpers (tslib, @oxc-project/runtime, etc.)
while (
line < stack.length &&
/node_modules\/(tslib\/|@oxc-project\/runtime\/)/.test(stack[line].replace(/\\/g, '/'))
) {
line++;
}
try {
const re = /\(.+\)/i.exec(stack[line]) ? /\((.*):\d+:\d+\)/ : /at\s*(.*):\d+:\d+$/;
return stack[line].match(re)[1];
} catch {
return name;
}
}
/** Retrieves or creates the metadata object for a decorated entity class. */
export function getMetadataFromDecorator(target) {
if (!Object.hasOwn(target, MetadataStorage.PATH_SYMBOL)) {
Object.defineProperty(target, MetadataStorage.PATH_SYMBOL, {
value: lookupPathFromDecorator(target.name),
writable: true,
});
}
return MetadataStorage.getMetadata(target.name, target[MetadataStorage.PATH_SYMBOL]);
}