@mikro-orm/core 7.0.10 → 7.0.11-dev.1

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 (206) hide show
  1. package/EntityManager.d.ts +584 -885
  2. package/EntityManager.js +1900 -1927
  3. package/MikroORM.d.ts +74 -103
  4. package/MikroORM.js +178 -177
  5. package/README.md +1 -1
  6. package/cache/CacheAdapter.d.ts +36 -36
  7. package/cache/FileCacheAdapter.d.ts +24 -30
  8. package/cache/FileCacheAdapter.js +78 -80
  9. package/cache/GeneratedCacheAdapter.d.ts +20 -18
  10. package/cache/GeneratedCacheAdapter.js +30 -30
  11. package/cache/MemoryCacheAdapter.d.ts +20 -18
  12. package/cache/MemoryCacheAdapter.js +36 -35
  13. package/cache/NullCacheAdapter.d.ts +16 -16
  14. package/cache/NullCacheAdapter.js +24 -24
  15. package/connections/Connection.d.ts +84 -95
  16. package/connections/Connection.js +168 -165
  17. package/drivers/DatabaseDriver.d.ts +80 -186
  18. package/drivers/DatabaseDriver.js +443 -450
  19. package/drivers/IDatabaseDriver.d.ts +301 -440
  20. package/entity/BaseEntity.d.ts +83 -120
  21. package/entity/BaseEntity.js +43 -43
  22. package/entity/Collection.d.ts +181 -215
  23. package/entity/Collection.js +724 -730
  24. package/entity/EntityAssigner.d.ts +77 -88
  25. package/entity/EntityAssigner.js +230 -231
  26. package/entity/EntityFactory.d.ts +55 -67
  27. package/entity/EntityFactory.js +416 -457
  28. package/entity/EntityHelper.d.ts +23 -35
  29. package/entity/EntityHelper.js +290 -302
  30. package/entity/EntityIdentifier.d.ts +4 -4
  31. package/entity/EntityIdentifier.js +10 -10
  32. package/entity/EntityLoader.d.ts +72 -98
  33. package/entity/EntityLoader.js +776 -805
  34. package/entity/EntityRepository.d.ts +201 -316
  35. package/entity/EntityRepository.js +213 -213
  36. package/entity/PolymorphicRef.d.ts +5 -5
  37. package/entity/PolymorphicRef.js +10 -10
  38. package/entity/Reference.d.ts +83 -127
  39. package/entity/Reference.js +277 -281
  40. package/entity/WrappedEntity.d.ts +72 -115
  41. package/entity/WrappedEntity.js +166 -168
  42. package/entity/defineEntity.d.ts +654 -1359
  43. package/entity/defineEntity.js +518 -527
  44. package/entity/utils.d.ts +3 -13
  45. package/entity/utils.js +73 -71
  46. package/entity/validators.js +43 -43
  47. package/entity/wrap.js +8 -8
  48. package/enums.d.ts +253 -258
  49. package/enums.js +252 -251
  50. package/errors.d.ts +72 -114
  51. package/errors.js +253 -350
  52. package/events/EventManager.d.ts +14 -26
  53. package/events/EventManager.js +77 -79
  54. package/events/EventSubscriber.d.ts +29 -29
  55. package/events/TransactionEventBroadcaster.d.ts +8 -15
  56. package/events/TransactionEventBroadcaster.js +14 -14
  57. package/exceptions.d.ts +40 -23
  58. package/exceptions.js +52 -35
  59. package/hydration/Hydrator.d.ts +17 -42
  60. package/hydration/Hydrator.js +43 -43
  61. package/hydration/ObjectHydrator.d.ts +17 -50
  62. package/hydration/ObjectHydrator.js +418 -483
  63. package/index.d.ts +2 -116
  64. package/index.js +1 -10
  65. package/logging/DefaultLogger.d.ts +32 -34
  66. package/logging/DefaultLogger.js +86 -86
  67. package/logging/Logger.d.ts +41 -41
  68. package/logging/SimpleLogger.d.ts +11 -13
  69. package/logging/SimpleLogger.js +22 -22
  70. package/logging/colors.d.ts +6 -6
  71. package/logging/colors.js +10 -11
  72. package/logging/inspect.js +7 -7
  73. package/metadata/EntitySchema.d.ts +130 -214
  74. package/metadata/EntitySchema.js +412 -411
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1884 -1962
  77. package/metadata/MetadataProvider.d.ts +26 -29
  78. package/metadata/MetadataProvider.js +97 -95
  79. package/metadata/MetadataStorage.d.ts +32 -38
  80. package/metadata/MetadataStorage.js +118 -118
  81. package/metadata/MetadataValidator.d.ts +39 -39
  82. package/metadata/MetadataValidator.js +338 -381
  83. package/metadata/discover-entities.d.ts +2 -5
  84. package/metadata/discover-entities.js +37 -35
  85. package/metadata/types.d.ts +531 -615
  86. package/naming-strategy/AbstractNamingStrategy.d.ts +39 -54
  87. package/naming-strategy/AbstractNamingStrategy.js +85 -90
  88. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  89. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  90. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  91. package/naming-strategy/MongoNamingStrategy.js +18 -18
  92. package/naming-strategy/NamingStrategy.d.ts +99 -109
  93. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  94. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  95. package/not-supported.js +4 -7
  96. package/package.json +1 -1
  97. package/platforms/ExceptionConverter.d.ts +1 -1
  98. package/platforms/ExceptionConverter.js +4 -4
  99. package/platforms/Platform.d.ts +303 -312
  100. package/platforms/Platform.js +675 -695
  101. package/serialization/EntitySerializer.d.ts +26 -49
  102. package/serialization/EntitySerializer.js +218 -224
  103. package/serialization/EntityTransformer.d.ts +6 -10
  104. package/serialization/EntityTransformer.js +217 -219
  105. package/serialization/SerializationContext.d.ts +23 -27
  106. package/serialization/SerializationContext.js +105 -105
  107. package/types/ArrayType.d.ts +8 -8
  108. package/types/ArrayType.js +33 -33
  109. package/types/BigIntType.d.ts +10 -17
  110. package/types/BigIntType.js +37 -37
  111. package/types/BlobType.d.ts +3 -3
  112. package/types/BlobType.js +13 -13
  113. package/types/BooleanType.d.ts +4 -4
  114. package/types/BooleanType.js +12 -12
  115. package/types/CharacterType.d.ts +2 -2
  116. package/types/CharacterType.js +6 -6
  117. package/types/DateTimeType.d.ts +5 -5
  118. package/types/DateTimeType.js +15 -15
  119. package/types/DateType.d.ts +5 -5
  120. package/types/DateType.js +15 -15
  121. package/types/DecimalType.d.ts +7 -7
  122. package/types/DecimalType.js +26 -26
  123. package/types/DoubleType.d.ts +3 -3
  124. package/types/DoubleType.js +12 -12
  125. package/types/EnumArrayType.d.ts +5 -5
  126. package/types/EnumArrayType.js +24 -24
  127. package/types/EnumType.d.ts +3 -3
  128. package/types/EnumType.js +11 -11
  129. package/types/FloatType.d.ts +3 -3
  130. package/types/FloatType.js +9 -9
  131. package/types/IntegerType.d.ts +3 -3
  132. package/types/IntegerType.js +9 -9
  133. package/types/IntervalType.d.ts +4 -4
  134. package/types/IntervalType.js +12 -12
  135. package/types/JsonType.d.ts +8 -8
  136. package/types/JsonType.js +32 -32
  137. package/types/MediumIntType.d.ts +1 -1
  138. package/types/MediumIntType.js +3 -3
  139. package/types/SmallIntType.d.ts +3 -3
  140. package/types/SmallIntType.js +9 -9
  141. package/types/StringType.d.ts +4 -4
  142. package/types/StringType.js +12 -12
  143. package/types/TextType.d.ts +3 -3
  144. package/types/TextType.js +9 -9
  145. package/types/TimeType.d.ts +5 -5
  146. package/types/TimeType.js +17 -17
  147. package/types/TinyIntType.d.ts +3 -3
  148. package/types/TinyIntType.js +10 -10
  149. package/types/Type.d.ts +79 -83
  150. package/types/Type.js +82 -82
  151. package/types/Uint8ArrayType.d.ts +4 -4
  152. package/types/Uint8ArrayType.js +21 -21
  153. package/types/UnknownType.d.ts +4 -4
  154. package/types/UnknownType.js +12 -12
  155. package/types/UuidType.d.ts +5 -5
  156. package/types/UuidType.js +19 -19
  157. package/types/index.d.ts +49 -75
  158. package/types/index.js +26 -52
  159. package/typings.d.ts +741 -1254
  160. package/typings.js +233 -244
  161. package/unit-of-work/ChangeSet.d.ts +26 -26
  162. package/unit-of-work/ChangeSet.js +56 -56
  163. package/unit-of-work/ChangeSetComputer.d.ts +12 -12
  164. package/unit-of-work/ChangeSetComputer.js +179 -187
  165. package/unit-of-work/ChangeSetPersister.d.ts +50 -69
  166. package/unit-of-work/ChangeSetPersister.js +442 -465
  167. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  168. package/unit-of-work/CommitOrderCalculator.js +88 -89
  169. package/unit-of-work/IdentityMap.d.ts +31 -31
  170. package/unit-of-work/IdentityMap.js +105 -105
  171. package/unit-of-work/UnitOfWork.d.ts +141 -181
  172. package/unit-of-work/UnitOfWork.js +1223 -1237
  173. package/utils/AbstractMigrator.d.ts +91 -111
  174. package/utils/AbstractMigrator.js +275 -275
  175. package/utils/AbstractSchemaGenerator.d.ts +34 -43
  176. package/utils/AbstractSchemaGenerator.js +122 -121
  177. package/utils/AsyncContext.d.ts +3 -3
  178. package/utils/AsyncContext.js +35 -34
  179. package/utils/Configuration.d.ts +808 -852
  180. package/utils/Configuration.js +344 -359
  181. package/utils/Cursor.d.ts +22 -40
  182. package/utils/Cursor.js +127 -135
  183. package/utils/DataloaderUtils.d.ts +43 -58
  184. package/utils/DataloaderUtils.js +198 -203
  185. package/utils/EntityComparator.d.ts +82 -99
  186. package/utils/EntityComparator.js +737 -829
  187. package/utils/NullHighlighter.d.ts +1 -1
  188. package/utils/NullHighlighter.js +3 -3
  189. package/utils/QueryHelper.d.ts +51 -79
  190. package/utils/QueryHelper.js +364 -375
  191. package/utils/RawQueryFragment.d.ts +34 -50
  192. package/utils/RawQueryFragment.js +121 -122
  193. package/utils/RequestContext.d.ts +32 -32
  194. package/utils/RequestContext.js +53 -52
  195. package/utils/TransactionContext.d.ts +16 -16
  196. package/utils/TransactionContext.js +27 -27
  197. package/utils/TransactionManager.d.ts +58 -58
  198. package/utils/TransactionManager.js +200 -202
  199. package/utils/Utils.d.ts +145 -204
  200. package/utils/Utils.js +826 -826
  201. package/utils/clone.js +114 -105
  202. package/utils/env-vars.js +88 -90
  203. package/utils/fs-utils.d.ts +15 -15
  204. package/utils/fs-utils.js +182 -181
  205. package/utils/upsert-utils.d.ts +5 -20
  206. package/utils/upsert-utils.js +116 -114
package/utils/Utils.js CHANGED
@@ -6,862 +6,862 @@ import { Collection } from '../entity/Collection.js';
6
6
  import { EntityHelper } from '../entity/EntityHelper.js';
7
7
  import { Raw, isRaw } from './RawQueryFragment.js';
8
8
  function compareConstructors(a, b) {
9
- if (a.constructor === b.constructor) {
10
- return true;
11
- }
12
- if (!a.constructor) {
13
- return b.constructor === Object;
14
- }
15
- if (!b.constructor) {
16
- return a.constructor === Object;
17
- }
18
- return false;
9
+ if (a.constructor === b.constructor) {
10
+ return true;
11
+ }
12
+ if (!a.constructor) {
13
+ return b.constructor === Object;
14
+ }
15
+ if (!b.constructor) {
16
+ return a.constructor === Object;
17
+ }
18
+ return false;
19
19
  }
20
20
  /** Deeply compares two objects for equality, handling dates, regexes, and raw fragments. */
21
21
  export function compareObjects(a, b) {
22
- if (a === b || (a == null && b == null)) {
22
+ if (a === b || (a == null && b == null)) {
23
+ return true;
24
+ }
25
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {
26
+ return false;
27
+ }
28
+ // Raw fragments are compared by `sql` + `params` *before* the constructor
29
+ // check, so that two fragments carrying the same SQL but constructed by
30
+ // different CJS/ESM copies of this module (different classes, different
31
+ // prototypes) still compare as equal. Without this, the dual-package hazard
32
+ // would produce spurious change-set diffs when a raw fragment is used as a
33
+ // property value.
34
+ if (isRaw(a) && isRaw(b)) {
35
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
36
+ return a.sql === b.sql && compareArrays(a.params, b.params);
37
+ }
38
+ if (!compareConstructors(a, b)) {
39
+ return false;
40
+ }
41
+ if (a instanceof Date && b instanceof Date) {
42
+ const timeA = a.getTime();
43
+ const timeB = b.getTime();
44
+ if (isNaN(timeA) || isNaN(timeB)) {
45
+ throw new Error('Comparing invalid dates is not supported');
46
+ }
47
+ return timeA === timeB;
48
+ }
49
+ /* v8 ignore next */
50
+ if ((typeof a === 'function' && typeof b === 'function') ||
51
+ (a instanceof RegExp && b instanceof RegExp) ||
52
+ (a instanceof String && b instanceof String) ||
53
+ (a instanceof Number && b instanceof Number)) {
54
+ return a.toString() === b.toString();
55
+ }
56
+ const keys = Object.keys(a);
57
+ const length = keys.length;
58
+ if (length !== Object.keys(b).length) {
59
+ return false;
60
+ }
61
+ for (let i = length; i-- !== 0;) {
62
+ if (!Object.hasOwn(b, keys[i])) {
63
+ return false;
64
+ }
65
+ }
66
+ for (let i = length; i-- !== 0;) {
67
+ const key = keys[i];
68
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
69
+ if (!equals(a[key], b[key])) {
70
+ return false;
71
+ }
72
+ }
23
73
  return true;
24
- }
25
- if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {
26
- return false;
27
- }
28
- // Raw fragments are compared by `sql` + `params` *before* the constructor
29
- // check, so that two fragments carrying the same SQL but constructed by
30
- // different CJS/ESM copies of this module (different classes, different
31
- // prototypes) still compare as equal. Without this, the dual-package hazard
32
- // would produce spurious change-set diffs when a raw fragment is used as a
33
- // property value.
34
- if (isRaw(a) && isRaw(b)) {
35
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
36
- return a.sql === b.sql && compareArrays(a.params, b.params);
37
- }
38
- if (!compareConstructors(a, b)) {
39
- return false;
40
- }
41
- if (a instanceof Date && b instanceof Date) {
42
- const timeA = a.getTime();
43
- const timeB = b.getTime();
44
- if (isNaN(timeA) || isNaN(timeB)) {
45
- throw new Error('Comparing invalid dates is not supported');
46
- }
47
- return timeA === timeB;
48
- }
49
- /* v8 ignore next */
50
- if (
51
- (typeof a === 'function' && typeof b === 'function') ||
52
- (a instanceof RegExp && b instanceof RegExp) ||
53
- (a instanceof String && b instanceof String) ||
54
- (a instanceof Number && b instanceof Number)
55
- ) {
56
- return a.toString() === b.toString();
57
- }
58
- const keys = Object.keys(a);
59
- const length = keys.length;
60
- if (length !== Object.keys(b).length) {
61
- return false;
62
- }
63
- for (let i = length; i-- !== 0; ) {
64
- if (!Object.hasOwn(b, keys[i])) {
65
- return false;
66
- }
67
- }
68
- for (let i = length; i-- !== 0; ) {
69
- const key = keys[i];
70
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
71
- if (!equals(a[key], b[key])) {
72
- return false;
73
- }
74
- }
75
- return true;
76
74
  }
77
75
  /** Compares two arrays element-by-element for deep equality. */
78
76
  export function compareArrays(a, b) {
79
- const length = a.length;
80
- if (length !== b.length) {
81
- return false;
82
- }
83
- for (let i = length; i-- !== 0; ) {
84
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
85
- if (!equals(a[i], b[i])) {
86
- return false;
87
- }
88
- }
89
- return true;
77
+ const length = a.length;
78
+ if (length !== b.length) {
79
+ return false;
80
+ }
81
+ for (let i = length; i-- !== 0;) {
82
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
83
+ if (!equals(a[i], b[i])) {
84
+ return false;
85
+ }
86
+ }
87
+ return true;
90
88
  }
91
89
  /** Compares two boolean values, treating numeric 0/1 as false/true. */
92
90
  export function compareBooleans(a, b) {
93
- a = typeof a === 'number' ? Boolean(a) : a;
94
- b = typeof b === 'number' ? Boolean(b) : b;
95
- return a === b;
91
+ a = typeof a === 'number' ? Boolean(a) : a;
92
+ b = typeof b === 'number' ? Boolean(b) : b;
93
+ return a === b;
96
94
  }
97
95
  /** Compares two byte arrays element-by-element. */
98
96
  export function compareBuffers(a, b) {
99
- const length = a.length;
100
- if (length !== b.length) {
101
- return false;
102
- }
103
- for (let i = length; i-- !== 0; ) {
104
- if (a[i] !== b[i]) {
105
- return false;
97
+ const length = a.length;
98
+ if (length !== b.length) {
99
+ return false;
100
+ }
101
+ for (let i = length; i-- !== 0;) {
102
+ if (a[i] !== b[i]) {
103
+ return false;
104
+ }
106
105
  }
107
- }
108
- return true;
106
+ return true;
109
107
  }
110
108
  /**
111
109
  * Checks if arguments are deeply (but not strictly) equal.
112
110
  */
113
111
  export function equals(a, b) {
114
- if (a === b) {
115
- return true;
116
- }
117
- if (a && b && typeof a === 'object' && typeof b === 'object') {
118
- if (Array.isArray(a)) {
119
- return compareArrays(a, b);
112
+ if (a === b) {
113
+ return true;
120
114
  }
121
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
122
- return compareBuffers(a, b);
115
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
116
+ if (Array.isArray(a)) {
117
+ return compareArrays(a, b);
118
+ }
119
+ if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
120
+ return compareBuffers(a, b);
121
+ }
122
+ return compareObjects(a, b);
123
123
  }
124
- return compareObjects(a, b);
125
- }
126
- return Number.isNaN(a) && Number.isNaN(b);
124
+ return Number.isNaN(a) && Number.isNaN(b);
127
125
  }
128
126
  const equalsFn = equals;
129
127
  /** Parses a JSON string safely, returning the original value if parsing fails. */
130
128
  export function parseJsonSafe(value) {
131
- if (typeof value === 'string') {
132
- /* v8 ignore next */
133
- try {
134
- return JSON.parse(value);
135
- } catch {
136
- // ignore and return the value, as sometimes we get the parsed value,
137
- // e.g. when it is a string value in JSON column
138
- }
139
- }
140
- return value;
129
+ if (typeof value === 'string') {
130
+ /* v8 ignore next */
131
+ try {
132
+ return JSON.parse(value);
133
+ }
134
+ catch {
135
+ // ignore and return the value, as sometimes we get the parsed value,
136
+ // e.g. when it is a string value in JSON column
137
+ }
138
+ }
139
+ return value;
141
140
  }
142
141
  /** Collection of general-purpose utility methods used throughout the ORM. */
143
142
  export class Utils {
144
- static PK_SEPARATOR = '~~~';
145
- static #ORM_VERSION = '7.0.10';
146
- /**
147
- * Checks if the argument is instance of `Object`. Returns false for arrays.
148
- */
149
- static isObject(o) {
150
- return !!o && typeof o === 'object' && !Array.isArray(o);
151
- }
152
- /**
153
- * Removes `undefined` properties (recursively) so they are not saved as nulls
154
- */
155
- static dropUndefinedProperties(o, value, visited = new Set()) {
156
- if (Array.isArray(o)) {
157
- for (const item of o) {
158
- Utils.dropUndefinedProperties(item, value, visited);
159
- }
160
- return;
161
- }
162
- if (!Utils.isPlainObject(o) || visited.has(o)) {
163
- return;
164
- }
165
- visited.add(o);
166
- for (const key of Object.keys(o)) {
167
- if (o[key] === value) {
168
- delete o[key];
169
- continue;
170
- }
171
- Utils.dropUndefinedProperties(o[key], value, visited);
172
- }
173
- }
174
- /**
175
- * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
176
- * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
177
- */
178
- static getObjectKeysSize(object) {
179
- let size = 0;
180
- for (const key in object) {
181
- if (Object.hasOwn(object, key)) {
182
- size++;
183
- }
184
- }
185
- return size;
186
- }
187
- /**
188
- * Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
189
- * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
190
- */
191
- static hasObjectKeys(object) {
192
- for (const key in object) {
193
- if (Object.hasOwn(object, key)) {
194
- return true;
195
- }
143
+ static PK_SEPARATOR = '~~~';
144
+ static #ORM_VERSION = '7.0.11-dev.1';
145
+ /**
146
+ * Checks if the argument is instance of `Object`. Returns false for arrays.
147
+ */
148
+ static isObject(o) {
149
+ return !!o && typeof o === 'object' && !Array.isArray(o);
150
+ }
151
+ /**
152
+ * Removes `undefined` properties (recursively) so they are not saved as nulls
153
+ */
154
+ static dropUndefinedProperties(o, value, visited = new Set()) {
155
+ if (Array.isArray(o)) {
156
+ for (const item of o) {
157
+ Utils.dropUndefinedProperties(item, value, visited);
158
+ }
159
+ return;
160
+ }
161
+ if (!Utils.isPlainObject(o) || visited.has(o)) {
162
+ return;
163
+ }
164
+ visited.add(o);
165
+ for (const key of Object.keys(o)) {
166
+ if (o[key] === value) {
167
+ delete o[key];
168
+ continue;
169
+ }
170
+ Utils.dropUndefinedProperties(o[key], value, visited);
171
+ }
196
172
  }
197
- return false;
198
- }
199
- /**
200
- * Checks if arguments are deeply (but not strictly) equal.
201
- */
202
- static equals(a, b) {
203
- return equalsFn(a, b);
204
- }
205
- /**
206
- * Gets array without duplicates.
207
- */
208
- static unique(items) {
209
- if (items.length < 2) {
210
- return items;
211
- }
212
- return [...new Set(items)];
213
- }
214
- /**
215
- * Merges all sources into the target recursively.
216
- */
217
- static merge(target, ...sources) {
218
- return Utils._merge(target, sources, false);
219
- }
220
- /**
221
- * Merges all sources into the target recursively. Ignores `undefined` values.
222
- */
223
- static mergeConfig(target, ...sources) {
224
- return Utils._merge(target, sources, true);
225
- }
226
- /**
227
- * Merges all sources into the target recursively.
228
- */
229
- static _merge(target, sources, ignoreUndefined) {
230
- if (!sources.length) {
231
- return target;
232
- }
233
- const source = sources.shift();
234
- if (Utils.isObject(target) && Utils.isPlainObject(source)) {
235
- for (const [key, value] of Object.entries(source)) {
236
- if (['__proto__', 'constructor', 'prototype'].includes(key)) {
237
- continue;
238
- }
239
- if (ignoreUndefined && typeof value === 'undefined') {
240
- continue;
241
- }
242
- if (Utils.isPlainObject(value)) {
243
- if (!Utils.isObject(target[key])) {
244
- target[key] = Utils.copy(value);
245
- continue;
246
- }
247
- /* v8 ignore next */
248
- if (!(key in target)) {
249
- Object.assign(target, { [key]: {} });
250
- }
251
- Utils._merge(target[key], [value], ignoreUndefined);
252
- } else {
253
- Object.assign(target, { [key]: value });
254
- }
255
- }
256
- }
257
- return Utils._merge(target, sources, ignoreUndefined);
258
- }
259
- /**
260
- * Creates deep copy of given object.
261
- */
262
- static copy(entity, respectCustomCloneMethod = true) {
263
- return clone(entity, respectCustomCloneMethod);
264
- }
265
- /**
266
- * Normalize the argument to always be an array.
267
- */
268
- static asArray(data, strict = false) {
269
- if (typeof data === 'undefined' && !strict) {
270
- return [];
271
- }
272
- if (this.isIterable(data)) {
273
- return Array.from(data);
274
- }
275
- return [data];
276
- }
277
- /**
278
- * Checks if the value is iterable, but considers strings and buffers as not iterable.
279
- */
280
- static isIterable(value) {
281
- if (value == null || typeof value === 'string' || ArrayBuffer.isView(value)) {
282
- return false;
283
- }
284
- return typeof Object(value)[Symbol.iterator] === 'function';
285
- }
286
- /**
287
- * Renames object key, keeps order of properties.
288
- */
289
- static renameKey(payload, from, to) {
290
- if (Utils.isObject(payload) && from in payload && !(to in payload)) {
291
- for (const key of Object.keys(payload)) {
292
- const value = payload[key];
293
- delete payload[key];
294
- payload[from === key ? to : key] = value;
295
- }
296
- }
297
- }
298
- /**
299
- * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
300
- */
301
- static getConstructorParams(func) {
302
- const source = func.toString();
303
- const i = source.indexOf('constructor');
304
- if (i === -1) {
305
- return undefined;
306
- }
307
- const start = source.indexOf('(', i);
308
- if (start === -1) {
309
- return undefined;
310
- }
311
- let depth = 0;
312
- let end = start;
313
- for (; end < source.length; end++) {
314
- if (source[end] === '(') {
315
- depth++;
316
- }
317
- if (source[end] === ')') {
318
- depth--;
319
- }
320
- if (depth === 0) {
321
- break;
322
- }
323
- }
324
- const raw = source.slice(start + 1, end);
325
- return raw
326
- .split(',')
327
- .map(s => s.trim().replace(/=.*$/, '').trim())
328
- .filter(Boolean)
329
- .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
330
- }
331
- /**
332
- * Checks whether the argument looks like primary key (string, number or ObjectId).
333
- */
334
- static isPrimaryKey(key, allowComposite = false) {
335
- if (['string', 'number', 'bigint'].includes(typeof key)) {
336
- return true;
337
- }
338
- if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
339
- return true;
340
- }
341
- if (Utils.isObject(key)) {
342
- if (key.constructor?.name === 'ObjectId') {
343
- return true;
344
- }
345
- if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
346
- return true;
347
- }
173
+ /**
174
+ * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
175
+ * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
176
+ */
177
+ static getObjectKeysSize(object) {
178
+ let size = 0;
179
+ for (const key in object) {
180
+ if (Object.hasOwn(object, key)) {
181
+ size++;
182
+ }
183
+ }
184
+ return size;
185
+ }
186
+ /**
187
+ * Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
188
+ * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
189
+ */
190
+ static hasObjectKeys(object) {
191
+ for (const key in object) {
192
+ if (Object.hasOwn(object, key)) {
193
+ return true;
194
+ }
195
+ }
196
+ return false;
348
197
  }
349
- return false;
350
- }
351
- /**
352
- * Extracts primary key from `data`. Accepts objects or primary keys directly.
353
- */
354
- static extractPK(data, meta, strict = false) {
355
- if (Utils.isPrimaryKey(data)) {
356
- return data;
357
- }
358
- if (Utils.isEntity(data, true)) {
359
- const wrapped = helper(data);
360
- if (wrapped.__meta.compositePK) {
361
- return wrapped.getPrimaryKeys();
362
- }
363
- return wrapped.getPrimaryKey();
364
- }
365
- if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
366
- return null;
367
- }
368
- if (Utils.isPlainObject(data) && meta) {
369
- if (meta.compositePK) {
370
- return this.getCompositeKeyValue(data, meta);
371
- }
372
- return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
373
- }
374
- return null;
375
- }
376
- static getCompositeKeyValue(data, meta, convertCustomTypes = false, platform) {
377
- return meta.primaryKeys.map((pk, idx) => {
378
- const value = Array.isArray(data) ? data[idx] : data[pk];
379
- const prop = meta.properties[pk];
380
- if (prop.targetMeta && Utils.isPlainObject(value)) {
381
- return this.getCompositeKeyValue(value, prop.targetMeta);
382
- }
383
- if (prop.customType && platform && convertCustomTypes) {
384
- const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
385
- return prop.customType[method](value, platform);
386
- }
387
- return value;
388
- });
389
- }
390
- static getCompositeKeyHash(data, meta, convertCustomTypes = false, platform, flat = false) {
391
- let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
392
- if (flat) {
393
- pks = Utils.flatten(pks);
394
- }
395
- return Utils.getPrimaryKeyHash(pks);
396
- }
397
- static getPrimaryKeyHash(pks) {
398
- return pks
399
- .map(pk => {
400
- if (Buffer.isBuffer(pk)) {
401
- return pk.toString('hex');
402
- }
403
- if (pk instanceof Date) {
404
- return pk.toISOString();
405
- }
406
- return pk;
407
- })
408
- .join(this.PK_SEPARATOR);
409
- }
410
- static splitPrimaryKeys(key) {
411
- return key.split(this.PK_SEPARATOR);
412
- }
413
- static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
414
- /* v8 ignore next */
415
- if (entity == null) {
416
- return entity;
417
- }
418
- function toArray(val) {
419
- if (Utils.isPlainObject(val)) {
420
- return Object.values(val).flatMap(v => toArray(v));
421
- }
422
- return val;
423
- }
424
- let pk;
425
- if (Utils.isEntity(entity, true)) {
426
- pk = helper(entity).getPrimaryKey(convertCustomTypes);
427
- } else {
428
- pk = meta.primaryKeys.reduce((o, pk) => {
429
- const targetMeta = meta.properties[pk].targetMeta;
430
- if (targetMeta && Utils.isPlainObject(entity[pk])) {
431
- o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
432
- } else {
433
- o[pk] = entity[pk];
434
- }
435
- return o;
436
- }, {});
437
- }
438
- if (meta.primaryKeys.length > 1) {
439
- return toArray(pk);
440
- }
441
- if (allowScalar) {
442
- if (Utils.isPlainObject(pk)) {
443
- return pk[meta.primaryKeys[0]];
444
- }
445
- return pk;
446
- }
447
- return [pk];
448
- }
449
- static getPrimaryKeyCond(entity, primaryKeys) {
450
- const cond = primaryKeys.reduce((o, pk) => {
451
- o[pk] = Utils.extractPK(entity[pk]);
452
- return o;
453
- }, {});
454
- if (Object.values(cond).some(v => v === null)) {
455
- return null;
456
- }
457
- return cond;
458
- }
459
- /**
460
- * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
461
- */
462
- static mapFlatCompositePrimaryKey(fk, prop, fieldNames = prop.fieldNames, idx = 0) {
463
- if (!prop.targetMeta) {
464
- return fk[idx++];
465
- }
466
- const parts = [];
467
- for (const pk of prop.targetMeta.getPrimaryProps()) {
468
- parts.push(this.mapFlatCompositePrimaryKey(fk, pk, fieldNames, idx));
469
- idx += pk.fieldNames.length;
470
- }
471
- if (parts.length < 2) {
472
- return parts[0];
473
- }
474
- return parts;
475
- }
476
- static getPrimaryKeyCondFromArray(pks, meta) {
477
- return meta.getPrimaryProps().reduce((o, pk, idx) => {
478
- if (Array.isArray(pks[idx]) && pk.targetMeta) {
479
- o[pk.name] = pks[idx];
480
- } else {
481
- o[pk.name] = Utils.extractPK(pks[idx], meta);
482
- }
483
- return o;
484
- }, {});
485
- }
486
- static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
487
- const data = Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id;
488
- const pks = meta.primaryKeys.map((pk, idx) => {
489
- const prop = meta.properties[pk];
490
- // `data` can be a composite PK in form of array of PKs, or a DTO
491
- let value = Array.isArray(data) ? data[idx] : (data[pk] ?? data);
492
- if (convertCustomTypes && platform && prop.customType && !prop.targetMeta) {
493
- value = prop.customType.convertToJSValue(value, platform);
494
- }
495
- if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
496
- const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
497
- value = value2.length > 1 ? value2 : value2[0];
498
- }
499
- return value;
500
- });
501
- if (allowScalar && pks.length === 1) {
502
- return pks[0];
503
- }
504
- // we need to flatten the PKs as composite PKs can be build from another composite PKs
505
- // and this method is used to get the PK hash in identity map, that expects flat array
506
- return Utils.flatten(pks);
507
- }
508
- /**
509
- * Checks whether given object is an entity instance.
510
- */
511
- static isEntity(data, allowReference = false) {
512
- if (!Utils.isObject(data)) {
513
- return false;
514
- }
515
- if (allowReference && Reference.isReference(data)) {
516
- return true;
517
- }
518
- return EntityHelper.isEntity(data);
519
- }
520
- /**
521
- * Checks whether given object is a scalar reference.
522
- */
523
- static isScalarReference(data) {
524
- return ScalarReference.isScalarReference(data);
525
- }
526
- /**
527
- * Checks whether the argument is empty (array without items, object without keys or falsy value).
528
- */
529
- static isEmpty(data) {
530
- if (Array.isArray(data)) {
531
- return data.length === 0;
532
- }
533
- if (Utils.isObject(data)) {
534
- return !Utils.hasObjectKeys(data);
535
- }
536
- return !data;
537
- }
538
- /**
539
- * Gets string name of given class.
540
- */
541
- static className(classOrName) {
542
- if (typeof classOrName === 'string') {
543
- return classOrName;
544
- }
545
- return classOrName.name;
546
- }
547
- static extractChildElements(items, prefix, allSymbol) {
548
- return items
549
- .filter(field => field === allSymbol || field.startsWith(`${prefix}.`))
550
- .map(field => (field === allSymbol ? allSymbol : field.substring(prefix.length + 1)));
551
- }
552
- /**
553
- * Tries to detect TypeScript support.
554
- */
555
- static detectTypeScriptSupport() {
556
- /* v8 ignore next */
557
- const process = globalThis.process ?? {};
558
- /* v8 ignore next */
559
- return (
560
- process.argv?.[0]?.endsWith('ts-node') || // running via ts-node directly
561
- !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS || // forced explicitly or enabled via `registerTypeScriptSupport()`
562
- !!process.env?.TS_JEST || // check if ts-jest is used
563
- !!process.env?.VITEST || // check if vitest is used
564
- !!process.versions?.bun || // check if bun is used
565
- process.argv?.slice(1).some(arg => /\.([mc]?ts|tsx)$/.exec(arg)) || // executing `.ts` file
566
- process.execArgv?.some(arg => {
567
- return (
568
- arg.includes('ts-node') || // check for ts-node loader
569
- arg.includes('@swc-node/register') || // check for swc-node/register loader
570
- arg.includes('node_modules/tsx/') || // check for tsx loader
571
- arg.includes('@oxc-node/core') // check for oxc-node loader
572
- );
573
- })
574
- );
575
- }
576
- /**
577
- * Gets the type of the argument.
578
- */
579
- static getObjectType(value) {
580
- const simple = typeof value;
581
- if (['string', 'number', 'boolean', 'bigint'].includes(simple)) {
582
- return simple;
583
- }
584
- const objectType = Object.prototype.toString.call(value);
585
- const type = /^\[object (.+)]$/.exec(objectType)[1];
586
- if (type === 'Uint8Array') {
587
- return 'Buffer';
588
- }
589
- return type;
590
- }
591
- /**
592
- * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
593
- */
594
- static isPlainObject(value) {
595
- return (
596
- (value !== null &&
597
- typeof value === 'object' &&
598
- typeof value.constructor === 'function' &&
599
- (Object.hasOwn(value.constructor.prototype, 'isPrototypeOf') ||
600
- Object.getPrototypeOf(value.constructor.prototype) === null)) ||
601
- (value && Object.getPrototypeOf(value) === null) ||
602
- value instanceof PlainObject
603
- );
604
- }
605
- /**
606
- * Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
607
- */
608
- static async runSerial(items, cb) {
609
- const ret = [];
610
- for (const item of items) {
611
- ret.push(await cb(item));
612
- }
613
- return ret;
614
- }
615
- static isCollection(item) {
616
- return Collection.isCollection(item);
617
- }
618
- // FNV-1a 64-bit
619
- static hash(data, length) {
620
- let h1 = 0xcbf29ce484222325n;
621
- for (let i = 0; i < data.length; i++) {
622
- h1 ^= BigInt(data.charCodeAt(i));
623
- h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
624
- }
625
- const hash = h1.toString(16).padStart(16, '0');
626
- if (length) {
627
- return hash.substring(0, length);
628
- }
629
- return hash;
630
- }
631
- static runIfNotEmpty(clause, data) {
632
- if (!Utils.isEmpty(data)) {
633
- clause();
634
- }
635
- }
636
- static defaultValue(prop, option, defaultValue) {
637
- prop[option] = option in prop ? prop[option] : defaultValue;
638
- }
639
- static findDuplicates(items) {
640
- return items.reduce((acc, v, i, arr) => {
641
- return arr.indexOf(v) !== i && !acc.includes(v) ? acc.concat(v) : acc;
642
- }, []);
643
- }
644
- static removeDuplicates(items) {
645
- const ret = [];
646
- const contains = (arr, val) => !!arr.find(v => equals(val, v));
647
- for (const item of items) {
648
- if (!contains(ret, item)) {
649
- ret.push(item);
650
- }
651
- }
652
- return ret;
653
- }
654
- static randomInt(min, max) {
655
- return Math.round(Math.random() * (max - min)) + min;
656
- }
657
- /**
658
- * Extracts all possible values of a TS enum. Works with both string and numeric enums.
659
- */
660
- static extractEnumValues(target) {
661
- // skip namespace-merged functions (GH #7500)
662
- const entries = Object.entries(target).filter(([, v]) => typeof v !== 'function');
663
- const keys = entries.map(([k]) => k);
664
- const values = entries.map(([, v]) => v);
665
- const numeric = !!values.find(v => typeof v === 'number');
666
- const constEnum =
667
- values.length % 2 === 0 && // const enum will have even number of items
668
- values.slice(0, values.length / 2).every(v => typeof v === 'string') && // first half are strings
669
- values.slice(values.length / 2).every(v => typeof v === 'number') && // second half are numbers
670
- this.equals(
671
- keys,
672
- values
673
- .slice(values.length / 2)
674
- .concat(values.slice(0, values.length / 2))
675
- .map(v => '' + v),
676
- ); // and when swapped, it will match the keys
677
- if (numeric || constEnum) {
678
- return values.filter(val => !keys.includes(val));
679
- }
680
- return values;
681
- }
682
- static flatten(arrays, deep) {
683
- return arrays.flatMap(v => (deep && Array.isArray(v) ? this.flatten(v, true) : v));
684
- }
685
- static isOperator(key, includeGroupOperators = true) {
686
- if (!includeGroupOperators) {
687
- return key in QueryOperator;
688
- }
689
- return key in GroupOperator || key in QueryOperator;
690
- }
691
- static hasNestedKey(object, key) {
692
- if (!object) {
693
- return false;
694
- }
695
- if (Array.isArray(object)) {
696
- return object.some(o => this.hasNestedKey(o, key));
697
- }
698
- if (typeof object === 'object') {
699
- return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
198
+ /**
199
+ * Checks if arguments are deeply (but not strictly) equal.
200
+ */
201
+ static equals(a, b) {
202
+ return equalsFn(a, b);
203
+ }
204
+ /**
205
+ * Gets array without duplicates.
206
+ */
207
+ static unique(items) {
208
+ if (items.length < 2) {
209
+ return items;
210
+ }
211
+ return [...new Set(items)];
212
+ }
213
+ /**
214
+ * Merges all sources into the target recursively.
215
+ */
216
+ static merge(target, ...sources) {
217
+ return Utils._merge(target, sources, false);
218
+ }
219
+ /**
220
+ * Merges all sources into the target recursively. Ignores `undefined` values.
221
+ */
222
+ static mergeConfig(target, ...sources) {
223
+ return Utils._merge(target, sources, true);
224
+ }
225
+ /**
226
+ * Merges all sources into the target recursively.
227
+ */
228
+ static _merge(target, sources, ignoreUndefined) {
229
+ if (!sources.length) {
230
+ return target;
231
+ }
232
+ const source = sources.shift();
233
+ if (Utils.isObject(target) && Utils.isPlainObject(source)) {
234
+ for (const [key, value] of Object.entries(source)) {
235
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) {
236
+ continue;
237
+ }
238
+ if (ignoreUndefined && typeof value === 'undefined') {
239
+ continue;
240
+ }
241
+ if (Utils.isPlainObject(value)) {
242
+ if (!Utils.isObject(target[key])) {
243
+ target[key] = Utils.copy(value);
244
+ continue;
245
+ }
246
+ /* v8 ignore next */
247
+ if (!(key in target)) {
248
+ Object.assign(target, { [key]: {} });
249
+ }
250
+ Utils._merge(target[key], [value], ignoreUndefined);
251
+ }
252
+ else {
253
+ Object.assign(target, { [key]: value });
254
+ }
255
+ }
256
+ }
257
+ return Utils._merge(target, sources, ignoreUndefined);
258
+ }
259
+ /**
260
+ * Creates deep copy of given object.
261
+ */
262
+ static copy(entity, respectCustomCloneMethod = true) {
263
+ return clone(entity, respectCustomCloneMethod);
264
+ }
265
+ /**
266
+ * Normalize the argument to always be an array.
267
+ */
268
+ static asArray(data, strict = false) {
269
+ if (typeof data === 'undefined' && !strict) {
270
+ return [];
271
+ }
272
+ if (this.isIterable(data)) {
273
+ return Array.from(data);
274
+ }
275
+ return [data];
276
+ }
277
+ /**
278
+ * Checks if the value is iterable, but considers strings and buffers as not iterable.
279
+ */
280
+ static isIterable(value) {
281
+ if (value == null || typeof value === 'string' || ArrayBuffer.isView(value)) {
282
+ return false;
283
+ }
284
+ return typeof Object(value)[Symbol.iterator] === 'function';
285
+ }
286
+ /**
287
+ * Renames object key, keeps order of properties.
288
+ */
289
+ static renameKey(payload, from, to) {
290
+ if (Utils.isObject(payload) && from in payload && !(to in payload)) {
291
+ for (const key of Object.keys(payload)) {
292
+ const value = payload[key];
293
+ delete payload[key];
294
+ payload[from === key ? to : key] = value;
295
+ }
296
+ }
700
297
  }
701
- return false;
702
- }
703
- static getORMVersion() {
704
- return this.#ORM_VERSION;
705
- }
706
- static createFunction(context, code, compiledFunctions, key) {
707
- if (key && compiledFunctions?.[key]) {
708
- return compiledFunctions[key](...context.values());
709
- }
710
- try {
711
- // eslint-disable-next-line @typescript-eslint/no-implied-eval
712
- return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
713
- /* v8 ignore next */
714
- } catch (e) {
715
- // eslint-disable-next-line no-console
716
- console.error(code);
717
- throw e;
718
- }
719
- }
720
- static callCompiledFunction(fn, ...args) {
721
- try {
722
- return fn(...args);
723
- } catch (e) {
724
- /* v8 ignore next */
725
- if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
726
- const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
727
- let code = fn.toString();
728
- if (position) {
729
- const lines = code.split('\n').map((line, idx) => {
730
- if (idx === +position[1] - 5) {
731
- return '> ' + line;
732
- }
733
- return ' ' + line;
734
- });
735
- lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
736
- code = lines.join('\n');
737
- }
738
- // eslint-disable-next-line no-console
739
- console.error(`JIT runtime error: ${e.message}\n\n${code}`);
740
- }
741
- throw e;
742
- }
743
- }
744
- static unwrapProperty(entity, meta, prop, payload = false) {
745
- let p = prop;
746
- const path = [];
747
- if (!prop.object && !prop.array && !prop.embedded) {
748
- return entity[prop.name] != null ? [[entity[prop.name], []]] : [];
749
- }
750
- while (p.embedded) {
751
- const child = meta.properties[p.embedded[0]];
752
- if (payload && !child.object && !child.array) {
753
- break;
754
- }
755
- path.shift();
756
- path.unshift(p.embedded[0], p.embedded[1]);
757
- p = child;
758
- }
759
- const ret = [];
760
- const follow = (t, idx = 0, i = []) => {
761
- const k = path[idx];
762
- if (Array.isArray(t)) {
763
- for (const t1 of t) {
764
- const ii = t.indexOf(t1);
765
- follow(t1, idx, [...i, ii]);
766
- }
767
- return;
768
- }
769
- if (t == null) {
770
- return;
771
- }
772
- const target = t[k];
773
- if (path[++idx]) {
774
- follow(target, idx, i);
775
- } else if (target != null) {
776
- ret.push([target, i]);
777
- }
778
- };
779
- follow(entity);
780
- return ret;
781
- }
782
- static setPayloadProperty(entity, meta, prop, value, idx) {
783
- if (!prop.object && !prop.array && !prop.embedded) {
784
- entity[prop.name] = value;
785
- return;
786
- }
787
- let target = entity;
788
- let p = prop;
789
- const path = [];
790
- while (p.embedded) {
791
- path.shift();
792
- path.unshift(p.embedded[0], p.embedded[1]);
793
- const prev = p;
794
- p = meta.properties[p.embedded[0]];
795
- if (!p.object) {
796
- path.shift();
797
- path[0] = prev.name;
798
- break;
799
- }
800
- }
801
- let j = 0;
802
- for (const k of path) {
803
- const i = path.indexOf(k);
804
- if (i === path.length - 1) {
805
- if (Array.isArray(target)) {
806
- target[idx[j++]][k] = value;
807
- } else {
808
- target[k] = value;
809
- }
810
- } else {
811
- if (Array.isArray(target)) {
812
- target = target[idx[j++]][k];
813
- } else {
814
- target = target[k];
815
- }
816
- }
817
- }
818
- }
819
- static async tryImport({ module, warning }) {
820
- try {
821
- return await import(module);
822
- } catch (err) {
823
- if (warning && err.code === 'ERR_MODULE_NOT_FOUND') {
824
- // eslint-disable-next-line no-console
825
- console.warn(warning);
826
- }
827
- return undefined;
828
- }
829
- }
830
- static xor(a, b) {
831
- return (a || b) && !(a && b);
832
- }
833
- static keys(obj) {
834
- return Object.keys(obj);
835
- }
836
- static values(obj) {
837
- return Object.values(obj);
838
- }
839
- static entries(obj) {
840
- return Object.entries(obj);
841
- }
842
- static primaryKeyToObject(meta, primaryKey, visible) {
843
- const pks =
844
- meta.compositePK && Utils.isPlainObject(primaryKey) ? Object.values(primaryKey) : Utils.asArray(primaryKey);
845
- const pkProps = meta.getPrimaryProps();
846
- return meta.primaryKeys.reduce((o, pk, idx) => {
847
- const pkProp = pkProps[idx];
848
- if (visible && !visible.includes(pkProp.name)) {
849
- return o;
850
- }
851
- if (Utils.isPlainObject(pks[idx]) && pkProp.targetMeta) {
852
- o[pk] = Utils.getOrderedPrimaryKeys(pks[idx], pkProp.targetMeta);
853
- return o;
854
- }
855
- o[pk] = pks[idx];
856
- return o;
857
- }, {});
858
- }
859
- static getObjectQueryKeys(obj) {
860
- return Reflect.ownKeys(obj).filter(key => {
861
- if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
298
+ /**
299
+ * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
300
+ */
301
+ static getConstructorParams(func) {
302
+ const source = func.toString();
303
+ const i = source.indexOf('constructor');
304
+ if (i === -1) {
305
+ return undefined;
306
+ }
307
+ const start = source.indexOf('(', i);
308
+ if (start === -1) {
309
+ return undefined;
310
+ }
311
+ let depth = 0;
312
+ let end = start;
313
+ for (; end < source.length; end++) {
314
+ if (source[end] === '(') {
315
+ depth++;
316
+ }
317
+ if (source[end] === ')') {
318
+ depth--;
319
+ }
320
+ if (depth === 0) {
321
+ break;
322
+ }
323
+ }
324
+ const raw = source.slice(start + 1, end);
325
+ return raw
326
+ .split(',')
327
+ .map(s => s.trim().replace(/=.*$/, '').trim())
328
+ .filter(Boolean)
329
+ .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
330
+ }
331
+ /**
332
+ * Checks whether the argument looks like primary key (string, number or ObjectId).
333
+ */
334
+ static isPrimaryKey(key, allowComposite = false) {
335
+ if (['string', 'number', 'bigint'].includes(typeof key)) {
336
+ return true;
337
+ }
338
+ if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
339
+ return true;
340
+ }
341
+ if (Utils.isObject(key)) {
342
+ if (key.constructor?.name === 'ObjectId') {
343
+ return true;
344
+ }
345
+ if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
346
+ return true;
347
+ }
348
+ }
349
+ return false;
350
+ }
351
+ /**
352
+ * Extracts primary key from `data`. Accepts objects or primary keys directly.
353
+ */
354
+ static extractPK(data, meta, strict = false) {
355
+ if (Utils.isPrimaryKey(data)) {
356
+ return data;
357
+ }
358
+ if (Utils.isEntity(data, true)) {
359
+ const wrapped = helper(data);
360
+ if (wrapped.__meta.compositePK) {
361
+ return wrapped.getPrimaryKeys();
362
+ }
363
+ return wrapped.getPrimaryKey();
364
+ }
365
+ if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
366
+ return null;
367
+ }
368
+ if (Utils.isPlainObject(data) && meta) {
369
+ if (meta.compositePK) {
370
+ return this.getCompositeKeyValue(data, meta);
371
+ }
372
+ return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
373
+ }
374
+ return null;
375
+ }
376
+ static getCompositeKeyValue(data, meta, convertCustomTypes = false, platform) {
377
+ return meta.primaryKeys.map((pk, idx) => {
378
+ const value = Array.isArray(data) ? data[idx] : data[pk];
379
+ const prop = meta.properties[pk];
380
+ if (prop.targetMeta && Utils.isPlainObject(value)) {
381
+ return this.getCompositeKeyValue(value, prop.targetMeta);
382
+ }
383
+ if (prop.customType && platform && convertCustomTypes) {
384
+ const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
385
+ return prop.customType[method](value, platform);
386
+ }
387
+ return value;
388
+ });
389
+ }
390
+ static getCompositeKeyHash(data, meta, convertCustomTypes = false, platform, flat = false) {
391
+ let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
392
+ if (flat) {
393
+ pks = Utils.flatten(pks);
394
+ }
395
+ return Utils.getPrimaryKeyHash(pks);
396
+ }
397
+ static getPrimaryKeyHash(pks) {
398
+ return pks
399
+ .map(pk => {
400
+ if (Buffer.isBuffer(pk)) {
401
+ return pk.toString('hex');
402
+ }
403
+ if (pk instanceof Date) {
404
+ return pk.toISOString();
405
+ }
406
+ return pk;
407
+ })
408
+ .join(this.PK_SEPARATOR);
409
+ }
410
+ static splitPrimaryKeys(key) {
411
+ return key.split(this.PK_SEPARATOR);
412
+ }
413
+ static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
414
+ /* v8 ignore next */
415
+ if (entity == null) {
416
+ return entity;
417
+ }
418
+ function toArray(val) {
419
+ if (Utils.isPlainObject(val)) {
420
+ return Object.values(val).flatMap(v => toArray(v));
421
+ }
422
+ return val;
423
+ }
424
+ let pk;
425
+ if (Utils.isEntity(entity, true)) {
426
+ pk = helper(entity).getPrimaryKey(convertCustomTypes);
427
+ }
428
+ else {
429
+ pk = meta.primaryKeys.reduce((o, pk) => {
430
+ const targetMeta = meta.properties[pk].targetMeta;
431
+ if (targetMeta && Utils.isPlainObject(entity[pk])) {
432
+ o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
433
+ }
434
+ else {
435
+ o[pk] = entity[pk];
436
+ }
437
+ return o;
438
+ }, {});
439
+ }
440
+ if (meta.primaryKeys.length > 1) {
441
+ return toArray(pk);
442
+ }
443
+ if (allowScalar) {
444
+ if (Utils.isPlainObject(pk)) {
445
+ return pk[meta.primaryKeys[0]];
446
+ }
447
+ return pk;
448
+ }
449
+ return [pk];
450
+ }
451
+ static getPrimaryKeyCond(entity, primaryKeys) {
452
+ const cond = primaryKeys.reduce((o, pk) => {
453
+ o[pk] = Utils.extractPK(entity[pk]);
454
+ return o;
455
+ }, {});
456
+ if (Object.values(cond).some(v => v === null)) {
457
+ return null;
458
+ }
459
+ return cond;
460
+ }
461
+ /**
462
+ * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
463
+ */
464
+ static mapFlatCompositePrimaryKey(fk, prop, fieldNames = prop.fieldNames, idx = 0) {
465
+ if (!prop.targetMeta) {
466
+ return fk[idx++];
467
+ }
468
+ const parts = [];
469
+ for (const pk of prop.targetMeta.getPrimaryProps()) {
470
+ parts.push(this.mapFlatCompositePrimaryKey(fk, pk, fieldNames, idx));
471
+ idx += pk.fieldNames.length;
472
+ }
473
+ if (parts.length < 2) {
474
+ return parts[0];
475
+ }
476
+ return parts;
477
+ }
478
+ static getPrimaryKeyCondFromArray(pks, meta) {
479
+ return meta.getPrimaryProps().reduce((o, pk, idx) => {
480
+ if (Array.isArray(pks[idx]) && pk.targetMeta) {
481
+ o[pk.name] = pks[idx];
482
+ }
483
+ else {
484
+ o[pk.name] = Utils.extractPK(pks[idx], meta);
485
+ }
486
+ return o;
487
+ }, {});
488
+ }
489
+ static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
490
+ const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id);
491
+ const pks = meta.primaryKeys.map((pk, idx) => {
492
+ const prop = meta.properties[pk];
493
+ // `data` can be a composite PK in form of array of PKs, or a DTO
494
+ let value = Array.isArray(data) ? data[idx] : (data[pk] ?? data);
495
+ if (convertCustomTypes && platform && prop.customType && !prop.targetMeta) {
496
+ value = prop.customType.convertToJSValue(value, platform);
497
+ }
498
+ if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
499
+ const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
500
+ value = value2.length > 1 ? value2 : value2[0];
501
+ }
502
+ return value;
503
+ });
504
+ if (allowScalar && pks.length === 1) {
505
+ return pks[0];
506
+ }
507
+ // we need to flatten the PKs as composite PKs can be build from another composite PKs
508
+ // and this method is used to get the PK hash in identity map, that expects flat array
509
+ return Utils.flatten(pks);
510
+ }
511
+ /**
512
+ * Checks whether given object is an entity instance.
513
+ */
514
+ static isEntity(data, allowReference = false) {
515
+ if (!Utils.isObject(data)) {
516
+ return false;
517
+ }
518
+ if (allowReference && Reference.isReference(data)) {
519
+ return true;
520
+ }
521
+ return EntityHelper.isEntity(data);
522
+ }
523
+ /**
524
+ * Checks whether given object is a scalar reference.
525
+ */
526
+ static isScalarReference(data) {
527
+ return ScalarReference.isScalarReference(data);
528
+ }
529
+ /**
530
+ * Checks whether the argument is empty (array without items, object without keys or falsy value).
531
+ */
532
+ static isEmpty(data) {
533
+ if (Array.isArray(data)) {
534
+ return data.length === 0;
535
+ }
536
+ if (Utils.isObject(data)) {
537
+ return !Utils.hasObjectKeys(data);
538
+ }
539
+ return !data;
540
+ }
541
+ /**
542
+ * Gets string name of given class.
543
+ */
544
+ static className(classOrName) {
545
+ if (typeof classOrName === 'string') {
546
+ return classOrName;
547
+ }
548
+ return classOrName.name;
549
+ }
550
+ static extractChildElements(items, prefix, allSymbol) {
551
+ return items
552
+ .filter(field => field === allSymbol || field.startsWith(`${prefix}.`))
553
+ .map(field => (field === allSymbol ? allSymbol : field.substring(prefix.length + 1)));
554
+ }
555
+ /**
556
+ * Tries to detect TypeScript support.
557
+ */
558
+ static detectTypeScriptSupport() {
559
+ /* v8 ignore next */
560
+ const process = globalThis.process ?? {};
561
+ /* v8 ignore next */
562
+ return (process.argv?.[0]?.endsWith('ts-node') || // running via ts-node directly
563
+ !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS || // forced explicitly or enabled via `registerTypeScriptSupport()`
564
+ !!process.env?.TS_JEST || // check if ts-jest is used
565
+ !!process.env?.VITEST || // check if vitest is used
566
+ !!process.versions?.bun || // check if bun is used
567
+ process.argv?.slice(1).some(arg => /\.([mc]?ts|tsx)$/.exec(arg)) || // executing `.ts` file
568
+ process.execArgv?.some(arg => {
569
+ return (arg.includes('ts-node') || // check for ts-node loader
570
+ arg.includes('@swc-node/register') || // check for swc-node/register loader
571
+ arg.includes('node_modules/tsx/') || // check for tsx loader
572
+ arg.includes('@oxc-node/core') // check for oxc-node loader
573
+ );
574
+ }));
575
+ }
576
+ /**
577
+ * Gets the type of the argument.
578
+ */
579
+ static getObjectType(value) {
580
+ const simple = typeof value;
581
+ if (['string', 'number', 'boolean', 'bigint'].includes(simple)) {
582
+ return simple;
583
+ }
584
+ const objectType = Object.prototype.toString.call(value);
585
+ const type = /^\[object (.+)]$/.exec(objectType)[1];
586
+ if (type === 'Uint8Array') {
587
+ return 'Buffer';
588
+ }
589
+ return type;
590
+ }
591
+ /**
592
+ * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
593
+ */
594
+ static isPlainObject(value) {
595
+ return ((value !== null &&
596
+ typeof value === 'object' &&
597
+ typeof value.constructor === 'function' &&
598
+ (Object.hasOwn(value.constructor.prototype, 'isPrototypeOf') ||
599
+ Object.getPrototypeOf(value.constructor.prototype) === null)) ||
600
+ (value && Object.getPrototypeOf(value) === null) ||
601
+ value instanceof PlainObject);
602
+ }
603
+ /**
604
+ * Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
605
+ */
606
+ static async runSerial(items, cb) {
607
+ const ret = [];
608
+ for (const item of items) {
609
+ ret.push(await cb(item));
610
+ }
611
+ return ret;
612
+ }
613
+ static isCollection(item) {
614
+ return Collection.isCollection(item);
615
+ }
616
+ // FNV-1a 64-bit
617
+ static hash(data, length) {
618
+ let h1 = 0xcbf29ce484222325n;
619
+ for (let i = 0; i < data.length; i++) {
620
+ h1 ^= BigInt(data.charCodeAt(i));
621
+ h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
622
+ }
623
+ const hash = h1.toString(16).padStart(16, '0');
624
+ if (length) {
625
+ return hash.substring(0, length);
626
+ }
627
+ return hash;
628
+ }
629
+ static runIfNotEmpty(clause, data) {
630
+ if (!Utils.isEmpty(data)) {
631
+ clause();
632
+ }
633
+ }
634
+ static defaultValue(prop, option, defaultValue) {
635
+ prop[option] = option in prop ? prop[option] : defaultValue;
636
+ }
637
+ static findDuplicates(items) {
638
+ return items.reduce((acc, v, i, arr) => {
639
+ return arr.indexOf(v) !== i && !acc.includes(v) ? acc.concat(v) : acc;
640
+ }, []);
641
+ }
642
+ static removeDuplicates(items) {
643
+ const ret = [];
644
+ const contains = (arr, val) => !!arr.find(v => equals(val, v));
645
+ for (const item of items) {
646
+ if (!contains(ret, item)) {
647
+ ret.push(item);
648
+ }
649
+ }
650
+ return ret;
651
+ }
652
+ static randomInt(min, max) {
653
+ return Math.round(Math.random() * (max - min)) + min;
654
+ }
655
+ /**
656
+ * Extracts all possible values of a TS enum. Works with both string and numeric enums.
657
+ */
658
+ static extractEnumValues(target) {
659
+ // skip namespace-merged functions (GH #7500)
660
+ const entries = Object.entries(target).filter(([, v]) => typeof v !== 'function');
661
+ const keys = entries.map(([k]) => k);
662
+ const values = entries.map(([, v]) => v);
663
+ const numeric = !!values.find(v => typeof v === 'number');
664
+ const constEnum = values.length % 2 === 0 && // const enum will have even number of items
665
+ values.slice(0, values.length / 2).every(v => typeof v === 'string') && // first half are strings
666
+ values.slice(values.length / 2).every(v => typeof v === 'number') && // second half are numbers
667
+ this.equals(keys, values
668
+ .slice(values.length / 2)
669
+ .concat(values.slice(0, values.length / 2))
670
+ .map(v => '' + v)); // and when swapped, it will match the keys
671
+ if (numeric || constEnum) {
672
+ return values.filter(val => !keys.includes(val));
673
+ }
674
+ return values;
675
+ }
676
+ static flatten(arrays, deep) {
677
+ return arrays.flatMap(v => (deep && Array.isArray(v) ? this.flatten(v, true) : v));
678
+ }
679
+ static isOperator(key, includeGroupOperators = true) {
680
+ if (!includeGroupOperators) {
681
+ return key in QueryOperator;
682
+ }
683
+ return key in GroupOperator || key in QueryOperator;
684
+ }
685
+ static hasNestedKey(object, key) {
686
+ if (!object) {
687
+ return false;
688
+ }
689
+ if (Array.isArray(object)) {
690
+ return object.some(o => this.hasNestedKey(o, key));
691
+ }
692
+ if (typeof object === 'object') {
693
+ return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
694
+ }
862
695
  return false;
863
- }
864
- return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
865
- });
866
- }
696
+ }
697
+ static getORMVersion() {
698
+ return this.#ORM_VERSION;
699
+ }
700
+ static createFunction(context, code, compiledFunctions, key) {
701
+ if (key && compiledFunctions?.[key]) {
702
+ return compiledFunctions[key](...context.values());
703
+ }
704
+ try {
705
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
706
+ return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
707
+ /* v8 ignore next */
708
+ }
709
+ catch (e) {
710
+ // eslint-disable-next-line no-console
711
+ console.error(code);
712
+ throw e;
713
+ }
714
+ }
715
+ static callCompiledFunction(fn, ...args) {
716
+ try {
717
+ return fn(...args);
718
+ }
719
+ catch (e) {
720
+ /* v8 ignore next */
721
+ if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
722
+ const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
723
+ let code = fn.toString();
724
+ if (position) {
725
+ const lines = code.split('\n').map((line, idx) => {
726
+ if (idx === +position[1] - 5) {
727
+ return '> ' + line;
728
+ }
729
+ return ' ' + line;
730
+ });
731
+ lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
732
+ code = lines.join('\n');
733
+ }
734
+ // eslint-disable-next-line no-console
735
+ console.error(`JIT runtime error: ${e.message}\n\n${code}`);
736
+ }
737
+ throw e;
738
+ }
739
+ }
740
+ static unwrapProperty(entity, meta, prop, payload = false) {
741
+ let p = prop;
742
+ const path = [];
743
+ if (!prop.object && !prop.array && !prop.embedded) {
744
+ return entity[prop.name] != null ? [[entity[prop.name], []]] : [];
745
+ }
746
+ while (p.embedded) {
747
+ const child = meta.properties[p.embedded[0]];
748
+ if (payload && !child.object && !child.array) {
749
+ break;
750
+ }
751
+ path.shift();
752
+ path.unshift(p.embedded[0], p.embedded[1]);
753
+ p = child;
754
+ }
755
+ const ret = [];
756
+ const follow = (t, idx = 0, i = []) => {
757
+ const k = path[idx];
758
+ if (Array.isArray(t)) {
759
+ for (const t1 of t) {
760
+ const ii = t.indexOf(t1);
761
+ follow(t1, idx, [...i, ii]);
762
+ }
763
+ return;
764
+ }
765
+ if (t == null) {
766
+ return;
767
+ }
768
+ const target = t[k];
769
+ if (path[++idx]) {
770
+ follow(target, idx, i);
771
+ }
772
+ else if (target != null) {
773
+ ret.push([target, i]);
774
+ }
775
+ };
776
+ follow(entity);
777
+ return ret;
778
+ }
779
+ static setPayloadProperty(entity, meta, prop, value, idx) {
780
+ if (!prop.object && !prop.array && !prop.embedded) {
781
+ entity[prop.name] = value;
782
+ return;
783
+ }
784
+ let target = entity;
785
+ let p = prop;
786
+ const path = [];
787
+ while (p.embedded) {
788
+ path.shift();
789
+ path.unshift(p.embedded[0], p.embedded[1]);
790
+ const prev = p;
791
+ p = meta.properties[p.embedded[0]];
792
+ if (!p.object) {
793
+ path.shift();
794
+ path[0] = prev.name;
795
+ break;
796
+ }
797
+ }
798
+ let j = 0;
799
+ for (const k of path) {
800
+ const i = path.indexOf(k);
801
+ if (i === path.length - 1) {
802
+ if (Array.isArray(target)) {
803
+ target[idx[j++]][k] = value;
804
+ }
805
+ else {
806
+ target[k] = value;
807
+ }
808
+ }
809
+ else {
810
+ if (Array.isArray(target)) {
811
+ target = target[idx[j++]][k];
812
+ }
813
+ else {
814
+ target = target[k];
815
+ }
816
+ }
817
+ }
818
+ }
819
+ static async tryImport({ module, warning, }) {
820
+ try {
821
+ return await import(module);
822
+ }
823
+ catch (err) {
824
+ if (warning && err.code === 'ERR_MODULE_NOT_FOUND') {
825
+ // eslint-disable-next-line no-console
826
+ console.warn(warning);
827
+ }
828
+ return undefined;
829
+ }
830
+ }
831
+ static xor(a, b) {
832
+ return (a || b) && !(a && b);
833
+ }
834
+ static keys(obj) {
835
+ return Object.keys(obj);
836
+ }
837
+ static values(obj) {
838
+ return Object.values(obj);
839
+ }
840
+ static entries(obj) {
841
+ return Object.entries(obj);
842
+ }
843
+ static primaryKeyToObject(meta, primaryKey, visible) {
844
+ const pks = meta.compositePK && Utils.isPlainObject(primaryKey) ? Object.values(primaryKey) : Utils.asArray(primaryKey);
845
+ const pkProps = meta.getPrimaryProps();
846
+ return meta.primaryKeys.reduce((o, pk, idx) => {
847
+ const pkProp = pkProps[idx];
848
+ if (visible && !visible.includes(pkProp.name)) {
849
+ return o;
850
+ }
851
+ if (Utils.isPlainObject(pks[idx]) && pkProp.targetMeta) {
852
+ o[pk] = Utils.getOrderedPrimaryKeys(pks[idx], pkProp.targetMeta);
853
+ return o;
854
+ }
855
+ o[pk] = pks[idx];
856
+ return o;
857
+ }, {});
858
+ }
859
+ static getObjectQueryKeys(obj) {
860
+ return Reflect.ownKeys(obj).filter(key => {
861
+ if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
862
+ return false;
863
+ }
864
+ return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
865
+ });
866
+ }
867
867
  }