@mikro-orm/reflection 7.0.0-dev.33 → 7.0.0-dev.331

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,14 +2,14 @@
2
2
  <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>
3
3
  </h1>
4
4
 
5
- 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 and SQLite (including libSQL) databases.
5
+ 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.
6
6
 
7
7
  > Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).
8
8
 
9
- [![NPM version](https://img.shields.io/npm/v/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
10
- [![NPM dev version](https://img.shields.io/npm/v/@mikro-orm/core/next.svg)](https://www.npmjs.com/package/@mikro-orm/core)
9
+ [![NPM version](https://img.shields.io/npm/v/@mikro-orm/core.svg)](https://npmx.dev/package/@mikro-orm/core)
10
+ [![NPM dev version](https://img.shields.io/npm/v/@mikro-orm/core/next.svg)](https://npmx.dev/package/@mikro-orm/core)
11
11
  [![Chat on discord](https://img.shields.io/discord/1214904142443839538?label=discord&color=blue)](https://discord.gg/w8bjxFHS7X)
12
- [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://www.npmjs.com/package/@mikro-orm/core)
12
+ [![Downloads](https://img.shields.io/npm/dm/@mikro-orm/core.svg)](https://npmx.dev/package/@mikro-orm/core)
13
13
  [![Coverage Status](https://img.shields.io/coveralls/mikro-orm/mikro-orm.svg)](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
14
14
  [![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)
15
15
 
@@ -181,6 +181,7 @@ yarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
181
181
  yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
182
182
  yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
183
183
  yarn add @mikro-orm/core @mikro-orm/mssql # for mssql
184
+ yarn add @mikro-orm/core @mikro-orm/oracledb # for oracle
184
185
  yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
185
186
  yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
186
187
  ```
@@ -381,6 +382,8 @@ See also the list of contributors who [participated](https://github.com/mikro-or
381
382
 
382
383
  Please ⭐️ this repository if this project helped you!
383
384
 
385
+ > If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
386
+
384
387
  ## 📝 License
385
388
 
386
389
  Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
@@ -3,8 +3,9 @@ import { type EntityMetadata, MetadataProvider } from '@mikro-orm/core';
3
3
  export declare class TsMorphMetadataProvider extends MetadataProvider {
4
4
  private project;
5
5
  private sources;
6
+ static useCache(): boolean;
6
7
  useCache(): boolean;
7
- loadEntityMetadata(meta: EntityMetadata, name: string): void;
8
+ loadEntityMetadata(meta: EntityMetadata): void;
8
9
  getExistingSourceFile(path: string, ext?: string, validate?: boolean): SourceFile;
9
10
  protected initProperties(meta: EntityMetadata): void;
10
11
  private extractType;
@@ -12,7 +13,10 @@ export declare class TsMorphMetadataProvider extends MetadataProvider {
12
13
  private initPropertyType;
13
14
  private readTypeFromSource;
14
15
  private getSourceFile;
16
+ private stripRelativePath;
15
17
  private processWrapper;
16
18
  private initProject;
17
19
  private initSourceFiles;
20
+ saveToCache(meta: EntityMetadata): void;
21
+ getCacheKey(meta: Pick<EntityMetadata, 'className' | 'path'>): string;
18
22
  }
@@ -1,12 +1,17 @@
1
- import { ModuleKind, Project } from 'ts-morph';
2
- import { ConfigurationLoader, MetadataError, MetadataProvider, MetadataStorage, ReferenceKind, Utils, } from '@mikro-orm/core';
1
+ import { extname } from 'node:path';
2
+ import { ComputedPropertyName, ModuleKind, NoSubstitutionTemplateLiteral, Project, StringLiteral, } from 'ts-morph';
3
+ import { EntitySchema, MetadataError, MetadataProvider, MetadataStorage, RawQueryFragment, ReferenceKind, Type, Utils, } from '@mikro-orm/core';
4
+ import { fs } from '@mikro-orm/core/fs-utils';
3
5
  export class TsMorphMetadataProvider extends MetadataProvider {
4
6
  project;
5
7
  sources;
8
+ static useCache() {
9
+ return true;
10
+ }
6
11
  useCache() {
7
- return this.config.get('metadataCache').enabled ?? true;
12
+ return this.config.get('metadataCache').enabled ?? TsMorphMetadataProvider.useCache();
8
13
  }
9
- loadEntityMetadata(meta, name) {
14
+ loadEntityMetadata(meta) {
10
15
  if (!meta.path) {
11
16
  return;
12
17
  }
@@ -16,35 +21,34 @@ export class TsMorphMetadataProvider extends MetadataProvider {
16
21
  if (!ext) {
17
22
  return this.getExistingSourceFile(path, '.d.ts', false) || this.getExistingSourceFile(path, '.ts');
18
23
  }
19
- const tsPath = path.match(/.*\/[^/]+$/)[0].replace(/\.js$/, ext);
24
+ const tsPath = /.*\/[^/]+$/.exec(path)[0].replace(/\.js$/, ext);
20
25
  return this.getSourceFile(tsPath, validate);
21
26
  }
22
27
  initProperties(meta) {
28
+ meta.path = fs.normalizePath(meta.path);
23
29
  // load types and column names
24
30
  for (const prop of Object.values(meta.properties)) {
25
- const type = this.extractType(prop);
26
- if (!type || this.config.get('discovery').alwaysAnalyseProperties) {
27
- this.initPropertyType(meta, prop);
28
- }
29
- prop.type = type || prop.type;
31
+ const { type, target } = this.extractType(meta, prop);
32
+ this.initPropertyType(meta, prop);
33
+ prop.type = type ?? prop.type;
34
+ prop.target = target;
30
35
  }
31
36
  }
32
- extractType(prop) {
33
- if (Utils.isString(prop.entity)) {
34
- return prop.entity;
37
+ extractType(meta, prop) {
38
+ /* v8 ignore next */
39
+ if (typeof prop.entity === 'string') {
40
+ throw new Error(`Relation target needs to be an entity class or EntitySchema instance, '${prop.entity}' given instead for ${meta.className}.${prop.name}.`);
35
41
  }
36
- if (prop.entity) {
37
- return Utils.className(prop.entity());
42
+ if (!prop.entity) {
43
+ return { type: prop.type };
38
44
  }
39
- return prop.type;
45
+ const tmp = prop.entity();
46
+ const target = tmp instanceof EntitySchema ? tmp.meta.class : tmp;
47
+ return { type: Utils.className(target), target };
40
48
  }
41
49
  cleanUpTypeTags(type) {
42
50
  const genericTags = [/Opt<(.*?)>/, /Hidden<(.*?)>/, /RequiredNullable<(.*?)>/];
43
- const intersectionTags = [
44
- 'Opt.Brand',
45
- 'Hidden.Brand',
46
- 'RequiredNullable.Brand',
47
- ];
51
+ const intersectionTags = ['Opt.Brand', 'Hidden.Brand', 'RequiredNullable.Brand'];
48
52
  for (const tag of genericTags) {
49
53
  type = type.replace(tag, '$1');
50
54
  }
@@ -67,19 +71,34 @@ export class TsMorphMetadataProvider extends MetadataProvider {
67
71
  this.processWrapper(prop, 'ScalarReference');
68
72
  this.processWrapper(prop, 'Collection');
69
73
  prop.runtimeType ??= prop.type;
70
- if (prop.type.replace(/import\(.*\)\./g, '').match(/^(Dictionary|Record)<.*>$/)) {
74
+ if (/^(Dictionary|Record)<.*>$/.exec(prop.type.replace(/import\(.*\)\./g, ''))) {
71
75
  prop.type = 'json';
72
76
  }
73
77
  }
74
78
  readTypeFromSource(meta, prop) {
75
79
  const source = this.getExistingSourceFile(meta.path);
76
80
  const cls = source.getClass(meta.className);
77
- /* v8 ignore next 3 */
81
+ /* v8 ignore next */
78
82
  if (!cls) {
79
83
  throw new MetadataError(`Source class for entity ${meta.className} not found. Verify you have 'compilerOptions.declaration' enabled in your 'tsconfig.json'. If you are using webpack, see https://bit.ly/35pPDNn`);
80
84
  }
81
85
  const properties = cls.getInstanceProperties();
82
- const property = properties.find(v => v.getName() === prop.name);
86
+ const property = properties.find(v => {
87
+ if (v.getName() === prop.name) {
88
+ return true;
89
+ }
90
+ const nameNode = v.getNameNode();
91
+ if (nameNode instanceof StringLiteral && nameNode.getLiteralText() === prop.name) {
92
+ return true;
93
+ }
94
+ if (nameNode instanceof ComputedPropertyName) {
95
+ const expr = nameNode.getExpression();
96
+ if (expr instanceof NoSubstitutionTemplateLiteral && expr.getLiteralText() === prop.name) {
97
+ return true;
98
+ }
99
+ }
100
+ return false;
101
+ });
83
102
  if (!property) {
84
103
  return { type: prop.type, optional: prop.nullable };
85
104
  }
@@ -90,9 +109,12 @@ export class TsMorphMetadataProvider extends MetadataProvider {
90
109
  }
91
110
  if (tsType.isArray()) {
92
111
  prop.array = true;
93
- /* v8 ignore next 3 */
112
+ /* v8 ignore next */
94
113
  if (tsType.getArrayElementType().isEnum()) {
95
- prop.items = tsType.getArrayElementType().getUnionTypes().map(t => t.getLiteralValueOrThrow());
114
+ prop.items = tsType
115
+ .getArrayElementType()
116
+ .getUnionTypes()
117
+ .map(t => t.getLiteralValueOrThrow());
96
118
  }
97
119
  }
98
120
  if (prop.array && prop.enum) {
@@ -102,7 +124,7 @@ export class TsMorphMetadataProvider extends MetadataProvider {
102
124
  const union = type.split(' | ');
103
125
  const optional = property.hasQuestionToken?.() || union.includes('null') || union.includes('undefined') || tsType.isNullable();
104
126
  type = union.filter(t => !['null', 'undefined'].includes(t)).join(' | ');
105
- prop.array ??= type.endsWith('[]') || !!type.match(/Array<(.*)>/);
127
+ prop.array ??= type.endsWith('[]') || !!/Array<(.*)>/.exec(type);
106
128
  type = type
107
129
  .replace(/Array<(.*)>/, '$1') // unwrap array
108
130
  .replace(/\[]$/, '') // remove array suffix
@@ -120,27 +142,29 @@ export class TsMorphMetadataProvider extends MetadataProvider {
120
142
  const baseDir = this.config.get('baseDir');
121
143
  const outDir = this.project.getCompilerOptions().outDir;
122
144
  let path = tsPath;
145
+ /* v8 ignore next */
123
146
  if (outDir != null) {
124
- const outDirRelative = Utils.relativePath(outDir, baseDir);
147
+ const outDirRelative = fs.relativePath(outDir, baseDir);
125
148
  path = path.replace(new RegExp(`^${outDirRelative}`), '');
126
149
  }
127
- path = Utils.stripRelativePath(path);
150
+ path = this.stripRelativePath(path);
128
151
  const source = this.sources.find(s => s.getFilePath().endsWith(path));
129
152
  if (!source && validate) {
130
- throw new MetadataError(`Source file '${tsPath}' not found. Check your 'entitiesTs' option and verify you have 'compilerOptions.declaration' enabled in your 'tsconfig.json'. If you are using webpack, see https://bit.ly/35pPDNn`);
153
+ throw new MetadataError(`Source file '${fs.relativePath(tsPath, baseDir)}' not found. Check your 'entitiesTs' option and verify you have 'compilerOptions.declaration' enabled in your 'tsconfig.json'. If you are using webpack, see https://bit.ly/35pPDNn`);
131
154
  }
132
155
  return source;
133
156
  }
157
+ stripRelativePath(str) {
158
+ return str.replace(/^(?:\.\.\/|\.\/)+/, '/');
159
+ }
134
160
  processWrapper(prop, wrapper) {
135
161
  // type can be sometimes in form of:
136
162
  // `'({ object?: Entity | undefined; } & import("...").Reference<Entity>)'`
137
163
  // `{ object?: import("...").Entity | undefined; } & import("...").Reference<Entity>`
138
164
  // `{ node?: ({ id?: number | undefined; } & import("...").Reference<import("...").Entity>) | undefined; } & import("...").Reference<Entity>`
139
165
  // the regexp is looking for the `wrapper`, possible prefixed with `.` or wrapped in parens.
140
- const type = prop.type
141
- .replace(/import\(.*\)\./g, '')
142
- .replace(/\{ .* } & ([\w &]+)/g, '$1');
143
- const m = type.match(new RegExp(`(?:^|[.( ])${wrapper}<(\\w+),?.*>(?:$|[) ])`));
166
+ const type = prop.type.replace(/import\(.*\)\./g, '').replace(/\{ .* } & ([\w &]+)/g, '$1');
167
+ const m = new RegExp(`(?:^|[.( ])${wrapper}<(\\w+),?.*>(?:$|[) ])`).exec(type);
144
168
  if (!m) {
145
169
  return;
146
170
  }
@@ -150,16 +174,15 @@ export class TsMorphMetadataProvider extends MetadataProvider {
150
174
  }
151
175
  }
152
176
  initProject() {
153
- const settings = ConfigurationLoader.getSettings();
154
177
  /* v8 ignore next */
155
- const tsConfigFilePath = this.config.get('discovery').tsConfigPath ?? settings.tsConfigPath ?? './tsconfig.json';
178
+ const tsConfigFilePath = this.config.get('discovery').tsConfigPath ?? './tsconfig.json';
156
179
  try {
157
180
  this.project = new Project({
158
- tsConfigFilePath: Utils.normalizePath(process.cwd(), tsConfigFilePath),
181
+ tsConfigFilePath: fs.normalizePath(process.cwd(), tsConfigFilePath),
159
182
  skipAddingFilesFromTsConfig: true,
160
183
  compilerOptions: {
161
184
  strictNullChecks: true,
162
- module: ModuleKind.Node16,
185
+ module: ModuleKind.Node20,
163
186
  },
164
187
  });
165
188
  }
@@ -168,29 +191,65 @@ export class TsMorphMetadataProvider extends MetadataProvider {
168
191
  this.project = new Project({
169
192
  compilerOptions: {
170
193
  strictNullChecks: true,
171
- module: ModuleKind.Node16,
194
+ module: ModuleKind.Node20,
172
195
  },
173
196
  });
174
197
  }
175
198
  }
176
199
  initSourceFiles() {
177
- if (!this.project) {
178
- this.initProject();
179
- }
200
+ this.initProject();
180
201
  this.sources = [];
181
202
  // All entity files are first required during the discovery, before we reach here, so it is safe to get the parts from the global
182
203
  // metadata storage. We know the path thanks to the decorators being executed. In case we are running the TS code, the extension
183
204
  // will be already `.ts`, so no change is needed. `.js` files will get renamed to `.d.ts` files as they will be used as a source for
184
205
  // the ts-morph reflection.
185
206
  for (const meta of Utils.values(MetadataStorage.getMetadata())) {
186
- /* v8 ignore next 3 */
187
- const path = meta.path.match(/\.[jt]s$/)
188
- ? meta.path.replace(/\.js$/, '.d.ts')
189
- : `${meta.path}.d.ts`; // when entities are bundled, their paths are just their names
207
+ const metaPath = fs.normalizePath(meta.path);
208
+ /* v8 ignore next */
209
+ const path = /\.[jt]s$/.exec(metaPath) ? metaPath.replace(/\.js$/, '.d.ts') : `${metaPath}.d.ts`; // when entities are bundled, their paths are just their names
190
210
  const sourceFile = this.project.addSourceFileAtPathIfExists(path);
191
211
  if (sourceFile) {
192
212
  this.sources.push(sourceFile);
193
213
  }
194
214
  }
195
215
  }
216
+ saveToCache(meta) {
217
+ if (!this.useCache()) {
218
+ return;
219
+ }
220
+ Reflect.deleteProperty(meta, 'root'); // to allow caching (as root can contain cycles)
221
+ const copy = Utils.copy(meta, false);
222
+ for (const prop of copy.props) {
223
+ if (Type.isMappedType(prop.type)) {
224
+ Reflect.deleteProperty(prop, 'type');
225
+ Reflect.deleteProperty(prop, 'customType');
226
+ }
227
+ if (prop.default) {
228
+ const raw = RawQueryFragment.getKnownFragment(prop.default);
229
+ if (raw) {
230
+ prop.defaultRaw ??= this.config.getPlatform().formatQuery(raw.sql, raw.params);
231
+ Reflect.deleteProperty(prop, 'default');
232
+ }
233
+ }
234
+ Reflect.deleteProperty(prop, 'targetMeta');
235
+ }
236
+ [
237
+ 'prototype',
238
+ 'props',
239
+ 'referencingProperties',
240
+ 'propertyOrder',
241
+ 'relations',
242
+ 'concurrencyCheckKeys',
243
+ 'checks',
244
+ ].forEach(key => delete copy[key]);
245
+ // base entity without properties might not have path, but nothing to cache there
246
+ if (meta.path) {
247
+ meta.path = fs.relativePath(meta.path, this.config.get('baseDir'));
248
+ this.config.getMetadataCacheAdapter().set(this.getCacheKey(meta), copy, meta.path);
249
+ }
250
+ }
251
+ getCacheKey(meta) {
252
+ /* v8 ignore next */
253
+ return meta.className + (meta.path ? extname(meta.path) : '');
254
+ }
196
255
  }
package/package.json CHANGED
@@ -1,62 +1,61 @@
1
1
  {
2
2
  "name": "@mikro-orm/reflection",
3
- "type": "module",
4
- "version": "7.0.0-dev.33",
3
+ "version": "7.0.0-dev.331",
5
4
  "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
- "exports": {
7
- "./package.json": "./package.json",
8
- ".": "./index.js"
9
- },
10
- "repository": {
11
- "type": "git",
12
- "url": "git+ssh://git@github.com/mikro-orm/mikro-orm.git"
13
- },
14
5
  "keywords": [
15
- "orm",
6
+ "data-mapper",
7
+ "ddd",
8
+ "entity",
9
+ "identity-map",
10
+ "javascript",
11
+ "js",
12
+ "mariadb",
13
+ "mikro-orm",
16
14
  "mongo",
17
15
  "mongodb",
18
16
  "mysql",
19
- "mariadb",
17
+ "orm",
20
18
  "postgresql",
21
19
  "sqlite",
22
20
  "sqlite3",
23
21
  "ts",
24
22
  "typescript",
25
- "js",
26
- "javascript",
27
- "entity",
28
- "ddd",
29
- "mikro-orm",
30
- "unit-of-work",
31
- "data-mapper",
32
- "identity-map"
23
+ "unit-of-work"
33
24
  ],
34
- "author": "Martin Adámek",
35
- "license": "MIT",
25
+ "homepage": "https://mikro-orm.io",
36
26
  "bugs": {
37
27
  "url": "https://github.com/mikro-orm/mikro-orm/issues"
38
28
  },
39
- "homepage": "https://mikro-orm.io",
40
- "engines": {
41
- "node": ">= 22.11.0"
29
+ "license": "MIT",
30
+ "author": "Martin Adámek",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+ssh://git@github.com/mikro-orm/mikro-orm.git"
34
+ },
35
+ "type": "module",
36
+ "exports": {
37
+ "./package.json": "./package.json",
38
+ ".": "./index.js"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
42
  },
43
43
  "scripts": {
44
- "build": "yarn clean && yarn compile && yarn copy",
44
+ "build": "yarn compile && yarn copy",
45
45
  "clean": "yarn run -T rimraf ./dist",
46
46
  "compile": "yarn run -T tsc -p tsconfig.build.json",
47
47
  "copy": "node ../../scripts/copy.mjs"
48
48
  },
49
- "publishConfig": {
50
- "access": "public"
51
- },
52
49
  "dependencies": {
53
- "tinyglobby": "0.2.13",
54
- "ts-morph": "27.0.0"
50
+ "ts-morph": "27.0.2"
55
51
  },
56
52
  "devDependencies": {
57
- "@mikro-orm/core": "^6.5.7"
53
+ "@mikro-orm/core": "^6.6.9"
58
54
  },
59
55
  "peerDependencies": {
60
- "@mikro-orm/core": "7.0.0-dev.33"
56
+ "@mikro-orm/core": "7.0.0-dev.331"
57
+ },
58
+ "engines": {
59
+ "node": ">= 22.17.0"
61
60
  }
62
61
  }