@mikro-orm/core 7.0.0-dev.63 → 7.0.0-dev.65

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.
Files changed (61) hide show
  1. package/MikroORM.js +1 -8
  2. package/entity/defineEntity.d.ts +2 -8
  3. package/enums.d.ts +2 -0
  4. package/index.d.ts +1 -2
  5. package/index.js +0 -1
  6. package/metadata/EntitySchema.d.ts +1 -9
  7. package/metadata/MetadataDiscovery.js +1 -4
  8. package/metadata/MetadataProvider.d.ts +2 -2
  9. package/metadata/MetadataProvider.js +15 -0
  10. package/metadata/index.d.ts +1 -1
  11. package/metadata/index.js +1 -1
  12. package/metadata/types.d.ts +480 -0
  13. package/metadata/types.js +1 -0
  14. package/package.json +2 -3
  15. package/typings.d.ts +2 -10
  16. package/utils/Configuration.d.ts +5 -11
  17. package/utils/Configuration.js +3 -5
  18. package/utils/ConfigurationLoader.d.ts +3 -30
  19. package/utils/ConfigurationLoader.js +25 -203
  20. package/utils/Utils.d.ts +0 -4
  21. package/utils/Utils.js +0 -8
  22. package/decorators/Check.d.ts +0 -3
  23. package/decorators/Check.js +0 -13
  24. package/decorators/CreateRequestContext.d.ts +0 -3
  25. package/decorators/CreateRequestContext.js +0 -32
  26. package/decorators/Embeddable.d.ts +0 -10
  27. package/decorators/Embeddable.js +0 -11
  28. package/decorators/Embedded.d.ts +0 -12
  29. package/decorators/Embedded.js +0 -18
  30. package/decorators/Entity.d.ts +0 -35
  31. package/decorators/Entity.js +0 -12
  32. package/decorators/Enum.d.ts +0 -9
  33. package/decorators/Enum.js +0 -16
  34. package/decorators/Filter.d.ts +0 -2
  35. package/decorators/Filter.js +0 -8
  36. package/decorators/Formula.d.ts +0 -4
  37. package/decorators/Formula.js +0 -15
  38. package/decorators/Indexed.d.ts +0 -19
  39. package/decorators/Indexed.js +0 -20
  40. package/decorators/ManyToMany.d.ts +0 -42
  41. package/decorators/ManyToMany.js +0 -14
  42. package/decorators/ManyToOne.d.ts +0 -34
  43. package/decorators/ManyToOne.js +0 -14
  44. package/decorators/OneToMany.d.ts +0 -28
  45. package/decorators/OneToMany.js +0 -17
  46. package/decorators/OneToOne.d.ts +0 -28
  47. package/decorators/OneToOne.js +0 -7
  48. package/decorators/PrimaryKey.d.ts +0 -8
  49. package/decorators/PrimaryKey.js +0 -20
  50. package/decorators/Property.d.ts +0 -294
  51. package/decorators/Property.js +0 -32
  52. package/decorators/Transactional.d.ts +0 -15
  53. package/decorators/Transactional.js +0 -31
  54. package/decorators/hooks.d.ts +0 -16
  55. package/decorators/hooks.js +0 -47
  56. package/decorators/index.d.ts +0 -17
  57. package/decorators/index.js +0 -17
  58. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  59. package/metadata/ReflectMetadataProvider.js +0 -44
  60. package/utils/resolveContextProvider.d.ts +0 -10
  61. package/utils/resolveContextProvider.js +0 -28
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
3
  "type": "module",
4
- "version": "7.0.0-dev.63",
4
+ "version": "7.0.0-dev.65",
5
5
  "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.",
6
6
  "exports": {
7
7
  "./package.json": "./package.json",
@@ -52,8 +52,7 @@
52
52
  "access": "public"
53
53
  },
54
54
  "dependencies": {
55
- "mikro-orm": "7.0.0-dev.63",
56
- "reflect-metadata": "0.2.2"
55
+ "mikro-orm": "7.0.0-dev.65"
57
56
  },
58
57
  "peerDependencies": {
59
58
  "dataloader": "2.2.3"
package/typings.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Transaction } from './connections/Connection.js';
2
- import { type Cascade, type DeferMode, type EventType, type LoadStrategy, type PopulatePath, type QueryOrderMap, ReferenceKind } from './enums.js';
2
+ import { type Cascade, type DeferMode, type EventType, type LoadStrategy, type PopulatePath, type QueryOrderMap, ReferenceKind, type EmbeddedPrefixMode } from './enums.js';
3
3
  import { type AssignOptions } from './entity/EntityAssigner.js';
4
4
  import { type EntityIdentifier } from './entity/EntityIdentifier.js';
5
5
  import { type EntityLoaderOptions } from './entity/EntityLoader.js';
@@ -7,7 +7,6 @@ import { type Collection } from './entity/Collection.js';
7
7
  import { type EntityFactory } from './entity/EntityFactory.js';
8
8
  import { type EntityRepository } from './entity/EntityRepository.js';
9
9
  import { Reference, type ScalarReference } from './entity/Reference.js';
10
- import type { MikroORM } from './MikroORM.js';
11
10
  import type { SerializationContext } from './serialization/SerializationContext.js';
12
11
  import type { SerializeOptions } from './serialization/EntitySerializer.js';
13
12
  import type { MetadataStorage } from './metadata/MetadataStorage.js';
@@ -17,7 +16,6 @@ import type { Platform } from './platforms/Platform.js';
17
16
  import type { Configuration } from './utils/Configuration.js';
18
17
  import type { RawQueryFragment } from './utils/RawQueryFragment.js';
19
18
  import type { EntityManager } from './EntityManager.js';
20
- import type { EmbeddedPrefixMode } from './decorators/Embedded.js';
21
19
  import type { EventSubscriber } from './events/EventSubscriber.js';
22
20
  import type { FilterOptions, FindOneOptions, FindOptions, LoadHint } from './drivers/IDatabaseDriver.js';
23
21
  export type Constructor<T = unknown> = new (...args: any[]) => T;
@@ -150,7 +148,6 @@ export type FilterValue<T> = OperatorMap<FilterItemValue<T>> | FilterItemValue<T
150
148
  export type FilterObject<T> = {
151
149
  -readonly [K in EntityKey<T>]?: ExpandQuery<ExpandProperty<T[K]>> | FilterValue<ExpandProperty<T[K]>> | null;
152
150
  };
153
- export type ExpandObject<T> = T extends object ? T extends Scalar ? never : FilterObject<T> : never;
154
151
  export type ExpandQuery<T> = T extends object ? T extends Scalar ? never : FilterQuery<T> : FilterValue<T>;
155
152
  export type EntityProps<T> = {
156
153
  -readonly [K in EntityKey<T>]?: T[K];
@@ -583,6 +580,7 @@ export interface GenerateOptions {
583
580
  bidirectionalRelations?: boolean;
584
581
  identifiedReferences?: boolean;
585
582
  entityDefinition?: 'decorators' | 'defineEntity' | 'entitySchema';
583
+ decorators?: 'es' | 'legacy';
586
584
  inferEntityType?: boolean;
587
585
  enumMode?: 'ts-enum' | 'union-type' | 'dictionary';
588
586
  esmImport?: boolean;
@@ -847,12 +845,6 @@ export interface Seeder<T extends Dictionary = Dictionary> {
847
845
  }
848
846
  export type ConnectionType = 'read' | 'write';
849
847
  export type MetadataProcessor = (metadata: EntityMetadata[], platform: Platform) => MaybePromise<void>;
850
- /**
851
- * The type of context that the user intends to inject.
852
- */
853
- export type ContextProvider<T> = MaybePromise<MikroORM> | ((type: T) => MaybePromise<MikroORM | EntityManager | EntityRepository<any> | {
854
- getEntityManager(): EntityManager;
855
- }>);
856
848
  export type MaybeReturnType<T> = T extends (...args: any[]) => infer R ? R : T;
857
849
  export interface EntitySchemaWithMeta<TName extends string = string, TTableName extends string = string, TEntity = any, TBase = never, TProperties extends Record<string, any> = Record<string, any>> extends EntitySchema<TEntity, TBase> {
858
850
  readonly name: TName;
@@ -9,15 +9,13 @@ import { type Logger, type LoggerNamespace, type LoggerOptions } from '../loggin
9
9
  import type { EntityManager } from '../EntityManager.js';
10
10
  import type { Platform } from '../platforms/Platform.js';
11
11
  import type { EntitySchema } from '../metadata/EntitySchema.js';
12
- import type { MetadataProvider } from '../metadata/MetadataProvider.js';
12
+ import { MetadataProvider } from '../metadata/MetadataProvider.js';
13
13
  import type { MetadataStorage } from '../metadata/MetadataStorage.js';
14
- import { ReflectMetadataProvider } from '../metadata/ReflectMetadataProvider.js';
15
- import type { EmbeddedPrefixMode } from '../decorators/Embedded.js';
16
14
  import type { EventSubscriber } from '../events/EventSubscriber.js';
17
15
  import type { AssignOptions } from '../entity/EntityAssigner.js';
18
16
  import type { EntityManagerType, IDatabaseDriver } from '../drivers/IDatabaseDriver.js';
19
17
  import { NotFoundError } from '../errors.js';
20
- import { DataloaderType, FlushMode, LoadStrategy, PopulateHint } from '../enums.js';
18
+ import { DataloaderType, FlushMode, LoadStrategy, PopulateHint, type EmbeddedPrefixMode } from '../enums.js';
21
19
  import { MemoryCacheAdapter } from '../cache/MemoryCacheAdapter.js';
22
20
  import { EntityComparator } from './EntityComparator.js';
23
21
  import type { Type } from '../types/Type.js';
@@ -31,13 +29,10 @@ declare const DEFAULTS: {
31
29
  readonly filters: {};
32
30
  readonly discovery: {
33
31
  readonly warnWhenNoEntities: true;
34
- readonly requireEntitiesArray: false;
35
32
  readonly checkDuplicateTableNames: true;
36
33
  readonly checkDuplicateFieldNames: true;
37
34
  readonly checkDuplicateEntities: true;
38
35
  readonly checkNonPersistentCompositeProps: true;
39
- readonly alwaysAnalyseProperties: true;
40
- readonly disableDynamicFileAccess: false;
41
36
  readonly inferDefaultValues: true;
42
37
  };
43
38
  readonly strict: false;
@@ -118,6 +113,7 @@ declare const DEFAULTS: {
118
113
  readonly identifiedReferences: true;
119
114
  readonly scalarPropertiesForRelations: "never";
120
115
  readonly entityDefinition: "defineEntity";
116
+ readonly decorators: "legacy";
121
117
  readonly enumMode: "dictionary";
122
118
  readonly fileName: (className: string) => string;
123
119
  readonly onlyPurePivotTables: false;
@@ -137,7 +133,7 @@ declare const DEFAULTS: {
137
133
  readonly expiration: 1000;
138
134
  readonly options: {};
139
135
  };
140
- readonly metadataProvider: typeof ReflectMetadataProvider;
136
+ readonly metadataProvider: typeof MetadataProvider;
141
137
  readonly highlighter: NullHighlighter;
142
138
  readonly seeder: {
143
139
  readonly path: "./seeders";
@@ -284,18 +280,16 @@ export interface PoolConfig {
284
280
  }
285
281
  export interface MetadataDiscoveryOptions {
286
282
  warnWhenNoEntities?: boolean;
287
- requireEntitiesArray?: boolean;
288
283
  checkDuplicateTableNames?: boolean;
289
284
  checkDuplicateFieldNames?: boolean;
290
285
  checkDuplicateEntities?: boolean;
291
286
  checkNonPersistentCompositeProps?: boolean;
292
- alwaysAnalyseProperties?: boolean;
293
- disableDynamicFileAccess?: boolean;
294
287
  inferDefaultValues?: boolean;
295
288
  getMappedType?: (type: string, platform: Platform) => Type<unknown> | undefined;
296
289
  onMetadata?: (meta: EntityMetadata, platform: Platform) => MaybePromise<void>;
297
290
  afterDiscovered?: (storage: MetadataStorage, platform: Platform) => MaybePromise<void>;
298
291
  tsConfigPath?: string;
292
+ /** @internal */
299
293
  skipSyncDiscovery?: boolean;
300
294
  }
301
295
  export interface Options<Driver extends IDatabaseDriver = IDatabaseDriver, EM extends EntityManager<Driver> & Driver[typeof EntityManagerType] = EntityManager<Driver> & Driver[typeof EntityManagerType], Entities extends (string | EntityClass<AnyEntity> | EntitySchema)[] = (string | EntityClass<AnyEntity> | EntitySchema)[]> extends ConnectionOptions {
@@ -5,7 +5,7 @@ import { NullHighlighter } from '../utils/NullHighlighter.js';
5
5
  import { DefaultLogger } from '../logging/DefaultLogger.js';
6
6
  import { colors } from '../logging/colors.js';
7
7
  import { Utils } from '../utils/Utils.js';
8
- import { ReflectMetadataProvider } from '../metadata/ReflectMetadataProvider.js';
8
+ import { MetadataProvider } from '../metadata/MetadataProvider.js';
9
9
  import { NotFoundError } from '../errors.js';
10
10
  import { RequestContext } from './RequestContext.js';
11
11
  import { DataloaderType, FlushMode, LoadStrategy, PopulateHint } from '../enums.js';
@@ -20,13 +20,10 @@ const DEFAULTS = {
20
20
  filters: {},
21
21
  discovery: {
22
22
  warnWhenNoEntities: true,
23
- requireEntitiesArray: false,
24
23
  checkDuplicateTableNames: true,
25
24
  checkDuplicateFieldNames: true,
26
25
  checkDuplicateEntities: true,
27
26
  checkNonPersistentCompositeProps: true,
28
- alwaysAnalyseProperties: true,
29
- disableDynamicFileAccess: false,
30
27
  inferDefaultValues: true,
31
28
  },
32
29
  strict: false,
@@ -108,6 +105,7 @@ const DEFAULTS = {
108
105
  identifiedReferences: true,
109
106
  scalarPropertiesForRelations: 'never',
110
107
  entityDefinition: 'defineEntity',
108
+ decorators: 'legacy',
111
109
  enumMode: 'dictionary',
112
110
  fileName: (className) => className,
113
111
  onlyPurePivotTables: false,
@@ -125,7 +123,7 @@ const DEFAULTS = {
125
123
  expiration: 1000, // 1s
126
124
  options: {},
127
125
  },
128
- metadataProvider: ReflectMetadataProvider,
126
+ metadataProvider: MetadataProvider,
129
127
  highlighter: new NullHighlighter(),
130
128
  seeder: {
131
129
  path: './seeders',
@@ -1,40 +1,13 @@
1
- import type { EntityManager } from '../EntityManager.js';
2
- import type { EntityManagerType, IDatabaseDriver } from '../drivers/IDatabaseDriver.js';
1
+ import type { IDatabaseDriver } from '../drivers/IDatabaseDriver.js';
3
2
  import type { Dictionary } from '../typings.js';
4
- import { Configuration, type Options } from './Configuration.js';
3
+ import { type Options } from './Configuration.js';
5
4
  /**
6
5
  * @internal
7
6
  */
8
7
  export declare class ConfigurationLoader {
9
- /**
10
- * Gets a named configuration
11
- *
12
- * @param contextName Load a config with the given `contextName` value. Used when config file exports array or factory function. Setting it to "default" matches also config objects without `contextName` set.
13
- * @param paths Array of possible paths for a configuration file. Files will be checked in order, and the first existing one will be used. Defaults to the output of {@link ConfigurationLoader.getConfigPaths}.
14
- * @param options Additional options to augment the final configuration with.
15
- */
16
- static getConfiguration<D extends IDatabaseDriver = IDatabaseDriver, EM extends D[typeof EntityManagerType] & EntityManager<D> = D[typeof EntityManagerType] & EntityManager<D>>(contextName?: string, paths?: string[], options?: Partial<Options>): Promise<Configuration<D, EM>>;
17
- static getConfigFile(paths: string[]): Promise<[string, unknown] | []>;
8
+ static loadEnvironmentVars<D extends IDatabaseDriver>(): Partial<Options<D>>;
18
9
  static getPackageConfig(basePath?: string): Dictionary;
19
- static getSettings(): Settings;
20
- static getConfigPaths(): string[];
21
- static isESM(): boolean;
22
- /**
23
- * Tries to register TS support in the following order: swc, tsx, jiti, tsimp
24
- * Use `MIKRO_ORM_CLI_TS_LOADER` env var to set the loader explicitly.
25
- * This method is used only in CLI context.
26
- */
27
- static registerTypeScriptSupport(configPath?: string, tsLoader?: 'swc' | 'tsx' | 'jiti' | 'tsimp' | 'auto'): Promise<boolean>;
28
- static loadEnvironmentVars<D extends IDatabaseDriver>(): Promise<Partial<Options<D>>>;
29
- static loadEnvironmentVarsSync<D extends IDatabaseDriver>(): Partial<Options<D>>;
30
10
  static getORMPackages(): Set<string>;
31
11
  static getORMPackageVersion(name: string): string | undefined;
32
12
  static checkPackageVersion(): string;
33
13
  }
34
- export interface Settings {
35
- verbose?: boolean;
36
- preferTs?: boolean;
37
- tsLoader?: 'swc' | 'tsx' | 'jiti' | 'tsimp' | 'auto';
38
- tsConfigPath?: string;
39
- configPaths?: string[];
40
- }
@@ -1,209 +1,11 @@
1
1
  import { realpathSync } from 'node:fs';
2
- import { colors } from '../logging/colors.js';
3
- import { Configuration } from './Configuration.js';
4
2
  import { Utils } from './Utils.js';
3
+ import { colors } from '../logging/colors.js';
5
4
  /**
6
5
  * @internal
7
6
  */
8
7
  export class ConfigurationLoader {
9
- /**
10
- * Gets a named configuration
11
- *
12
- * @param contextName Load a config with the given `contextName` value. Used when config file exports array or factory function. Setting it to "default" matches also config objects without `contextName` set.
13
- * @param paths Array of possible paths for a configuration file. Files will be checked in order, and the first existing one will be used. Defaults to the output of {@link ConfigurationLoader.getConfigPaths}.
14
- * @param options Additional options to augment the final configuration with.
15
- */
16
- static async getConfiguration(contextName = 'default', paths = ConfigurationLoader.getConfigPaths(), options = {}) {
17
- const env = await this.loadEnvironmentVars();
18
- const configFinder = (cfg) => {
19
- return typeof cfg === 'object' && cfg !== null && ('contextName' in cfg ? cfg.contextName === contextName : (contextName === 'default'));
20
- };
21
- const isValidConfigFactoryResult = (cfg) => {
22
- return typeof cfg === 'object' && cfg !== null && (!('contextName' in cfg) || cfg.contextName === contextName);
23
- };
24
- const result = await this.getConfigFile(paths);
25
- if (!result[0]) {
26
- if (Utils.hasObjectKeys(env)) {
27
- return new Configuration(Utils.mergeConfig({ contextName }, options, env));
28
- }
29
- throw new Error(`MikroORM config file not found in ['${paths.join(`', '`)}']`);
30
- }
31
- const path = result[0];
32
- let tmp = result[1];
33
- if (Array.isArray(tmp)) {
34
- const tmpFirstIndex = tmp.findIndex(configFinder);
35
- if (tmpFirstIndex === -1) {
36
- // Static config not found. Try factory functions
37
- let configCandidate;
38
- for (let i = 0, l = tmp.length; i < l; ++i) {
39
- const f = tmp[i];
40
- if (typeof f !== 'function') {
41
- continue;
42
- }
43
- configCandidate = await f(contextName);
44
- if (!isValidConfigFactoryResult(configCandidate)) {
45
- continue;
46
- }
47
- tmp = configCandidate;
48
- break;
49
- }
50
- if (Array.isArray(tmp)) {
51
- throw new Error(`MikroORM config '${contextName}' was not found within the config file '${path}'. Either add a config with this name to the array, or add a function that when given this name will return a configuration object without a name, or with name set to this name.`);
52
- }
53
- }
54
- else {
55
- const tmpLastIndex = tmp.findLastIndex(configFinder);
56
- if (tmpLastIndex !== tmpFirstIndex) {
57
- throw new Error(`MikroORM config '${contextName}' is not unique within the array exported by '${path}' (first occurrence index: ${tmpFirstIndex}; last occurrence index: ${tmpLastIndex})`);
58
- }
59
- tmp = tmp[tmpFirstIndex];
60
- }
61
- }
62
- else {
63
- if (tmp instanceof Function) {
64
- tmp = await tmp(contextName);
65
- if (!isValidConfigFactoryResult(tmp)) {
66
- throw new Error(`MikroORM config '${contextName}' was not what the function exported from '${path}' provided. Ensure it returns a config object with no name, or name matching the requested one.`);
67
- }
68
- }
69
- else {
70
- if (!configFinder(tmp)) {
71
- throw new Error(`MikroORM config '${contextName}' was not what the default export from '${path}' provided.`);
72
- }
73
- }
74
- }
75
- const esmConfigOptions = this.isESM() ? { entityGenerator: { esmImport: true } } : {};
76
- return new Configuration(Utils.mergeConfig({}, esmConfigOptions, tmp, options, env));
77
- }
78
- static async getConfigFile(paths) {
79
- for (let path of paths) {
80
- path = Utils.absolutePath(path);
81
- path = Utils.normalizePath(path);
82
- if (Utils.pathExists(path)) {
83
- const config = await Utils.dynamicImport(path);
84
- /* v8 ignore next */
85
- return [path, await (config.default ?? config)];
86
- }
87
- }
88
- return [];
89
- }
90
- static getPackageConfig(basePath = process.cwd()) {
91
- if (Utils.pathExists(`${basePath}/package.json`)) {
92
- /* v8 ignore next 5 */
93
- try {
94
- return Utils.readJSONSync(`${basePath}/package.json`);
95
- }
96
- catch {
97
- return {};
98
- }
99
- }
100
- const parentFolder = realpathSync(`${basePath}/..`);
101
- // we reached the root folder
102
- if (basePath === parentFolder) {
103
- return {};
104
- }
105
- return this.getPackageConfig(parentFolder);
106
- }
107
- static getSettings() {
108
- const config = ConfigurationLoader.getPackageConfig();
109
- const settings = { ...config['mikro-orm'] };
110
- const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
111
- settings.preferTs = process.env.MIKRO_ORM_CLI_PREFER_TS != null ? bool(process.env.MIKRO_ORM_CLI_PREFER_TS) : settings.preferTs;
112
- settings.tsLoader = process.env.MIKRO_ORM_CLI_TS_LOADER ?? settings.tsLoader;
113
- settings.tsConfigPath = process.env.MIKRO_ORM_CLI_TS_CONFIG_PATH ?? settings.tsConfigPath;
114
- settings.verbose = process.env.MIKRO_ORM_CLI_VERBOSE != null ? bool(process.env.MIKRO_ORM_CLI_VERBOSE) : settings.verbose;
115
- if (process.env.MIKRO_ORM_CLI_CONFIG?.endsWith('.ts')) {
116
- settings.preferTs = true;
117
- }
118
- return settings;
119
- }
120
- static getConfigPaths() {
121
- const settings = ConfigurationLoader.getSettings();
122
- const typeScriptSupport = settings.preferTs ?? Utils.detectTypeScriptSupport();
123
- const paths = [];
124
- if (process.env.MIKRO_ORM_CLI_CONFIG) {
125
- paths.push(process.env.MIKRO_ORM_CLI_CONFIG);
126
- }
127
- paths.push(...(settings.configPaths || []));
128
- if (typeScriptSupport) {
129
- paths.push('./src/mikro-orm.config.ts');
130
- paths.push('./mikro-orm.config.ts');
131
- }
132
- const distDir = Utils.pathExists(process.cwd() + '/dist');
133
- const buildDir = Utils.pathExists(process.cwd() + '/build');
134
- /* v8 ignore next */
135
- const path = distDir ? 'dist' : (buildDir ? 'build' : 'src');
136
- paths.push(`./${path}/mikro-orm.config.js`);
137
- paths.push('./mikro-orm.config.js');
138
- /* v8 ignore next */
139
- return Utils.unique(paths).filter(p => !p.match(/\.[mc]?ts$/) || typeScriptSupport);
140
- }
141
- static isESM() {
142
- const config = ConfigurationLoader.getPackageConfig();
143
- const type = config?.type ?? '';
144
- return type === 'module';
145
- }
146
- /**
147
- * Tries to register TS support in the following order: swc, tsx, jiti, tsimp
148
- * Use `MIKRO_ORM_CLI_TS_LOADER` env var to set the loader explicitly.
149
- * This method is used only in CLI context.
150
- */
151
- static async registerTypeScriptSupport(configPath = 'tsconfig.json', tsLoader) {
152
- /* v8 ignore next 3 */
153
- if (process.versions.bun) {
154
- return true;
155
- }
156
- process.env.SWC_NODE_PROJECT ??= configPath;
157
- process.env.TSIMP_PROJECT ??= configPath;
158
- process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS ??= '1';
159
- const isEsm = this.isESM();
160
- /* v8 ignore next */
161
- const importMethod = isEsm ? 'tryImport' : 'tryRequire';
162
- const explicitLoader = tsLoader ?? process.env.MIKRO_ORM_CLI_TS_LOADER ?? 'auto';
163
- const loaders = {
164
- swc: { esm: '@swc-node/register/esm-register', cjs: '@swc-node/register' },
165
- tsx: { esm: 'tsx/esm/api', cjs: 'tsx/cjs/api', cb: (tsx) => tsx.register({ tsconfig: configPath }) },
166
- jiti: { esm: 'jiti/register', cjs: 'jiti/register', cb: () => Utils.setDynamicImportProvider(id => import(id).then(mod => mod?.default ?? mod)) },
167
- tsimp: { esm: 'tsimp/import', cjs: 'tsimp/import' },
168
- };
169
- for (const loader of Utils.keys(loaders)) {
170
- if (explicitLoader !== 'auto' && loader !== explicitLoader) {
171
- continue;
172
- }
173
- const { esm, cjs, cb } = loaders[loader];
174
- /* v8 ignore next */
175
- const module = isEsm ? esm : cjs;
176
- const mod = await Utils[importMethod]({ module });
177
- if (mod) {
178
- cb?.(mod);
179
- process.env.MIKRO_ORM_CLI_TS_LOADER = loader;
180
- return true;
181
- }
182
- }
183
- // eslint-disable-next-line no-console
184
- console.warn('Neither `swc`, `tsx`, `jiti` nor `tsimp` found in the project dependencies, support for working with TypeScript files might not work. To use `swc`, you need to install both `@swc-node/register` and `@swc/core`.');
185
- return false;
186
- }
187
- static async loadEnvironmentVars() {
188
- const ret = this.loadEnvironmentVarsSync();
189
- // only to keep some sort of back compatibility with those using env vars only, to support `MIKRO_ORM_TYPE`
190
- const PLATFORMS = {
191
- mongo: { className: 'MongoDriver', module: '@mikro-orm/mongodb' },
192
- mysql: { className: 'MySqlDriver', module: '@mikro-orm/mysql' },
193
- mssql: { className: 'MsSqlDriver', module: '@mikro-orm/mssql' },
194
- mariadb: { className: 'MariaDbDriver', module: '@mikro-orm/mariadb' },
195
- postgresql: { className: 'PostgreSqlDriver', module: '@mikro-orm/postgresql' },
196
- sqlite: { className: 'SqliteDriver', module: '@mikro-orm/sqlite' },
197
- libsql: { className: 'LibSqlDriver', module: '@mikro-orm/libsql' },
198
- };
199
- if (process.env.MIKRO_ORM_TYPE) {
200
- const val = process.env.MIKRO_ORM_TYPE;
201
- const driver = await import(PLATFORMS[val].module);
202
- ret.driver = driver[PLATFORMS[val].className];
203
- }
204
- return ret;
205
- }
206
- static loadEnvironmentVarsSync() {
8
+ static loadEnvironmentVars() {
207
9
  const ret = {};
208
10
  const array = (v) => v.split(',').map(vv => vv.trim());
209
11
  const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
@@ -245,9 +47,12 @@ export class ConfigurationLoader {
245
47
  read(ret, 'MIKRO_ORM_COLORS', 'colors', bool);
246
48
  ret.discovery = {};
247
49
  read(ret.discovery, 'MIKRO_ORM_DISCOVERY_WARN_WHEN_NO_ENTITIES', 'warnWhenNoEntities', bool);
248
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_REQUIRE_ENTITIES_ARRAY', 'requireEntitiesArray', bool);
249
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_ALWAYS_ANALYSE_PROPERTIES', 'alwaysAnalyseProperties', bool);
250
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_DISABLE_DYNAMIC_FILE_ACCESS', 'disableDynamicFileAccess', bool);
50
+ read(ret.discovery, 'MIKRO_ORM_DISCOVERY_CHECK_DUPLICATE_TABLE_NAMES', 'checkDuplicateTableNames', bool);
51
+ read(ret.discovery, 'MIKRO_ORM_DISCOVERY_CHECK_DUPLICATE_FIELD_NAMES', 'checkDuplicateFieldNames', bool);
52
+ read(ret.discovery, 'MIKRO_ORM_DISCOVERY_CHECK_DUPLICATE_ENTITIES', 'checkDuplicateEntities', bool);
53
+ read(ret.discovery, 'MIKRO_ORM_DISCOVERY_CHECK_NON_PERSISTENT_COMPOSITE_PROPS', 'checkNonPersistentCompositeProps', bool);
54
+ read(ret.discovery, 'MIKRO_ORM_DISCOVERY_INFER_DEFAULT_VALUES', 'inferDefaultValues', bool);
55
+ read(ret.discovery, 'MIKRO_ORM_DISCOVERY_TS_CONFIG_PATH', 'tsConfigPath');
251
56
  cleanup(ret, 'discovery');
252
57
  ret.migrations = {};
253
58
  read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_TABLE_NAME', 'tableName');
@@ -277,6 +82,23 @@ export class ConfigurationLoader {
277
82
  cleanup(ret, 'seeder');
278
83
  return ret;
279
84
  }
85
+ static getPackageConfig(basePath = process.cwd()) {
86
+ if (Utils.pathExists(`${basePath}/package.json`)) {
87
+ /* v8 ignore next 5 */
88
+ try {
89
+ return Utils.readJSONSync(`${basePath}/package.json`);
90
+ }
91
+ catch {
92
+ return {};
93
+ }
94
+ }
95
+ const parentFolder = realpathSync(`${basePath}/..`);
96
+ // we reached the root folder
97
+ if (basePath === parentFolder) {
98
+ return {};
99
+ }
100
+ return this.getPackageConfig(parentFolder);
101
+ }
280
102
  static getORMPackages() {
281
103
  const pkg = this.getPackageConfig();
282
104
  return new Set([
package/utils/Utils.d.ts CHANGED
@@ -227,10 +227,6 @@ export declare class Utils {
227
227
  static getORMVersion(): string;
228
228
  static createFunction(context: Map<string, any>, code: string): any;
229
229
  static callCompiledFunction<T extends unknown[], R>(fn: (...args: T) => R, ...args: T): R;
230
- /**
231
- * @see https://github.com/mikro-orm/mikro-orm/issues/840
232
- */
233
- static propertyDecoratorReturnValue(): any;
234
230
  static unwrapProperty<T>(entity: T, meta: EntityMetadata<T>, prop: EntityProperty<T>, payload?: boolean): [unknown, number[]][];
235
231
  static setPayloadProperty<T>(entity: EntityDictionary<T>, meta: EntityMetadata<T>, prop: EntityProperty<T>, value: unknown, idx: number[]): void;
236
232
  static tryRequire<T extends Dictionary = any>({ module, from, allowError, warning }: {
package/utils/Utils.js CHANGED
@@ -975,14 +975,6 @@ export class Utils {
975
975
  throw e;
976
976
  }
977
977
  }
978
- /**
979
- * @see https://github.com/mikro-orm/mikro-orm/issues/840
980
- */
981
- static propertyDecoratorReturnValue() {
982
- if (process.env.BABEL_DECORATORS_COMPAT) {
983
- return {};
984
- }
985
- }
986
978
  static unwrapProperty(entity, meta, prop, payload = false) {
987
979
  let p = prop;
988
980
  const path = [];
@@ -1,3 +0,0 @@
1
- import type { CheckConstraint, EntityClass } from '../typings.js';
2
- export declare function Check<T>(options: CheckOptions<T>): (target: T, propertyName?: T extends EntityClass<unknown> ? undefined : keyof T) => any;
3
- export type CheckOptions<T = any> = CheckConstraint<T>;
@@ -1,13 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { Utils } from '../utils/Utils.js';
3
- export function Check(options) {
4
- return function (target, propertyName) {
5
- const meta = MetadataStorage.getMetadataFromDecorator((propertyName ? target.constructor : target));
6
- options.property ??= propertyName;
7
- meta.checks.push(options);
8
- if (!propertyName) {
9
- return target;
10
- }
11
- return Utils.propertyDecoratorReturnValue();
12
- };
13
- }
@@ -1,3 +0,0 @@
1
- import type { ContextProvider } from '../typings.js';
2
- export declare function CreateRequestContext<T extends object>(context?: ContextProvider<T>, respectExistingContext?: boolean): MethodDecorator;
3
- export declare function EnsureRequestContext<T extends object>(context?: ContextProvider<T>): MethodDecorator;
@@ -1,32 +0,0 @@
1
- import { RequestContext } from '../utils/RequestContext.js';
2
- import { resolveContextProvider } from '../utils/resolveContextProvider.js';
3
- import { TransactionContext } from '../utils/TransactionContext.js';
4
- export function CreateRequestContext(context, respectExistingContext = false) {
5
- return function (target, propertyKey, descriptor) {
6
- const originalMethod = descriptor.value;
7
- const name = respectExistingContext ? 'EnsureRequestContext' : 'CreateRequestContext';
8
- if (originalMethod.constructor.name !== 'AsyncFunction') {
9
- throw new Error(`@${name}() should be use with async functions`);
10
- }
11
- descriptor.value = async function (...args) {
12
- const em = await resolveContextProvider(this, context);
13
- if (!em) {
14
- 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.`);
15
- }
16
- // reuse existing context if available for given respect `contextName`
17
- if (respectExistingContext && RequestContext.getEntityManager(em.name)) {
18
- return originalMethod.apply(this, args);
19
- }
20
- // Otherwise, the outer tx context would be preferred.
21
- const txContext = TransactionContext.currentTransactionContext();
22
- const provider = txContext ? TransactionContext : RequestContext;
23
- return txContext
24
- ? provider.create(em.fork({ useContext: true }), () => originalMethod.apply(this, args))
25
- : provider.create(em, () => originalMethod.apply(this, args));
26
- };
27
- return descriptor;
28
- };
29
- }
30
- export function EnsureRequestContext(context) {
31
- return CreateRequestContext(context, true);
32
- }
@@ -1,10 +0,0 @@
1
- import type { AnyString, Dictionary, EntityClass } from '../typings.js';
2
- export declare function Embeddable<T>(options?: EmbeddableOptions<T>): (target: T) => T;
3
- export interface EmbeddableOptions<T> {
4
- /** Specify constructor parameters to be used in `em.create` or when `forceConstructor` is enabled. Those should be names of declared entity properties in the same order as your constructor uses them. The ORM tries to infer those automatically, use this option in case the inference fails. */
5
- constructorParams?: (T extends EntityClass<infer P> ? keyof P : string)[];
6
- discriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString;
7
- discriminatorMap?: Dictionary<string>;
8
- discriminatorValue?: number | string;
9
- abstract?: boolean;
10
- }
@@ -1,11 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- export function Embeddable(options = {}) {
3
- return function (target) {
4
- const meta = MetadataStorage.getMetadataFromDecorator(target);
5
- meta.class = target;
6
- meta.name = meta.class.name;
7
- meta.embeddable = true;
8
- Object.assign(meta, options);
9
- return target;
10
- };
11
- }
@@ -1,12 +0,0 @@
1
- import type { AnyEntity, EntityName } from '../typings.js';
2
- import type { PropertyOptions } from './Property.js';
3
- export declare function Embedded<Owner extends object, Target>(type?: EmbeddedOptions<Owner, Target> | (() => EntityName<Target> | EntityName<Target>[]), options?: EmbeddedOptions<Owner, Target>): (target: AnyEntity, propertyName: string) => any;
4
- /** With `absolute` the prefix is set at the root of the entity (regardless of the nesting level) */
5
- export type EmbeddedPrefixMode = 'absolute' | 'relative';
6
- export interface EmbeddedOptions<Owner, Target> extends PropertyOptions<Owner> {
7
- entity?: string | (() => EntityName<Target> | EntityName<Target>[]);
8
- prefix?: string | boolean;
9
- prefixMode?: EmbeddedPrefixMode;
10
- object?: boolean;
11
- array?: boolean;
12
- }
@@ -1,18 +0,0 @@
1
- import { MetadataValidator } from '../metadata/MetadataValidator.js';
2
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
3
- import { Utils } from '../utils/Utils.js';
4
- import { ReferenceKind } from '../enums.js';
5
- export function Embedded(type = {}, options = {}) {
6
- return function (target, propertyName) {
7
- const meta = MetadataStorage.getMetadataFromDecorator(target.constructor);
8
- MetadataValidator.validateSingleDecorator(meta, propertyName, ReferenceKind.EMBEDDED);
9
- options = type instanceof Function ? { entity: type, ...options } : { ...type, ...options };
10
- Utils.defaultValue(options, 'prefix', true);
11
- meta.properties[propertyName] = {
12
- name: propertyName,
13
- kind: ReferenceKind.EMBEDDED,
14
- ...options,
15
- };
16
- return Utils.propertyDecoratorReturnValue();
17
- };
18
- }