@mikro-orm/core 7.0.0-dev.1 → 7.0.0-dev.100

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 (281) hide show
  1. package/EntityManager.d.ts +96 -58
  2. package/EntityManager.js +465 -395
  3. package/MikroORM.d.ts +45 -35
  4. package/MikroORM.js +109 -160
  5. package/README.md +3 -2
  6. package/cache/CacheAdapter.js +1 -2
  7. package/cache/FileCacheAdapter.d.ts +2 -2
  8. package/cache/FileCacheAdapter.js +20 -27
  9. package/cache/GeneratedCacheAdapter.d.ts +2 -3
  10. package/cache/GeneratedCacheAdapter.js +1 -7
  11. package/cache/MemoryCacheAdapter.d.ts +1 -1
  12. package/cache/MemoryCacheAdapter.js +1 -5
  13. package/cache/NullCacheAdapter.d.ts +1 -1
  14. package/cache/NullCacheAdapter.js +1 -5
  15. package/cache/index.d.ts +4 -5
  16. package/cache/index.js +4 -21
  17. package/connections/Connection.d.ts +22 -14
  18. package/connections/Connection.js +27 -23
  19. package/connections/index.d.ts +1 -1
  20. package/connections/index.js +1 -17
  21. package/drivers/DatabaseDriver.d.ts +25 -15
  22. package/drivers/DatabaseDriver.js +77 -64
  23. package/drivers/IDatabaseDriver.d.ts +40 -16
  24. package/drivers/IDatabaseDriver.js +1 -4
  25. package/drivers/index.d.ts +2 -2
  26. package/drivers/index.js +2 -18
  27. package/entity/BaseEntity.d.ts +6 -7
  28. package/entity/BaseEntity.js +16 -23
  29. package/entity/Collection.d.ts +98 -34
  30. package/entity/Collection.js +466 -131
  31. package/entity/EntityAssigner.d.ts +3 -3
  32. package/entity/EntityAssigner.js +67 -64
  33. package/entity/EntityFactory.d.ts +10 -3
  34. package/entity/EntityFactory.js +112 -91
  35. package/entity/EntityHelper.d.ts +2 -2
  36. package/entity/EntityHelper.js +66 -53
  37. package/entity/EntityIdentifier.d.ts +1 -1
  38. package/entity/EntityIdentifier.js +1 -5
  39. package/entity/EntityLoader.d.ts +8 -7
  40. package/entity/EntityLoader.js +161 -128
  41. package/entity/EntityRepository.d.ts +8 -8
  42. package/entity/EntityRepository.js +7 -11
  43. package/entity/Reference.d.ts +10 -13
  44. package/entity/Reference.js +64 -46
  45. package/entity/WrappedEntity.d.ts +12 -17
  46. package/entity/WrappedEntity.js +22 -31
  47. package/entity/defineEntity.d.ts +568 -0
  48. package/entity/defineEntity.js +529 -0
  49. package/entity/index.d.ts +14 -13
  50. package/entity/index.js +14 -29
  51. package/entity/utils.d.ts +8 -1
  52. package/entity/utils.js +22 -13
  53. package/entity/validators.d.ts +11 -0
  54. package/entity/validators.js +65 -0
  55. package/entity/wrap.d.ts +1 -1
  56. package/entity/wrap.js +2 -6
  57. package/enums.d.ts +24 -9
  58. package/enums.js +50 -41
  59. package/errors.d.ts +11 -3
  60. package/errors.js +42 -32
  61. package/events/EventManager.d.ts +5 -4
  62. package/events/EventManager.js +26 -22
  63. package/events/EventSubscriber.d.ts +8 -5
  64. package/events/EventSubscriber.js +1 -2
  65. package/events/TransactionEventBroadcaster.d.ts +3 -3
  66. package/events/TransactionEventBroadcaster.js +1 -5
  67. package/events/index.d.ts +3 -3
  68. package/events/index.js +3 -19
  69. package/exceptions.js +18 -39
  70. package/hydration/Hydrator.d.ts +5 -5
  71. package/hydration/Hydrator.js +2 -6
  72. package/hydration/ObjectHydrator.d.ts +7 -7
  73. package/hydration/ObjectHydrator.js +58 -50
  74. package/hydration/index.d.ts +2 -2
  75. package/hydration/index.js +2 -18
  76. package/index.d.ts +21 -21
  77. package/index.js +20 -46
  78. package/logging/DefaultLogger.d.ts +2 -2
  79. package/logging/DefaultLogger.js +10 -13
  80. package/logging/Logger.d.ts +1 -1
  81. package/logging/Logger.js +1 -2
  82. package/logging/SimpleLogger.d.ts +3 -3
  83. package/logging/SimpleLogger.js +2 -6
  84. package/logging/colors.js +1 -5
  85. package/logging/index.d.ts +5 -4
  86. package/logging/index.js +5 -20
  87. package/logging/inspect.d.ts +2 -0
  88. package/logging/inspect.js +16 -0
  89. package/metadata/EntitySchema.d.ts +14 -10
  90. package/metadata/EntitySchema.js +78 -64
  91. package/metadata/MetadataDiscovery.d.ts +11 -14
  92. package/metadata/MetadataDiscovery.js +278 -317
  93. package/metadata/MetadataProvider.d.ts +13 -4
  94. package/metadata/MetadataProvider.js +47 -8
  95. package/metadata/MetadataStorage.d.ts +2 -7
  96. package/metadata/MetadataStorage.js +19 -35
  97. package/metadata/MetadataValidator.d.ts +3 -10
  98. package/metadata/MetadataValidator.js +51 -64
  99. package/metadata/discover-entities.d.ts +5 -0
  100. package/metadata/discover-entities.js +40 -0
  101. package/metadata/index.d.ts +6 -6
  102. package/metadata/index.js +6 -22
  103. package/metadata/types.d.ts +480 -0
  104. package/metadata/types.js +1 -0
  105. package/naming-strategy/AbstractNamingStrategy.d.ts +7 -3
  106. package/naming-strategy/AbstractNamingStrategy.js +11 -9
  107. package/naming-strategy/EntityCaseNamingStrategy.d.ts +1 -1
  108. package/naming-strategy/EntityCaseNamingStrategy.js +2 -6
  109. package/naming-strategy/MongoNamingStrategy.d.ts +1 -1
  110. package/naming-strategy/MongoNamingStrategy.js +2 -6
  111. package/naming-strategy/NamingStrategy.d.ts +12 -2
  112. package/naming-strategy/NamingStrategy.js +1 -2
  113. package/naming-strategy/UnderscoreNamingStrategy.d.ts +1 -1
  114. package/naming-strategy/UnderscoreNamingStrategy.js +2 -6
  115. package/naming-strategy/index.d.ts +5 -5
  116. package/naming-strategy/index.js +5 -21
  117. package/not-supported.d.ts +2 -0
  118. package/not-supported.js +4 -0
  119. package/package.json +19 -20
  120. package/platforms/ExceptionConverter.d.ts +2 -2
  121. package/platforms/ExceptionConverter.js +4 -8
  122. package/platforms/Platform.d.ts +15 -22
  123. package/platforms/Platform.js +58 -88
  124. package/platforms/index.d.ts +2 -2
  125. package/platforms/index.js +2 -18
  126. package/serialization/EntitySerializer.d.ts +4 -2
  127. package/serialization/EntitySerializer.js +64 -51
  128. package/serialization/EntityTransformer.d.ts +1 -1
  129. package/serialization/EntityTransformer.js +48 -42
  130. package/serialization/SerializationContext.d.ts +2 -2
  131. package/serialization/SerializationContext.js +24 -25
  132. package/serialization/index.d.ts +3 -3
  133. package/serialization/index.js +3 -19
  134. package/types/ArrayType.d.ts +3 -3
  135. package/types/ArrayType.js +6 -11
  136. package/types/BigIntType.d.ts +12 -9
  137. package/types/BigIntType.js +6 -6
  138. package/types/BlobType.d.ts +3 -4
  139. package/types/BlobType.js +2 -11
  140. package/types/BooleanType.d.ts +5 -4
  141. package/types/BooleanType.js +5 -6
  142. package/types/CharacterType.d.ts +3 -3
  143. package/types/CharacterType.js +2 -6
  144. package/types/DateTimeType.d.ts +3 -3
  145. package/types/DateTimeType.js +2 -6
  146. package/types/DateType.d.ts +3 -3
  147. package/types/DateType.js +2 -6
  148. package/types/DecimalType.d.ts +9 -7
  149. package/types/DecimalType.js +5 -8
  150. package/types/DoubleType.d.ts +3 -3
  151. package/types/DoubleType.js +4 -7
  152. package/types/EnumArrayType.d.ts +4 -4
  153. package/types/EnumArrayType.js +4 -10
  154. package/types/EnumType.d.ts +3 -3
  155. package/types/EnumType.js +2 -6
  156. package/types/FloatType.d.ts +3 -3
  157. package/types/FloatType.js +2 -6
  158. package/types/IntegerType.d.ts +3 -3
  159. package/types/IntegerType.js +2 -6
  160. package/types/IntervalType.d.ts +3 -3
  161. package/types/IntervalType.js +2 -6
  162. package/types/JsonType.d.ts +4 -4
  163. package/types/JsonType.js +9 -8
  164. package/types/MediumIntType.d.ts +3 -3
  165. package/types/MediumIntType.js +2 -6
  166. package/types/SmallIntType.d.ts +3 -3
  167. package/types/SmallIntType.js +2 -6
  168. package/types/StringType.d.ts +3 -3
  169. package/types/StringType.js +2 -6
  170. package/types/TextType.d.ts +3 -3
  171. package/types/TextType.js +2 -6
  172. package/types/TimeType.d.ts +3 -3
  173. package/types/TimeType.js +4 -8
  174. package/types/TinyIntType.d.ts +3 -3
  175. package/types/TinyIntType.js +3 -6
  176. package/types/Type.d.ts +4 -6
  177. package/types/Type.js +6 -10
  178. package/types/Uint8ArrayType.d.ts +3 -4
  179. package/types/Uint8ArrayType.js +3 -12
  180. package/types/UnknownType.d.ts +3 -3
  181. package/types/UnknownType.js +2 -6
  182. package/types/UuidType.d.ts +3 -3
  183. package/types/UuidType.js +2 -6
  184. package/types/index.d.ts +25 -25
  185. package/types/index.js +52 -79
  186. package/typings.d.ts +134 -93
  187. package/typings.js +67 -65
  188. package/unit-of-work/ChangeSet.d.ts +1 -4
  189. package/unit-of-work/ChangeSet.js +13 -17
  190. package/unit-of-work/ChangeSetComputer.d.ts +8 -9
  191. package/unit-of-work/ChangeSetComputer.js +36 -38
  192. package/unit-of-work/ChangeSetPersister.d.ts +11 -9
  193. package/unit-of-work/ChangeSetPersister.js +100 -65
  194. package/unit-of-work/CommitOrderCalculator.d.ts +1 -1
  195. package/unit-of-work/CommitOrderCalculator.js +6 -10
  196. package/unit-of-work/IdentityMap.d.ts +1 -1
  197. package/unit-of-work/IdentityMap.js +1 -5
  198. package/unit-of-work/UnitOfWork.d.ts +16 -8
  199. package/unit-of-work/UnitOfWork.js +266 -209
  200. package/unit-of-work/index.d.ts +6 -6
  201. package/unit-of-work/index.js +6 -22
  202. package/utils/AbstractSchemaGenerator.d.ts +11 -11
  203. package/utils/AbstractSchemaGenerator.js +21 -20
  204. package/utils/Configuration.d.ts +774 -224
  205. package/utils/Configuration.js +166 -216
  206. package/utils/ConfigurationLoader.d.ts +1 -53
  207. package/utils/ConfigurationLoader.js +1 -367
  208. package/utils/Cursor.d.ts +6 -9
  209. package/utils/Cursor.js +25 -25
  210. package/utils/DataloaderUtils.d.ts +18 -8
  211. package/utils/DataloaderUtils.js +63 -21
  212. package/utils/EntityComparator.d.ts +9 -5
  213. package/utils/EntityComparator.js +155 -108
  214. package/utils/NullHighlighter.d.ts +1 -1
  215. package/utils/NullHighlighter.js +1 -5
  216. package/utils/QueryHelper.d.ts +12 -4
  217. package/utils/QueryHelper.js +110 -53
  218. package/utils/RawQueryFragment.d.ts +37 -14
  219. package/utils/RawQueryFragment.js +50 -33
  220. package/utils/RequestContext.d.ts +2 -2
  221. package/utils/RequestContext.js +3 -7
  222. package/utils/TransactionContext.d.ts +1 -1
  223. package/utils/TransactionContext.js +4 -8
  224. package/utils/TransactionManager.d.ts +65 -0
  225. package/utils/TransactionManager.js +223 -0
  226. package/utils/Utils.d.ts +16 -100
  227. package/utils/Utils.js +114 -332
  228. package/utils/clone.js +7 -11
  229. package/utils/env-vars.d.ts +3 -0
  230. package/utils/env-vars.js +87 -0
  231. package/utils/fs-utils.d.ts +12 -0
  232. package/utils/fs-utils.js +97 -0
  233. package/utils/index.d.ts +14 -13
  234. package/utils/index.js +14 -29
  235. package/utils/upsert-utils.d.ts +8 -3
  236. package/utils/upsert-utils.js +57 -10
  237. package/decorators/Check.d.ts +0 -3
  238. package/decorators/Check.js +0 -16
  239. package/decorators/CreateRequestContext.d.ts +0 -3
  240. package/decorators/CreateRequestContext.js +0 -33
  241. package/decorators/Embeddable.d.ts +0 -8
  242. package/decorators/Embeddable.js +0 -14
  243. package/decorators/Embedded.d.ts +0 -18
  244. package/decorators/Embedded.js +0 -20
  245. package/decorators/Entity.d.ts +0 -18
  246. package/decorators/Entity.js +0 -16
  247. package/decorators/Enum.d.ts +0 -9
  248. package/decorators/Enum.js +0 -19
  249. package/decorators/Filter.d.ts +0 -2
  250. package/decorators/Filter.js +0 -11
  251. package/decorators/Formula.d.ts +0 -5
  252. package/decorators/Formula.js +0 -18
  253. package/decorators/Indexed.d.ts +0 -17
  254. package/decorators/Indexed.js +0 -24
  255. package/decorators/ManyToMany.d.ts +0 -40
  256. package/decorators/ManyToMany.js +0 -16
  257. package/decorators/ManyToOne.d.ts +0 -30
  258. package/decorators/ManyToOne.js +0 -16
  259. package/decorators/OneToMany.d.ts +0 -28
  260. package/decorators/OneToMany.js +0 -20
  261. package/decorators/OneToOne.d.ts +0 -24
  262. package/decorators/OneToOne.js +0 -10
  263. package/decorators/PrimaryKey.d.ts +0 -9
  264. package/decorators/PrimaryKey.js +0 -23
  265. package/decorators/Property.d.ts +0 -250
  266. package/decorators/Property.js +0 -34
  267. package/decorators/Transactional.d.ts +0 -13
  268. package/decorators/Transactional.js +0 -31
  269. package/decorators/hooks.d.ts +0 -16
  270. package/decorators/hooks.js +0 -59
  271. package/decorators/index.d.ts +0 -17
  272. package/decorators/index.js +0 -36
  273. package/entity/ArrayCollection.d.ts +0 -116
  274. package/entity/ArrayCollection.js +0 -399
  275. package/entity/EntityValidator.d.ts +0 -19
  276. package/entity/EntityValidator.js +0 -154
  277. package/index.mjs +0 -199
  278. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  279. package/metadata/ReflectMetadataProvider.js +0 -48
  280. package/utils/resolveContextProvider.d.ts +0 -10
  281. package/utils/resolveContextProvider.js +0 -31
@@ -1,367 +1 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ConfigurationLoader = void 0;
7
- const dotenv_1 = __importDefault(require("dotenv"));
8
- const fs_extra_1 = require("fs-extra");
9
- const node_os_1 = require("node:os");
10
- const node_path_1 = require("node:path");
11
- const node_url_1 = require("node:url");
12
- const colors_1 = require("../logging/colors");
13
- const Configuration_1 = require("./Configuration");
14
- const Utils_1 = require("./Utils");
15
- /**
16
- * @internal
17
- */
18
- class ConfigurationLoader {
19
- static async getConfiguration(contextName = 'default', paths = ConfigurationLoader.getConfigPaths(), options = {}) {
20
- // Backwards compatibility layer
21
- if (typeof contextName === 'boolean' || !Array.isArray(paths)) {
22
- this.commonJSCompat(options);
23
- this.registerDotenv(options);
24
- const configPathFromArg = ConfigurationLoader.configPathsFromArg();
25
- const configPaths = configPathFromArg ?? (Array.isArray(paths) ? paths : ConfigurationLoader.getConfigPaths());
26
- const config = contextName
27
- ? (await ConfigurationLoader.getConfiguration(process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default', configPaths, Array.isArray(paths) ? {} : paths))
28
- : await (async () => {
29
- const env = this.loadEnvironmentVars();
30
- const [path, tmp] = await this.getConfigFile(configPaths);
31
- if (!path) {
32
- if (Utils_1.Utils.hasObjectKeys(env)) {
33
- return new Configuration_1.Configuration(Utils_1.Utils.mergeConfig({}, options, env), false);
34
- }
35
- throw new Error(`MikroORM config file not found in ['${configPaths.join(`', '`)}']`);
36
- }
37
- return new Configuration_1.Configuration(Utils_1.Utils.mergeConfig(tmp, options, env), false);
38
- })();
39
- if (configPathFromArg) {
40
- config.getLogger().warn('deprecated', 'Path for config file was inferred from the command line arguments. Instead, you should set the MIKRO_ORM_CLI_CONFIG environment variable to specify the path, or if you really must use the command line arguments, import the config manually based on them, and pass it to init.', { label: 'D0001' });
41
- }
42
- return config;
43
- }
44
- const env = this.loadEnvironmentVars();
45
- const configFinder = (cfg) => {
46
- return typeof cfg === 'object' && cfg !== null && ('contextName' in cfg ? cfg.contextName === contextName : (contextName === 'default'));
47
- };
48
- const isValidConfigFactoryResult = (cfg) => {
49
- return typeof cfg === 'object' && cfg !== null && (!('contextName' in cfg) || cfg.contextName === contextName);
50
- };
51
- const result = await this.getConfigFile(paths);
52
- if (!result[0]) {
53
- if (Utils_1.Utils.hasObjectKeys(env)) {
54
- return new Configuration_1.Configuration(Utils_1.Utils.mergeConfig({ contextName }, options, env));
55
- }
56
- throw new Error(`MikroORM config file not found in ['${paths.join(`', '`)}']`);
57
- }
58
- const path = result[0];
59
- let tmp = result[1];
60
- if (Array.isArray(tmp)) {
61
- const tmpFirstIndex = tmp.findIndex(configFinder);
62
- if (tmpFirstIndex === -1) {
63
- // Static config not found. Try factory functions
64
- let configCandidate;
65
- for (let i = 0, l = tmp.length; i < l; ++i) {
66
- const f = tmp[i];
67
- if (typeof f !== 'function') {
68
- continue;
69
- }
70
- configCandidate = await f(contextName);
71
- if (!isValidConfigFactoryResult(configCandidate)) {
72
- continue;
73
- }
74
- tmp = configCandidate;
75
- break;
76
- }
77
- if (Array.isArray(tmp)) {
78
- throw new Error(`MikroORM config '${contextName}' was not found within the config file '${path}'. Either add a config with this name to the array, or add a function that when given this name will return a configuration object without a name, or with name set to this name.`);
79
- }
80
- }
81
- else {
82
- const tmpLastIndex = tmp.findLastIndex(configFinder);
83
- if (tmpLastIndex !== tmpFirstIndex) {
84
- throw new Error(`MikroORM config '${contextName}' is not unique within the array exported by '${path}' (first occurrence index: ${tmpFirstIndex}; last occurrence index: ${tmpLastIndex})`);
85
- }
86
- tmp = tmp[tmpFirstIndex];
87
- }
88
- }
89
- else {
90
- if (tmp instanceof Function) {
91
- tmp = await tmp(contextName);
92
- if (!isValidConfigFactoryResult(tmp)) {
93
- throw new Error(`MikroORM config '${contextName}' was not what the function exported from '${path}' provided. Ensure it returns a config object with no name, or name matching the requested one.`);
94
- }
95
- }
96
- else {
97
- if (!configFinder(tmp)) {
98
- throw new Error(`MikroORM config '${contextName}' was not what the default export from '${path}' provided.`);
99
- }
100
- }
101
- }
102
- const esmConfigOptions = this.isESM() ? { entityGenerator: { esmImport: true } } : {};
103
- return new Configuration_1.Configuration(Utils_1.Utils.mergeConfig({}, esmConfigOptions, tmp, options, env));
104
- }
105
- static async getConfigFile(paths) {
106
- for (let path of paths) {
107
- path = Utils_1.Utils.absolutePath(path);
108
- path = Utils_1.Utils.normalizePath(path);
109
- if ((0, fs_extra_1.pathExistsSync)(path)) {
110
- const config = await Utils_1.Utils.dynamicImport(path);
111
- /* istanbul ignore next */
112
- return [path, await (config.default ?? config)];
113
- }
114
- }
115
- return [];
116
- }
117
- static getPackageConfig(basePath = process.cwd()) {
118
- if ((0, fs_extra_1.pathExistsSync)(`${basePath}/package.json`)) {
119
- /* istanbul ignore next */
120
- try {
121
- return (0, fs_extra_1.readJSONSync)(`${basePath}/package.json`);
122
- }
123
- catch {
124
- return {};
125
- }
126
- }
127
- const parentFolder = (0, fs_extra_1.realpathSync)(`${basePath}/..`);
128
- // we reached the root folder
129
- if (basePath === parentFolder) {
130
- return {};
131
- }
132
- return this.getPackageConfig(parentFolder);
133
- }
134
- static getSettings() {
135
- const config = ConfigurationLoader.getPackageConfig();
136
- const settings = { ...config['mikro-orm'] };
137
- const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
138
- settings.useTsNode = process.env.MIKRO_ORM_CLI_USE_TS_NODE != null ? bool(process.env.MIKRO_ORM_CLI_USE_TS_NODE) : settings.useTsNode;
139
- settings.tsConfigPath = process.env.MIKRO_ORM_CLI_TS_CONFIG_PATH ?? settings.tsConfigPath;
140
- settings.alwaysAllowTs = process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS != null ? bool(process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS) : settings.alwaysAllowTs;
141
- settings.verbose = process.env.MIKRO_ORM_CLI_VERBOSE != null ? bool(process.env.MIKRO_ORM_CLI_VERBOSE) : settings.verbose;
142
- if (process.env.MIKRO_ORM_CLI_CONFIG?.endsWith('.ts')) {
143
- settings.useTsNode = true;
144
- }
145
- return settings;
146
- }
147
- static configPathsFromArg() {
148
- const options = Utils_1.Utils.parseArgs();
149
- const configArgName = process.env.MIKRO_ORM_CONFIG_ARG_NAME ?? 'config';
150
- if (options[configArgName]) {
151
- return [options[configArgName]];
152
- }
153
- return undefined;
154
- }
155
- static getConfigPaths() {
156
- const paths = [];
157
- const settings = ConfigurationLoader.getSettings();
158
- if (process.env.MIKRO_ORM_CLI_CONFIG) {
159
- paths.push(process.env.MIKRO_ORM_CLI_CONFIG);
160
- }
161
- paths.push(...(settings.configPaths || []));
162
- const alwaysAllowTs = settings.alwaysAllowTs ?? process.versions.bun;
163
- if (settings.useTsNode !== false || alwaysAllowTs) {
164
- paths.push('./src/mikro-orm.config.ts');
165
- paths.push('./mikro-orm.config.ts');
166
- }
167
- const distDir = (0, fs_extra_1.pathExistsSync)(process.cwd() + '/dist');
168
- const buildDir = (0, fs_extra_1.pathExistsSync)(process.cwd() + '/build');
169
- /* istanbul ignore next */
170
- const path = distDir ? 'dist' : (buildDir ? 'build' : 'src');
171
- paths.push(`./${path}/mikro-orm.config.js`);
172
- paths.push('./mikro-orm.config.js');
173
- const tsNode = Utils_1.Utils.detectTsNode();
174
- return Utils_1.Utils.unique(paths).filter(p => p.endsWith('.js') || tsNode || alwaysAllowTs);
175
- }
176
- static isESM() {
177
- const config = ConfigurationLoader.getPackageConfig();
178
- const type = config?.type ?? '';
179
- return type === 'module';
180
- }
181
- static registerTsNode(configPath = 'tsconfig.json') {
182
- /* istanbul ignore next */
183
- if (process.versions.bun) {
184
- return true;
185
- }
186
- const tsConfigPath = (0, node_path_1.isAbsolute)(configPath) ? configPath : (0, node_path_1.join)(process.cwd(), configPath);
187
- const tsNode = Utils_1.Utils.tryRequire({
188
- module: 'ts-node',
189
- from: tsConfigPath,
190
- warning: 'ts-node not installed, support for working with TS files might not work',
191
- });
192
- /* istanbul ignore next */
193
- if (!tsNode) {
194
- return false;
195
- }
196
- const { options } = tsNode.register({
197
- project: tsConfigPath,
198
- transpileOnly: true,
199
- compilerOptions: {
200
- module: 'nodenext',
201
- moduleResolution: 'nodenext',
202
- },
203
- }).config;
204
- if (Object.entries(options?.paths ?? {}).length > 0) {
205
- Utils_1.Utils.requireFrom('tsconfig-paths', tsConfigPath).register({
206
- baseUrl: options.baseUrl ?? '.',
207
- paths: options.paths,
208
- });
209
- }
210
- return true;
211
- }
212
- static registerDotenv(options) {
213
- const baseDir = options instanceof Configuration_1.Configuration ? options.get('baseDir') : options?.baseDir;
214
- const path = process.env.MIKRO_ORM_ENV ?? ((baseDir ?? process.cwd()) + '/.env');
215
- const env = {};
216
- dotenv_1.default.config({ path, processEnv: env });
217
- // only propagate known env vars
218
- for (const key of Object.keys(env)) {
219
- if (key.startsWith('MIKRO_ORM_')) {
220
- process.env[key] ??= env[key]; // respect user provided values
221
- }
222
- }
223
- }
224
- static loadEnvironmentVars() {
225
- const ret = {};
226
- // only to keep some sort of back compatibility with those using env vars only, to support `MIKRO_ORM_TYPE`
227
- const PLATFORMS = {
228
- mongo: { className: 'MongoDriver', module: '@mikro-orm/mongodb' },
229
- mysql: { className: 'MySqlDriver', module: '@mikro-orm/mysql' },
230
- mssql: { className: 'MsSqlDriver', module: '@mikro-orm/mssql' },
231
- mariadb: { className: 'MariaDbDriver', module: '@mikro-orm/mariadb' },
232
- postgresql: { className: 'PostgreSqlDriver', module: '@mikro-orm/postgresql' },
233
- sqlite: { className: 'SqliteDriver', module: '@mikro-orm/sqlite' },
234
- libsql: { className: 'LibSqlDriver', module: '@mikro-orm/libsql' },
235
- };
236
- const array = (v) => v.split(',').map(vv => vv.trim());
237
- const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
238
- const num = (v) => +v;
239
- const driver = (v) => Utils_1.Utils.requireFrom(PLATFORMS[v].module)[PLATFORMS[v].className];
240
- const read = (o, envKey, key, mapper = v => v) => {
241
- if (!(envKey in process.env)) {
242
- return;
243
- }
244
- const val = process.env[envKey];
245
- o[key] = mapper(val);
246
- };
247
- const cleanup = (o, k) => Utils_1.Utils.hasObjectKeys(o[k]) ? {} : delete o[k];
248
- read(ret, 'MIKRO_ORM_BASE_DIR', 'baseDir');
249
- read(ret, 'MIKRO_ORM_TYPE', 'driver', driver);
250
- read(ret, 'MIKRO_ORM_ENTITIES', 'entities', array);
251
- read(ret, 'MIKRO_ORM_ENTITIES_TS', 'entitiesTs', array);
252
- read(ret, 'MIKRO_ORM_CLIENT_URL', 'clientUrl');
253
- read(ret, 'MIKRO_ORM_HOST', 'host');
254
- read(ret, 'MIKRO_ORM_PORT', 'port', num);
255
- read(ret, 'MIKRO_ORM_USER', 'user');
256
- read(ret, 'MIKRO_ORM_PASSWORD', 'password');
257
- read(ret, 'MIKRO_ORM_DB_NAME', 'dbName');
258
- read(ret, 'MIKRO_ORM_SCHEMA', 'schema');
259
- read(ret, 'MIKRO_ORM_LOAD_STRATEGY', 'loadStrategy');
260
- read(ret, 'MIKRO_ORM_BATCH_SIZE', 'batchSize', num);
261
- read(ret, 'MIKRO_ORM_USE_BATCH_INSERTS', 'useBatchInserts', bool);
262
- read(ret, 'MIKRO_ORM_USE_BATCH_UPDATES', 'useBatchUpdates', bool);
263
- read(ret, 'MIKRO_ORM_STRICT', 'strict', bool);
264
- read(ret, 'MIKRO_ORM_VALIDATE', 'validate', bool);
265
- read(ret, 'MIKRO_ORM_ALLOW_GLOBAL_CONTEXT', 'allowGlobalContext', bool);
266
- read(ret, 'MIKRO_ORM_AUTO_JOIN_ONE_TO_ONE_OWNER', 'autoJoinOneToOneOwner', bool);
267
- read(ret, 'MIKRO_ORM_POPULATE_AFTER_FLUSH', 'populateAfterFlush', bool);
268
- read(ret, 'MIKRO_ORM_FORCE_ENTITY_CONSTRUCTOR', 'forceEntityConstructor', bool);
269
- read(ret, 'MIKRO_ORM_FORCE_UNDEFINED', 'forceUndefined', bool);
270
- read(ret, 'MIKRO_ORM_FORCE_UTC_TIMEZONE', 'forceUtcTimezone', bool);
271
- read(ret, 'MIKRO_ORM_TIMEZONE', 'timezone');
272
- read(ret, 'MIKRO_ORM_ENSURE_INDEXES', 'ensureIndexes', bool);
273
- read(ret, 'MIKRO_ORM_IMPLICIT_TRANSACTIONS', 'implicitTransactions', bool);
274
- read(ret, 'MIKRO_ORM_DEBUG', 'debug', bool);
275
- read(ret, 'MIKRO_ORM_COLORS', 'colors', bool);
276
- ret.discovery = {};
277
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_WARN_WHEN_NO_ENTITIES', 'warnWhenNoEntities', bool);
278
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_REQUIRE_ENTITIES_ARRAY', 'requireEntitiesArray', bool);
279
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_ALWAYS_ANALYSE_PROPERTIES', 'alwaysAnalyseProperties', bool);
280
- read(ret.discovery, 'MIKRO_ORM_DISCOVERY_DISABLE_DYNAMIC_FILE_ACCESS', 'disableDynamicFileAccess', bool);
281
- cleanup(ret, 'discovery');
282
- ret.migrations = {};
283
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_TABLE_NAME', 'tableName');
284
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_PATH', 'path');
285
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_PATH_TS', 'pathTs');
286
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_GLOB', 'glob');
287
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_TRANSACTIONAL', 'transactional', bool);
288
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_DISABLE_FOREIGN_KEYS', 'disableForeignKeys', bool);
289
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_ALL_OR_NOTHING', 'allOrNothing', bool);
290
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_DROP_TABLES', 'dropTables', bool);
291
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_SAFE', 'safe', bool);
292
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_SILENT', 'silent', bool);
293
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_EMIT', 'emit');
294
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_SNAPSHOT', 'snapshot', bool);
295
- read(ret.migrations, 'MIKRO_ORM_MIGRATIONS_SNAPSHOT_NAME', 'snapshotName');
296
- cleanup(ret, 'migrations');
297
- ret.schemaGenerator = {};
298
- read(ret.schemaGenerator, 'MIKRO_ORM_SCHEMA_GENERATOR_DISABLE_FOREIGN_KEYS', 'disableForeignKeys', bool);
299
- read(ret.schemaGenerator, 'MIKRO_ORM_SCHEMA_GENERATOR_CREATE_FOREIGN_KEY_CONSTRAINTS', 'createForeignKeyConstraints', bool);
300
- cleanup(ret, 'schemaGenerator');
301
- ret.seeder = {};
302
- read(ret.seeder, 'MIKRO_ORM_SEEDER_PATH', 'path');
303
- read(ret.seeder, 'MIKRO_ORM_SEEDER_PATH_TS', 'pathTs');
304
- read(ret.seeder, 'MIKRO_ORM_SEEDER_GLOB', 'glob');
305
- read(ret.seeder, 'MIKRO_ORM_SEEDER_EMIT', 'emit');
306
- read(ret.seeder, 'MIKRO_ORM_SEEDER_DEFAULT_SEEDER', 'defaultSeeder');
307
- cleanup(ret, 'seeder');
308
- return ret;
309
- }
310
- static getORMPackages() {
311
- const pkg = this.getPackageConfig();
312
- return new Set([
313
- ...Object.keys(pkg.dependencies ?? {}),
314
- ...Object.keys(pkg.devDependencies ?? {}),
315
- ]);
316
- }
317
- /** @internal */
318
- static commonJSCompat(options) {
319
- if (this.isESM()) {
320
- return;
321
- }
322
- /* istanbul ignore next */
323
- options.dynamicImportProvider ??= id => {
324
- if ((0, node_os_1.platform)() === 'win32') {
325
- try {
326
- id = (0, node_url_1.fileURLToPath)(id);
327
- }
328
- catch {
329
- // ignore
330
- }
331
- }
332
- return Utils_1.Utils.requireFrom(id);
333
- };
334
- Utils_1.Utils.setDynamicImportProvider(options.dynamicImportProvider);
335
- }
336
- static getORMPackageVersion(name) {
337
- /* istanbul ignore next */
338
- try {
339
- const pkg = Utils_1.Utils.requireFrom(`${name}/package.json`);
340
- return pkg?.version;
341
- }
342
- catch (e) {
343
- return undefined;
344
- }
345
- }
346
- // inspired by https://github.com/facebook/docusaurus/pull/3386
347
- static checkPackageVersion() {
348
- const coreVersion = Utils_1.Utils.getORMVersion();
349
- if (process.env.MIKRO_ORM_ALLOW_VERSION_MISMATCH) {
350
- return coreVersion;
351
- }
352
- const deps = this.getORMPackages();
353
- const exceptions = new Set(['nestjs', 'sql-highlighter', 'mongo-highlighter']);
354
- const ormPackages = [...deps].filter(d => d.startsWith('@mikro-orm/') && d !== '@mikro-orm/core' && !exceptions.has(d.substring('@mikro-orm/'.length)));
355
- for (const ormPackage of ormPackages) {
356
- const version = this.getORMPackageVersion(ormPackage);
357
- if (version != null && version !== coreVersion) {
358
- throw new Error(`Bad ${colors_1.colors.cyan(ormPackage)} version ${colors_1.colors.yellow('' + version)}.\n` +
359
- `All official @mikro-orm/* packages need to have the exact same version as @mikro-orm/core (${colors_1.colors.green(coreVersion)}).\n` +
360
- `Only exceptions are packages that don't live in the 'mikro-orm' repository: ${[...exceptions].join(', ')}.\n` +
361
- `Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?`);
362
- }
363
- }
364
- return coreVersion;
365
- }
366
- }
367
- exports.ConfigurationLoader = ConfigurationLoader;
1
+ export {};
package/utils/Cursor.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { inspect } from 'node:util';
2
- import type { EntityMetadata, FilterObject, Loaded } from '../typings';
3
- import type { FindByCursorOptions, OrderDefinition } from '../drivers/IDatabaseDriver';
4
- import { type QueryOrder } from '../enums';
1
+ import type { EntityMetadata, FilterObject, Loaded } from '../typings.js';
2
+ import type { FindByCursorOptions, OrderDefinition } from '../drivers/IDatabaseDriver.js';
3
+ import { type QueryOrder } from '../enums.js';
5
4
  /**
6
5
  * As an alternative to the offset-based pagination with `limit` and `offset`, we can paginate based on a cursor.
7
6
  * A cursor is an opaque string that defines a specific place in ordered entity graph. You can use `em.findByCursor()`
@@ -49,13 +48,13 @@ import { type QueryOrder } from '../enums';
49
48
  * }
50
49
  * ```
51
50
  */
52
- export declare class Cursor<Entity extends object, Hint extends string = never, Fields extends string = '*', Excludes extends string = never> {
51
+ export declare class Cursor<Entity extends object, Hint extends string = never, Fields extends string = '*', Excludes extends string = never, IncludeCount extends boolean = true> {
53
52
  readonly items: Loaded<Entity, Hint, Fields, Excludes>[];
54
- readonly totalCount: number;
53
+ readonly totalCount: IncludeCount extends true ? number : undefined;
55
54
  readonly hasPrevPage: boolean;
56
55
  readonly hasNextPage: boolean;
57
56
  private readonly definition;
58
- constructor(items: Loaded<Entity, Hint, Fields, Excludes>[], totalCount: number, options: FindByCursorOptions<Entity, Hint, Fields, Excludes>, meta: EntityMetadata<Entity>);
57
+ constructor(items: Loaded<Entity, Hint, Fields, Excludes>[], totalCount: IncludeCount extends true ? number : undefined, options: FindByCursorOptions<Entity, Hint, Fields, Excludes, IncludeCount>, meta: EntityMetadata<Entity>);
59
58
  get startCursor(): string | null;
60
59
  get endCursor(): string | null;
61
60
  /**
@@ -71,6 +70,4 @@ export declare class Cursor<Entity extends object, Hint extends string = never,
71
70
  static encode(value: unknown[]): string;
72
71
  static decode(value: string): unknown[];
73
72
  static getDefinition<Entity extends object>(meta: EntityMetadata<Entity>, orderBy: OrderDefinition<Entity>): [never, QueryOrder][];
74
- /** @ignore */
75
- [inspect.custom](): string;
76
73
  }
package/utils/Cursor.js CHANGED
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Cursor = void 0;
4
- const node_util_1 = require("node:util");
5
- const Utils_1 = require("./Utils");
6
- const enums_1 = require("../enums");
7
- const Reference_1 = require("../entity/Reference");
8
- const wrap_1 = require("../entity/wrap");
9
- const RawQueryFragment_1 = require("../utils/RawQueryFragment");
10
- const errors_1 = require("../errors");
1
+ import { Utils } from './Utils.js';
2
+ import { ReferenceKind } from '../enums.js';
3
+ import { Reference } from '../entity/Reference.js';
4
+ import { helper } from '../entity/wrap.js';
5
+ import { RawQueryFragment } from '../utils/RawQueryFragment.js';
6
+ import { CursorError } from '../errors.js';
7
+ import { inspect } from '../logging/inspect.js';
11
8
  /**
12
9
  * As an alternative to the offset-based pagination with `limit` and `offset`, we can paginate based on a cursor.
13
10
  * A cursor is an opaque string that defines a specific place in ordered entity graph. You can use `em.findByCursor()`
@@ -55,7 +52,7 @@ const errors_1 = require("../errors");
55
52
  * }
56
53
  * ```
57
54
  */
58
- class Cursor {
55
+ export class Cursor {
59
56
  items;
60
57
  totalCount;
61
58
  hasPrevPage;
@@ -97,18 +94,21 @@ class Cursor {
97
94
  */
98
95
  from(entity) {
99
96
  const processEntity = (entity, prop, direction, object = false) => {
100
- if (Utils_1.Utils.isPlainObject(direction)) {
101
- return Utils_1.Utils.keys(direction).reduce((o, key) => {
102
- Object.assign(o, processEntity(Reference_1.Reference.unwrapReference(entity[prop]), key, direction[key], true));
97
+ if (Utils.isPlainObject(direction)) {
98
+ return Utils.keys(direction).reduce((o, key) => {
99
+ Object.assign(o, processEntity(Reference.unwrapReference(entity[prop]), key, direction[key], true));
103
100
  return o;
104
101
  }, {});
105
102
  }
106
103
  if (entity[prop] == null) {
107
- throw errors_1.CursorError.entityNotPopulated(entity, prop);
104
+ throw CursorError.entityNotPopulated(entity, prop);
108
105
  }
109
106
  let value = entity[prop];
110
- if (Utils_1.Utils.isEntity(value, true)) {
111
- value = (0, wrap_1.helper)(value).getPrimaryKey();
107
+ if (Utils.isEntity(value, true)) {
108
+ value = helper(value).getPrimaryKey();
109
+ }
110
+ if (Utils.isScalarReference(value)) {
111
+ value = value.unwrap();
112
112
  }
113
113
  if (object) {
114
114
  return ({ [prop]: value });
@@ -145,15 +145,16 @@ class Cursor {
145
145
  });
146
146
  }
147
147
  static getDefinition(meta, orderBy) {
148
- return Utils_1.Utils.asArray(orderBy).flatMap(order => {
148
+ return Utils.asArray(orderBy).flatMap(order => {
149
149
  const ret = [];
150
- for (const key of Utils_1.Utils.keys(order)) {
151
- if (RawQueryFragment_1.RawQueryFragment.isKnownFragment(key)) {
150
+ for (const key of Utils.keys(order)) {
151
+ if (RawQueryFragment.isKnownFragment(key)) {
152
152
  ret.push([key, order[key]]);
153
153
  continue;
154
154
  }
155
155
  const prop = meta.properties[key];
156
- if (!prop || !([enums_1.ReferenceKind.SCALAR, enums_1.ReferenceKind.EMBEDDED, enums_1.ReferenceKind.MANY_TO_ONE].includes(prop.kind) || (prop.kind === enums_1.ReferenceKind.ONE_TO_ONE && prop.owner))) {
156
+ /* v8 ignore next */
157
+ if (!prop || !([ReferenceKind.SCALAR, ReferenceKind.EMBEDDED, ReferenceKind.MANY_TO_ONE].includes(prop.kind) || (prop.kind === ReferenceKind.ONE_TO_ONE && prop.owner))) {
157
158
  continue;
158
159
  }
159
160
  ret.push([prop.name, order[prop.name]]);
@@ -161,13 +162,12 @@ class Cursor {
161
162
  return ret;
162
163
  });
163
164
  }
164
- /* istanbul ignore next */
165
165
  /** @ignore */
166
- [node_util_1.inspect.custom]() {
166
+ /* v8 ignore next */
167
+ [Symbol.for('nodejs.util.inspect.custom')]() {
167
168
  const type = this.items[0]?.constructor.name;
168
169
  const { items, startCursor, endCursor, hasPrevPage, hasNextPage, totalCount, length } = this;
169
- const options = (0, node_util_1.inspect)({ startCursor, endCursor, totalCount, hasPrevPage, hasNextPage, items, length }, { depth: 0 });
170
+ const options = inspect({ startCursor, endCursor, totalCount, hasPrevPage, hasNextPage, items, length }, { depth: 0 });
170
171
  return `Cursor${type ? `<${type}>` : ''} ${options.replace('items: [Array]', 'items: [...]')}`;
171
172
  }
172
173
  }
173
- exports.Cursor = Cursor;
@@ -1,9 +1,10 @@
1
- import type { Primary, Ref } from '../typings';
2
- import { Collection, type InitCollectionOptions } from '../entity/Collection';
3
- import { type EntityManager } from '../EntityManager';
4
- import type DataLoader from 'dataloader';
5
- import { type LoadReferenceOptions } from '../entity/Reference';
1
+ import type { Constructor, Primary, Ref } from '../typings.js';
2
+ import { Collection, type InitCollectionOptions } from '../entity/Collection.js';
3
+ import { type EntityManager } from '../EntityManager.js';
4
+ import { type LoadReferenceOptions } from '../entity/Reference.js';
5
+ type BatchLoadFn<K, V> = (keys: readonly K[]) => PromiseLike<ArrayLike<V | Error>>;
6
6
  export declare class DataloaderUtils {
7
+ private static DataLoader?;
7
8
  /**
8
9
  * Groups identified references by entity and returns a Map with the
9
10
  * class name as the index and the corresponding primary keys as the value.
@@ -13,7 +14,7 @@ export declare class DataloaderUtils {
13
14
  * Returns the reference dataloader batchLoadFn, which aggregates references by entity,
14
15
  * makes one query per entity and maps each input reference to the corresponding result.
15
16
  */
16
- static getRefBatchLoadFn(em: EntityManager): DataLoader.BatchLoadFn<[Ref<any>, Omit<LoadReferenceOptions<any, any>, 'dataloader'>?], any>;
17
+ static getRefBatchLoadFn(em: EntityManager): BatchLoadFn<[Ref<any>, Omit<LoadReferenceOptions<any, any>, 'dataloader'>?], any>;
17
18
  /**
18
19
  * Groups collections by entity and returns a Map whose keys are the entity names and whose values are filter Maps
19
20
  * which we can use to narrow down the find query to return just the items of the collections that have been dataloaded.
@@ -34,8 +35,17 @@ export declare class DataloaderUtils {
34
35
  */
35
36
  static getColFilter<T, S extends T>(collection: Collection<any>): (result: T) => result is S;
36
37
  /**
37
- * Returns the collection dataloader batchLoadFn, which aggregates collections by entity,
38
+ * Returns the 1:M collection dataloader batchLoadFn, which aggregates collections by entity,
38
39
  * makes one query per entity and maps each input collection to the corresponding result.
39
40
  */
40
- static getColBatchLoadFn(em: EntityManager): DataLoader.BatchLoadFn<[Collection<any>, Omit<InitCollectionOptions<any, any>, 'dataloader'>?], any>;
41
+ static getColBatchLoadFn(em: EntityManager): BatchLoadFn<[Collection<any>, Omit<InitCollectionOptions<any, any>, 'dataloader'>?], any>;
42
+ /**
43
+ * Returns the M:N collection dataloader batchLoadFn, which aggregates collections by entity,
44
+ * makes one query per entity and maps each input collection to the corresponding result.
45
+ */
46
+ static getManyToManyColBatchLoadFn(em: EntityManager): BatchLoadFn<[Collection<any>, Omit<InitCollectionOptions<any, any>, 'dataloader'>?], any>;
47
+ static getDataLoader(): Promise<Constructor<{
48
+ load: (...args: unknown[]) => Promise<unknown>;
49
+ }>>;
41
50
  }
51
+ export {};