@mikro-orm/core 7.0.0-dev.2 → 7.0.0-dev.200

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 (210) hide show
  1. package/EntityManager.d.ts +111 -61
  2. package/EntityManager.js +346 -300
  3. package/MikroORM.d.ts +44 -35
  4. package/MikroORM.js +103 -143
  5. package/README.md +3 -2
  6. package/cache/FileCacheAdapter.d.ts +1 -1
  7. package/cache/FileCacheAdapter.js +8 -7
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +0 -1
  11. package/cache/index.js +0 -1
  12. package/connections/Connection.d.ts +16 -7
  13. package/connections/Connection.js +23 -14
  14. package/drivers/DatabaseDriver.d.ts +25 -16
  15. package/drivers/DatabaseDriver.js +80 -35
  16. package/drivers/IDatabaseDriver.d.ts +47 -17
  17. package/entity/BaseEntity.d.ts +2 -2
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +95 -31
  20. package/entity/Collection.js +444 -102
  21. package/entity/EntityAssigner.d.ts +1 -1
  22. package/entity/EntityAssigner.js +26 -18
  23. package/entity/EntityFactory.d.ts +13 -1
  24. package/entity/EntityFactory.js +88 -54
  25. package/entity/EntityHelper.d.ts +2 -2
  26. package/entity/EntityHelper.js +38 -15
  27. package/entity/EntityLoader.d.ts +8 -7
  28. package/entity/EntityLoader.js +134 -80
  29. package/entity/EntityRepository.d.ts +24 -4
  30. package/entity/EntityRepository.js +8 -2
  31. package/entity/Reference.d.ts +9 -12
  32. package/entity/Reference.js +34 -9
  33. package/entity/WrappedEntity.d.ts +2 -7
  34. package/entity/WrappedEntity.js +3 -8
  35. package/entity/defineEntity.d.ts +585 -0
  36. package/entity/defineEntity.js +533 -0
  37. package/entity/index.d.ts +3 -2
  38. package/entity/index.js +3 -2
  39. package/entity/utils.d.ts +7 -0
  40. package/entity/utils.js +16 -4
  41. package/entity/validators.d.ts +11 -0
  42. package/entity/validators.js +65 -0
  43. package/enums.d.ts +22 -6
  44. package/enums.js +15 -1
  45. package/errors.d.ts +23 -9
  46. package/errors.js +59 -21
  47. package/events/EventManager.d.ts +2 -1
  48. package/events/EventManager.js +19 -11
  49. package/events/EventSubscriber.d.ts +3 -1
  50. package/hydration/Hydrator.js +1 -2
  51. package/hydration/ObjectHydrator.d.ts +4 -4
  52. package/hydration/ObjectHydrator.js +53 -33
  53. package/index.d.ts +2 -2
  54. package/index.js +1 -2
  55. package/logging/DefaultLogger.d.ts +1 -1
  56. package/logging/DefaultLogger.js +1 -0
  57. package/logging/SimpleLogger.d.ts +1 -1
  58. package/logging/colors.d.ts +1 -1
  59. package/logging/colors.js +7 -6
  60. package/logging/index.d.ts +1 -0
  61. package/logging/index.js +1 -0
  62. package/logging/inspect.d.ts +2 -0
  63. package/logging/inspect.js +11 -0
  64. package/metadata/EntitySchema.d.ts +26 -26
  65. package/metadata/EntitySchema.js +82 -51
  66. package/metadata/MetadataDiscovery.d.ts +7 -10
  67. package/metadata/MetadataDiscovery.js +408 -335
  68. package/metadata/MetadataProvider.d.ts +11 -2
  69. package/metadata/MetadataProvider.js +46 -2
  70. package/metadata/MetadataStorage.d.ts +13 -11
  71. package/metadata/MetadataStorage.js +70 -37
  72. package/metadata/MetadataValidator.d.ts +17 -9
  73. package/metadata/MetadataValidator.js +100 -42
  74. package/metadata/discover-entities.d.ts +5 -0
  75. package/metadata/discover-entities.js +40 -0
  76. package/metadata/index.d.ts +1 -1
  77. package/metadata/index.js +1 -1
  78. package/metadata/types.d.ts +502 -0
  79. package/metadata/types.js +1 -0
  80. package/naming-strategy/AbstractNamingStrategy.d.ts +12 -4
  81. package/naming-strategy/AbstractNamingStrategy.js +14 -2
  82. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  83. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  84. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  85. package/naming-strategy/MongoNamingStrategy.js +6 -6
  86. package/naming-strategy/NamingStrategy.d.ts +24 -4
  87. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  88. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  89. package/not-supported.d.ts +2 -0
  90. package/not-supported.js +4 -0
  91. package/package.json +19 -11
  92. package/platforms/ExceptionConverter.js +1 -1
  93. package/platforms/Platform.d.ts +7 -13
  94. package/platforms/Platform.js +20 -43
  95. package/serialization/EntitySerializer.d.ts +5 -0
  96. package/serialization/EntitySerializer.js +47 -27
  97. package/serialization/EntityTransformer.js +28 -18
  98. package/serialization/SerializationContext.d.ts +6 -6
  99. package/serialization/SerializationContext.js +16 -13
  100. package/types/ArrayType.d.ts +1 -1
  101. package/types/ArrayType.js +2 -3
  102. package/types/BigIntType.d.ts +9 -6
  103. package/types/BigIntType.js +4 -1
  104. package/types/BlobType.d.ts +0 -1
  105. package/types/BlobType.js +0 -3
  106. package/types/BooleanType.d.ts +2 -1
  107. package/types/BooleanType.js +3 -0
  108. package/types/DecimalType.d.ts +6 -4
  109. package/types/DecimalType.js +3 -3
  110. package/types/DoubleType.js +2 -2
  111. package/types/EnumArrayType.js +1 -2
  112. package/types/JsonType.d.ts +1 -1
  113. package/types/JsonType.js +7 -2
  114. package/types/TinyIntType.js +1 -1
  115. package/types/Type.d.ts +2 -4
  116. package/types/Type.js +3 -3
  117. package/types/Uint8ArrayType.d.ts +0 -1
  118. package/types/Uint8ArrayType.js +1 -4
  119. package/types/index.d.ts +1 -1
  120. package/typings.d.ts +300 -140
  121. package/typings.js +62 -44
  122. package/unit-of-work/ChangeSet.d.ts +2 -6
  123. package/unit-of-work/ChangeSet.js +4 -5
  124. package/unit-of-work/ChangeSetComputer.d.ts +1 -3
  125. package/unit-of-work/ChangeSetComputer.js +26 -13
  126. package/unit-of-work/ChangeSetPersister.d.ts +5 -4
  127. package/unit-of-work/ChangeSetPersister.js +77 -35
  128. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  129. package/unit-of-work/CommitOrderCalculator.js +13 -13
  130. package/unit-of-work/IdentityMap.d.ts +12 -0
  131. package/unit-of-work/IdentityMap.js +39 -1
  132. package/unit-of-work/UnitOfWork.d.ts +23 -3
  133. package/unit-of-work/UnitOfWork.js +199 -106
  134. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  135. package/utils/AbstractSchemaGenerator.js +22 -17
  136. package/utils/AsyncContext.d.ts +6 -0
  137. package/utils/AsyncContext.js +42 -0
  138. package/utils/Configuration.d.ts +779 -207
  139. package/utils/Configuration.js +146 -190
  140. package/utils/ConfigurationLoader.d.ts +1 -54
  141. package/utils/ConfigurationLoader.js +1 -352
  142. package/utils/Cursor.d.ts +3 -6
  143. package/utils/Cursor.js +27 -11
  144. package/utils/DataloaderUtils.d.ts +15 -5
  145. package/utils/DataloaderUtils.js +65 -17
  146. package/utils/EntityComparator.d.ts +13 -9
  147. package/utils/EntityComparator.js +164 -89
  148. package/utils/QueryHelper.d.ts +14 -6
  149. package/utils/QueryHelper.js +88 -26
  150. package/utils/RawQueryFragment.d.ts +48 -25
  151. package/utils/RawQueryFragment.js +67 -66
  152. package/utils/RequestContext.js +2 -2
  153. package/utils/TransactionContext.js +2 -2
  154. package/utils/TransactionManager.d.ts +65 -0
  155. package/utils/TransactionManager.js +223 -0
  156. package/utils/Utils.d.ts +13 -120
  157. package/utils/Utils.js +104 -375
  158. package/utils/clone.js +8 -23
  159. package/utils/env-vars.d.ts +7 -0
  160. package/utils/env-vars.js +97 -0
  161. package/utils/fs-utils.d.ts +32 -0
  162. package/utils/fs-utils.js +178 -0
  163. package/utils/index.d.ts +2 -1
  164. package/utils/index.js +2 -1
  165. package/utils/upsert-utils.d.ts +9 -4
  166. package/utils/upsert-utils.js +55 -4
  167. package/decorators/Check.d.ts +0 -3
  168. package/decorators/Check.js +0 -13
  169. package/decorators/CreateRequestContext.d.ts +0 -3
  170. package/decorators/CreateRequestContext.js +0 -29
  171. package/decorators/Embeddable.d.ts +0 -8
  172. package/decorators/Embeddable.js +0 -11
  173. package/decorators/Embedded.d.ts +0 -18
  174. package/decorators/Embedded.js +0 -18
  175. package/decorators/Entity.d.ts +0 -18
  176. package/decorators/Entity.js +0 -13
  177. package/decorators/Enum.d.ts +0 -9
  178. package/decorators/Enum.js +0 -16
  179. package/decorators/Filter.d.ts +0 -2
  180. package/decorators/Filter.js +0 -8
  181. package/decorators/Formula.d.ts +0 -5
  182. package/decorators/Formula.js +0 -15
  183. package/decorators/Indexed.d.ts +0 -17
  184. package/decorators/Indexed.js +0 -20
  185. package/decorators/ManyToMany.d.ts +0 -40
  186. package/decorators/ManyToMany.js +0 -14
  187. package/decorators/ManyToOne.d.ts +0 -30
  188. package/decorators/ManyToOne.js +0 -14
  189. package/decorators/OneToMany.d.ts +0 -28
  190. package/decorators/OneToMany.js +0 -17
  191. package/decorators/OneToOne.d.ts +0 -24
  192. package/decorators/OneToOne.js +0 -7
  193. package/decorators/PrimaryKey.d.ts +0 -9
  194. package/decorators/PrimaryKey.js +0 -20
  195. package/decorators/Property.d.ts +0 -250
  196. package/decorators/Property.js +0 -32
  197. package/decorators/Transactional.d.ts +0 -13
  198. package/decorators/Transactional.js +0 -28
  199. package/decorators/hooks.d.ts +0 -16
  200. package/decorators/hooks.js +0 -47
  201. package/decorators/index.d.ts +0 -17
  202. package/decorators/index.js +0 -17
  203. package/entity/ArrayCollection.d.ts +0 -116
  204. package/entity/ArrayCollection.js +0 -395
  205. package/entity/EntityValidator.d.ts +0 -19
  206. package/entity/EntityValidator.js +0 -150
  207. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  208. package/metadata/ReflectMetadataProvider.js +0 -44
  209. package/utils/resolveContextProvider.d.ts +0 -10
  210. package/utils/resolveContextProvider.js +0 -28
package/utils/Utils.js CHANGED
@@ -1,15 +1,7 @@
1
- import { createRequire } from 'node:module';
2
- import globby from 'globby';
3
- import { extname, isAbsolute, join, normalize, relative, resolve } from 'node:path';
4
- import { platform } from 'node:os';
5
- import { fileURLToPath, pathToFileURL } from 'node:url';
6
- import { existsSync, mkdirSync, readFileSync } from 'node:fs';
7
- import { createHash } from 'node:crypto';
8
- import { tokenize } from 'esprima';
9
1
  import { clone } from './clone.js';
10
- import { ARRAY_OPERATORS, JSON_KEY_OPERATORS, GroupOperator, PlainObject, QueryOperator, ReferenceKind } from '../enums.js';
2
+ import { GroupOperator, PlainObject, QueryOperator, ReferenceKind } from '../enums.js';
11
3
  import { helper } from '../entity/wrap.js';
12
- export const ObjectBindingPattern = Symbol('ObjectBindingPattern');
4
+ import { Raw } from './RawQueryFragment.js';
13
5
  function compareConstructors(a, b) {
14
6
  if (a.constructor === b.constructor) {
15
7
  return true;
@@ -41,9 +33,8 @@ export function compareObjects(a, b) {
41
33
  }
42
34
  return timeA === timeB;
43
35
  }
44
- /* v8 ignore next 9 */
36
+ /* v8 ignore next */
45
37
  if ((typeof a === 'function' && typeof b === 'function') ||
46
- (typeof a === 'object' && a.client && ['Ref', 'Raw'].includes(a.constructor.name) && typeof b === 'object' && b.client && ['Ref', 'Raw'].includes(b.constructor.name)) || // knex qb
47
38
  (a instanceof RegExp && b instanceof RegExp) ||
48
39
  (a instanceof String && b instanceof String) ||
49
40
  (a instanceof Number && b instanceof Number)) {
@@ -119,7 +110,7 @@ export function equals(a, b) {
119
110
  const equalsFn = equals;
120
111
  export function parseJsonSafe(value) {
121
112
  if (typeof value === 'string') {
122
- /* v8 ignore next 6 */
113
+ /* v8 ignore next */
123
114
  try {
124
115
  return JSON.parse(value);
125
116
  }
@@ -132,52 +123,13 @@ export function parseJsonSafe(value) {
132
123
  }
133
124
  export class Utils {
134
125
  static PK_SEPARATOR = '~~~';
135
- /* v8 ignore next */
136
- static dynamicImportProvider = (id) => import(id);
137
- /**
138
- * Checks if the argument is not undefined
139
- */
140
- static isDefined(data) {
141
- return typeof data !== 'undefined';
142
- }
126
+ static #ORM_VERSION = '7.0.0-dev.200';
143
127
  /**
144
128
  * Checks if the argument is instance of `Object`. Returns false for arrays.
145
129
  */
146
130
  static isObject(o) {
147
131
  return !!o && typeof o === 'object' && !Array.isArray(o);
148
132
  }
149
- /**
150
- * Relation decorators allow using two signatures
151
- * - using first parameter as options object
152
- * - using all parameters
153
- *
154
- * This function validates those two ways are not mixed and returns the final options object.
155
- * If the second way is used, we always consider the last parameter as options object.
156
- * @internal
157
- */
158
- static processDecoratorParameters(params) {
159
- const keys = Object.keys(params);
160
- const values = Object.values(params);
161
- if (!Utils.isPlainObject(values[0])) {
162
- const lastKey = keys[keys.length - 1];
163
- const last = params[lastKey];
164
- delete params[lastKey];
165
- return { ...last, ...params };
166
- }
167
- // validate only first parameter is used if its an option object
168
- const empty = (v) => v == null || (Utils.isPlainObject(v) && !Utils.hasObjectKeys(v));
169
- if (values.slice(1).some(v => !empty(v))) {
170
- throw new Error('Mixing first decorator parameter as options object with other parameters is forbidden. ' +
171
- 'If you want to use the options parameter at first position, provide all options inside it.');
172
- }
173
- return values[0];
174
- }
175
- /**
176
- * Checks if the argument is instance of `Object`, but not one of the blacklisted types. Returns false for arrays.
177
- */
178
- static isNotObject(o, not) {
179
- return this.isObject(o) && !not.some(cls => o instanceof cls);
180
- }
181
133
  /**
182
134
  * Removes `undefined` properties (recursively) so they are not saved as nulls
183
135
  */
@@ -225,18 +177,6 @@ export class Utils {
225
177
  }
226
178
  return false;
227
179
  }
228
- /**
229
- * Checks if the argument is string
230
- */
231
- static isString(s) {
232
- return typeof s === 'string';
233
- }
234
- /**
235
- * Checks if the argument is number
236
- */
237
- static isNumber(s) {
238
- return typeof s === 'number';
239
- }
240
180
  /**
241
181
  * Checks if arguments are deeply (but not strictly) equal.
242
182
  */
@@ -282,7 +222,7 @@ export class Utils {
282
222
  target[key] = Utils.copy(value);
283
223
  continue;
284
224
  }
285
- /* v8 ignore next 3 */
225
+ /* v8 ignore next */
286
226
  if (!(key in target)) {
287
227
  Object.assign(target, { [key]: {} });
288
228
  }
@@ -295,30 +235,6 @@ export class Utils {
295
235
  }
296
236
  return Utils._merge(target, sources, ignoreUndefined);
297
237
  }
298
- static getRootEntity(metadata, meta) {
299
- const base = meta.extends && metadata.find(Utils.className(meta.extends));
300
- if (!base || base === meta) { // make sure we do not fall into infinite loop
301
- return meta;
302
- }
303
- const root = Utils.getRootEntity(metadata, base);
304
- if (root.discriminatorColumn) {
305
- return root;
306
- }
307
- return meta;
308
- }
309
- /**
310
- * Computes difference between two objects, ignoring items missing in `b`.
311
- */
312
- static diff(a, b) {
313
- const ret = {};
314
- for (const k of Object.keys(b)) {
315
- if (Utils.equals(a[k], b[k])) {
316
- continue;
317
- }
318
- ret[k] = b[k];
319
- }
320
- return ret;
321
- }
322
238
  /**
323
239
  * Creates deep copy of given object.
324
240
  */
@@ -359,53 +275,37 @@ export class Utils {
359
275
  }
360
276
  }
361
277
  /**
362
- * Returns array of functions argument names. Uses `esprima` for source code analysis.
278
+ * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
363
279
  */
364
- static tokenize(func) {
365
- if (Array.isArray(func)) {
366
- return func;
367
- }
368
- /* v8 ignore next 5 */
369
- try {
370
- return tokenize(func.toString(), { tolerant: true });
280
+ static getConstructorParams(func) {
281
+ const source = func.toString();
282
+ const i = source.indexOf('constructor');
283
+ if (i === -1) {
284
+ return undefined;
371
285
  }
372
- catch {
373
- return [];
286
+ const start = source.indexOf('(', i);
287
+ if (start === -1) {
288
+ return undefined;
374
289
  }
375
- }
376
- /**
377
- * Returns array of functions argument names. Uses `esprima` for source code analysis.
378
- */
379
- static getParamNames(func, methodName) {
380
- const ret = [];
381
- const tokens = this.tokenize(func);
382
- let inside = 0;
383
- let currentBlockStart = 0;
384
- for (let i = 0; i < tokens.length; i++) {
385
- const token = tokens[i];
386
- if (token.type === 'Identifier' && token.value === methodName) {
387
- inside = 1;
388
- currentBlockStart = i;
389
- continue;
290
+ let depth = 0;
291
+ let end = start;
292
+ for (; end < source.length; end++) {
293
+ if (source[end] === '(') {
294
+ depth++;
390
295
  }
391
- if (inside === 1 && token.type === 'Punctuator' && token.value === '(') {
392
- inside = 2;
393
- currentBlockStart = i;
394
- continue;
296
+ if (source[end] === ')') {
297
+ depth--;
395
298
  }
396
- if (inside === 2 && token.type === 'Punctuator' && token.value === ')') {
299
+ if (depth === 0) {
397
300
  break;
398
301
  }
399
- if (inside === 2 && token.type === 'Punctuator' && token.value === '{' && i === currentBlockStart + 1) {
400
- ret.push(ObjectBindingPattern);
401
- i = tokens.findIndex((t, idx) => idx > i + 2 && t.type === 'Punctuator' && t.value === '}');
402
- continue;
403
- }
404
- if (inside === 2 && token.type === 'Identifier') {
405
- ret.push(token.value);
406
- }
407
302
  }
408
- return ret;
303
+ const raw = source.slice(start + 1, end);
304
+ return raw
305
+ .split(',')
306
+ .map(s => s.trim().replace(/=.*$/, '').trim())
307
+ .filter(Boolean)
308
+ .map(raw => raw.startsWith('{') && raw.endsWith('}') ? '' : raw);
409
309
  }
410
310
  /**
411
311
  * Checks whether the argument looks like primary key (string, number or ObjectId).
@@ -418,7 +318,7 @@ export class Utils {
418
318
  return true;
419
319
  }
420
320
  if (Utils.isObject(key)) {
421
- if (key.constructor && key.constructor.name.toLowerCase() === 'objectid') {
321
+ if (key.constructor?.name === 'ObjectId') {
422
322
  return true;
423
323
  }
424
324
  if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
@@ -435,7 +335,11 @@ export class Utils {
435
335
  return data;
436
336
  }
437
337
  if (Utils.isEntity(data, true)) {
438
- return helper(data).getPrimaryKey();
338
+ const wrapped = helper(data);
339
+ if (wrapped.__meta.compositePK) {
340
+ return wrapped.getPrimaryKeys();
341
+ }
342
+ return wrapped.getPrimaryKey();
439
343
  }
440
344
  if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
441
345
  return null;
@@ -444,7 +348,7 @@ export class Utils {
444
348
  if (meta.compositePK) {
445
349
  return this.getCompositeKeyValue(data, meta);
446
350
  }
447
- return data[meta.primaryKeys[0]] || data[meta.serializedPrimaryKey] || null;
351
+ return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
448
352
  }
449
353
  return null;
450
354
  }
@@ -483,8 +387,8 @@ export class Utils {
483
387
  static splitPrimaryKeys(key) {
484
388
  return key.split(this.PK_SEPARATOR);
485
389
  }
486
- static getPrimaryKeyValues(entity, primaryKeys, allowScalar = false, convertCustomTypes = false) {
487
- /* v8 ignore next 3 */
390
+ static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
391
+ /* v8 ignore next */
488
392
  if (entity == null) {
489
393
  return entity;
490
394
  }
@@ -494,15 +398,28 @@ export class Utils {
494
398
  }
495
399
  return val;
496
400
  }
497
- const pk = Utils.isEntity(entity, true)
498
- ? helper(entity).getPrimaryKey(convertCustomTypes)
499
- : primaryKeys.reduce((o, pk) => { o[pk] = entity[pk]; return o; }, {});
500
- if (primaryKeys.length > 1) {
401
+ let pk;
402
+ if (Utils.isEntity(entity, true)) {
403
+ pk = helper(entity).getPrimaryKey(convertCustomTypes);
404
+ }
405
+ else {
406
+ pk = meta.primaryKeys.reduce((o, pk) => {
407
+ const targetMeta = meta.properties[pk].targetMeta;
408
+ if (targetMeta && Utils.isPlainObject(entity[pk])) {
409
+ o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
410
+ }
411
+ else {
412
+ o[pk] = entity[pk];
413
+ }
414
+ return o;
415
+ }, {});
416
+ }
417
+ if (meta.primaryKeys.length > 1) {
501
418
  return toArray(pk);
502
419
  }
503
420
  if (allowScalar) {
504
421
  if (Utils.isPlainObject(pk)) {
505
- return pk[primaryKeys[0]];
422
+ return pk[(meta.primaryKeys)[0]];
506
423
  }
507
424
  return pk;
508
425
  }
@@ -546,7 +463,7 @@ export class Utils {
546
463
  return o;
547
464
  }, {});
548
465
  }
549
- static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false) {
466
+ static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
550
467
  const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id);
551
468
  const pks = meta.primaryKeys.map((pk, idx) => {
552
469
  const prop = meta.properties[pk];
@@ -556,11 +473,14 @@ export class Utils {
556
473
  value = prop.customType.convertToJSValue(value, platform);
557
474
  }
558
475
  if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
559
- const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes);
476
+ const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
560
477
  value = value2.length > 1 ? value2 : value2[0];
561
478
  }
562
479
  return value;
563
480
  });
481
+ if (allowScalar && pks.length === 1) {
482
+ return pks[0];
483
+ }
564
484
  // we need to flatten the PKs as composite PKs can be build from another composite PKs
565
485
  // and this method is used to get the PK hash in identity map, that expects flat array
566
486
  return Utils.flatten(pks);
@@ -583,12 +503,6 @@ export class Utils {
583
503
  static isScalarReference(data, allowReference = false) {
584
504
  return typeof data === 'object' && data?.__scalarReference;
585
505
  }
586
- /**
587
- * Checks whether the argument is ObjectId instance
588
- */
589
- static isObjectID(key) {
590
- return Utils.isObject(key) && key.constructor && key.constructor.name.toLowerCase() === 'objectid';
591
- }
592
506
  /**
593
507
  * Checks whether the argument is empty (array without items, object without keys or falsy value).
594
508
  */
@@ -619,50 +533,20 @@ export class Utils {
619
533
  * Tries to detect TypeScript support.
620
534
  */
621
535
  static detectTypeScriptSupport() {
622
- /* v8 ignore next 7 */
623
- return process.argv[0].endsWith('ts-node') // running via ts-node directly
624
- || !!process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS // forced explicitly or enabled via `registerTypeScriptSupport()`
625
- || !!process.env.TS_JEST // check if ts-jest is used (works only with v27.0.4+)
626
- || !!process.env.VITEST // check if vitest is used
627
- || !!process.versions.bun // check if bun is used
628
- || process.argv.slice(1).some(arg => arg.includes('ts-node')) // registering ts-node runner
629
- || process.execArgv.some(arg => arg === 'ts-node/esm'); // check for ts-node/esm module loader
630
- }
631
- /**
632
- * Uses some dark magic to get source path to caller where decorator is used.
633
- * Analyses stack trace of error created inside the function call.
634
- */
635
- static lookupPathFromDecorator(name, stack) {
636
- // use some dark magic to get source path to caller
637
- stack = stack || new Error().stack.split('\n');
638
- // In some situations (e.g. swc 1.3.4+), the presence of a source map can obscure the call to
639
- // __decorate(), replacing it with the constructor name. To support these cases we look for
640
- // Reflect.decorate() as well. Also when babel is used, we need to check
641
- // the `_applyDecoratedDescriptor` method instead.
642
- let line = stack.findIndex(line => line.match(/__decorate|Reflect\.decorate|_applyDecoratedDescriptor/));
643
- // bun does not have those lines at all, only the DecorateProperty/DecorateConstructor,
644
- // but those are also present in node, so we need to check this only if they weren't found.
645
- if (line === -1) {
646
- // here we handle bun which stack is different from nodejs so we search for reflect-metadata
647
- const reflectLine = stack.findIndex(line => Utils.normalizePath(line).includes('node_modules/reflect-metadata/Reflect.js'));
648
- if (reflectLine === -1 || reflectLine + 2 >= stack.length || !stack[reflectLine + 1].includes('bun:wrap')) {
649
- return name;
650
- }
651
- line = reflectLine + 2;
652
- }
653
- if (stack[line].includes('Reflect.decorate')) {
654
- line++;
655
- }
656
- if (Utils.normalizePath(stack[line]).includes('node_modules/tslib/tslib')) {
657
- line++;
658
- }
659
- try {
660
- const re = stack[line].match(/\(.+\)/i) ? /\((.*):\d+:\d+\)/ : /at\s*(.*):\d+:\d+$/;
661
- return Utils.normalizePath(stack[line].match(re)[1]);
662
- }
663
- catch {
664
- return name;
665
- }
536
+ /* v8 ignore next */
537
+ const process = globalThis.process ?? {};
538
+ /* v8 ignore next */
539
+ return process.argv?.[0]?.endsWith('ts-node') // running via ts-node directly
540
+ || !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS // forced explicitly or enabled via `registerTypeScriptSupport()`
541
+ || !!process.env?.TS_JEST // check if ts-jest is used
542
+ || !!process.env?.VITEST // check if vitest is used
543
+ || !!process.versions?.bun // check if bun is used
544
+ || process.argv?.slice(1).some(arg => arg.match(/\.([mc]?ts|tsx)$/)) // executing `.ts` file
545
+ || process.execArgv?.some(arg => {
546
+ return arg.includes('ts-node') // check for ts-node loader
547
+ || arg.includes('@swc-node/register') // check for swc-node/register loader
548
+ || arg.includes('node_modules/tsx/'); // check for tsx loader
549
+ });
666
550
  }
667
551
  /**
668
552
  * Gets the type of the argument.
@@ -673,11 +557,11 @@ export class Utils {
673
557
  return simple;
674
558
  }
675
559
  const objectType = Object.prototype.toString.call(value);
676
- const type = objectType.match(/\[object (\w+)]/)[1];
560
+ const type = objectType.match(/^\[object (.+)]$/)[1];
677
561
  if (type === 'Uint8Array') {
678
562
  return 'Buffer';
679
563
  }
680
- return ['Date', 'Buffer', 'RegExp'].includes(type) ? type : type.toLowerCase();
564
+ return type;
681
565
  }
682
566
  /**
683
567
  * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
@@ -703,66 +587,14 @@ export class Utils {
703
587
  static isCollection(item) {
704
588
  return item?.__collection;
705
589
  }
706
- static fileURLToPath(url) {
707
- // expose `fileURLToPath` on Utils so that it can be properly mocked in tests
708
- return fileURLToPath(url);
709
- }
710
- /**
711
- * Resolves and normalizes a series of path parts relative to each preceding part.
712
- * If any part is a `file:` URL, it is converted to a local path. If any part is an
713
- * absolute path, it replaces preceding paths (similar to `path.resolve` in NodeJS).
714
- * Trailing directory separators are removed, and all directory separators are converted
715
- * to POSIX-style separators (`/`).
716
- */
717
- static normalizePath(...parts) {
718
- let start = 0;
719
- for (let i = 0; i < parts.length; i++) {
720
- const part = parts[i];
721
- if (isAbsolute(part)) {
722
- start = i;
723
- }
724
- else if (part.startsWith('file:')) {
725
- start = i;
726
- parts[i] = Utils.fileURLToPath(part);
727
- }
728
- }
729
- if (start > 0) {
730
- parts = parts.slice(start);
731
- }
732
- let path = parts.join('/').replace(/\\/g, '/').replace(/\/$/, '');
733
- path = normalize(path).replace(/\\/g, '/');
734
- return (path.match(/^[/.]|[a-zA-Z]:/) || path.startsWith('!')) ? path : './' + path;
735
- }
736
- /**
737
- * Determines the relative path between two paths. If either path is a `file:` URL,
738
- * it is converted to a local path.
739
- */
740
- static relativePath(path, relativeTo) {
741
- if (!path) {
742
- return path;
743
- }
744
- path = Utils.normalizePath(path);
745
- if (path.startsWith('.')) {
746
- return path;
747
- }
748
- path = relative(Utils.normalizePath(relativeTo), path);
749
- return Utils.normalizePath(path);
750
- }
751
- /**
752
- * Computes the absolute path to for the given path relative to the provided base directory.
753
- * If either `path` or `baseDir` are `file:` URLs, they are converted to local paths.
754
- */
755
- static absolutePath(path, baseDir = process.cwd()) {
756
- if (!path) {
757
- return Utils.normalizePath(baseDir);
758
- }
759
- if (!isAbsolute(path) && !path.startsWith('file://')) {
760
- path = baseDir + '/' + path;
761
- }
762
- return Utils.normalizePath(path);
763
- }
590
+ // FNV-1a 64-bit
764
591
  static hash(data, length) {
765
- const hash = createHash('md5').update(data).digest('hex');
592
+ let h1 = 0xcbf29ce484222325n;
593
+ for (let i = 0; i < data.length; i++) {
594
+ h1 ^= BigInt(data.charCodeAt(i));
595
+ h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
596
+ }
597
+ const hash = h1.toString(16).padStart(16, '0');
766
598
  if (length) {
767
599
  return hash.substring(0, length);
768
600
  }
@@ -794,13 +626,6 @@ export class Utils {
794
626
  static randomInt(min, max) {
795
627
  return Math.round(Math.random() * (max - min)) + min;
796
628
  }
797
- static async pathExists(path, options = {}) {
798
- if (globby.hasMagic(path)) {
799
- const found = await globby(path, options);
800
- return found.length > 0;
801
- }
802
- return this.pathExistsSync(path);
803
- }
804
629
  /**
805
630
  * Extracts all possible values of a TS enum. Works with both string and numeric enums.
806
631
  */
@@ -817,8 +642,8 @@ export class Utils {
817
642
  }
818
643
  return values;
819
644
  }
820
- static flatten(arrays) {
821
- return [].concat.apply([], arrays);
645
+ static flatten(arrays, deep) {
646
+ return arrays.flatMap(v => deep && Array.isArray(v) ? this.flatten(v, true) : v);
822
647
  }
823
648
  static isOperator(key, includeGroupOperators = true) {
824
649
  if (!includeGroupOperators) {
@@ -826,15 +651,6 @@ export class Utils {
826
651
  }
827
652
  return key in GroupOperator || key in QueryOperator;
828
653
  }
829
- static isGroupOperator(key) {
830
- return key in GroupOperator;
831
- }
832
- static isArrayOperator(key) {
833
- return ARRAY_OPERATORS.includes(key);
834
- }
835
- static isJsonKeyOperator(key) {
836
- return JSON_KEY_OPERATORS.includes(key);
837
- }
838
654
  static hasNestedKey(object, key) {
839
655
  if (!object) {
840
656
  return false;
@@ -847,66 +663,13 @@ export class Utils {
847
663
  }
848
664
  return false;
849
665
  }
850
- static getGlobalStorage(namespace) {
851
- const key = `mikro-orm-${namespace}`;
852
- globalThis[key] = globalThis[key] || {};
853
- return globalThis[key];
854
- }
855
- /**
856
- * Require a module from a specific location
857
- * @param id The module to require
858
- * @param [from] Location to start the node resolution
859
- */
860
- static requireFrom(id, from = process.cwd()) {
861
- if (!extname(from)) {
862
- from = join(from, '__fake.js');
863
- }
864
- return createRequire(resolve(from))(id);
865
- }
866
- static async dynamicImport(id) {
867
- /* v8 ignore next 7 */
868
- if (platform() === 'win32') {
869
- try {
870
- id = pathToFileURL(id).toString();
871
- }
872
- catch {
873
- // ignore
874
- }
875
- }
876
- /* v8 ignore next */
877
- return this.dynamicImportProvider(id);
878
- }
879
- /* v8 ignore next 3 */
880
- static setDynamicImportProvider(provider) {
881
- this.dynamicImportProvider = provider;
882
- }
883
- static ensureDir(path) {
884
- if (!existsSync(path)) {
885
- mkdirSync(path, { recursive: true });
886
- }
887
- }
888
- static pathExistsSync(path) {
889
- return existsSync(path);
890
- }
891
- static readJSONSync(path) {
892
- const file = readFileSync(path);
893
- return JSON.parse(file.toString());
894
- }
895
666
  static getORMVersion() {
896
- try {
897
- // this works during development where we have `src` folder
898
- return this.requireFrom('../../package.json', import.meta.dirname).version;
899
- /* v8 ignore next 5 */
900
- }
901
- catch {
902
- // this works in production build where we do not have the `src` folder
903
- return this.requireFrom('../package.json', import.meta.dirname).version;
904
- }
667
+ return this.#ORM_VERSION;
905
668
  }
906
669
  static createFunction(context, code) {
907
670
  try {
908
671
  return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
909
- /* v8 ignore next 5 */
672
+ /* v8 ignore next */
910
673
  }
911
674
  catch (e) {
912
675
  // eslint-disable-next-line no-console
@@ -919,7 +682,7 @@ export class Utils {
919
682
  return fn(...args);
920
683
  }
921
684
  catch (e) {
922
- /* v8 ignore start */
685
+ /* v8 ignore next */
923
686
  if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
924
687
  const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
925
688
  let code = fn.toString();
@@ -936,18 +699,9 @@ export class Utils {
936
699
  // eslint-disable-next-line no-console
937
700
  console.error(`JIT runtime error: ${e.message}\n\n${code}`);
938
701
  }
939
- /* v8 ignore stop */
940
702
  throw e;
941
703
  }
942
704
  }
943
- /**
944
- * @see https://github.com/mikro-orm/mikro-orm/issues/840
945
- */
946
- static propertyDecoratorReturnValue() {
947
- if (process.env.BABEL_DECORATORS_COMPAT) {
948
- return {};
949
- }
950
- }
951
705
  static unwrapProperty(entity, meta, prop, payload = false) {
952
706
  let p = prop;
953
707
  const path = [];
@@ -1027,54 +781,21 @@ export class Utils {
1027
781
  }
1028
782
  }
1029
783
  }
1030
- static tryRequire({ module, from, allowError, warning }) {
1031
- allowError ??= `Cannot find module '${module}'`;
1032
- from ??= process.cwd();
784
+ static async tryImport({ module, warning }) {
1033
785
  try {
1034
- return Utils.requireFrom(module, from);
786
+ return await import(module);
1035
787
  }
1036
788
  catch (err) {
1037
- if (err.message.includes(allowError)) {
1038
- // eslint-disable-next-line no-console
1039
- console.warn(warning);
789
+ if (err.code === 'ERR_MODULE_NOT_FOUND') {
790
+ if (warning) {
791
+ // eslint-disable-next-line no-console
792
+ console.warn(warning);
793
+ }
1040
794
  return undefined;
1041
795
  }
1042
796
  throw err;
1043
797
  }
1044
798
  }
1045
- static async tryImport({ module, warning }) {
1046
- try {
1047
- return await this.dynamicImport(module);
1048
- }
1049
- catch (err) {
1050
- // eslint-disable-next-line no-console
1051
- console.warn(warning);
1052
- return undefined;
1053
- }
1054
- }
1055
- static stripRelativePath(str) {
1056
- return str.replace(/^(?:\.\.\/|\.\/)+/, '/');
1057
- }
1058
- /**
1059
- * simple process.argv parser, supports only properties with long names, prefixed with `--`
1060
- */
1061
- static parseArgs() {
1062
- let lastKey;
1063
- return process.argv.slice(2).reduce((args, arg) => {
1064
- if (arg.includes('=')) {
1065
- const [key, value] = arg.split('=');
1066
- args[key.substring(2)] = value;
1067
- }
1068
- else if (lastKey) {
1069
- args[lastKey] = arg;
1070
- lastKey = undefined;
1071
- }
1072
- else if (arg.startsWith('--')) {
1073
- lastKey = arg.substring(2);
1074
- }
1075
- return args;
1076
- }, {});
1077
- }
1078
799
  static xor(a, b) {
1079
800
  return (a || b) && !(a && b);
1080
801
  }
@@ -1103,4 +824,12 @@ export class Utils {
1103
824
  return o;
1104
825
  }, {});
1105
826
  }
827
+ static getObjectQueryKeys(obj) {
828
+ return Reflect.ownKeys(obj).filter(key => {
829
+ if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
830
+ return false;
831
+ }
832
+ return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
833
+ });
834
+ }
1106
835
  }