@mikro-orm/cli 7.0.3-dev.8 → 7.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLIHelper.js CHANGED
@@ -2,346 +2,357 @@ import { extname, join } from 'node:path';
2
2
  import { createRequire } from 'node:module';
3
3
  import { fileURLToPath, pathToFileURL } from 'node:url';
4
4
  import yargs from 'yargs';
5
- import { colors, Configuration, loadEnvironmentVars, loadOptionalDependencies, MikroORM, Utils, } from '@mikro-orm/core';
5
+ import { colors, Configuration, loadEnvironmentVars, loadOptionalDependencies, MikroORM, Utils } from '@mikro-orm/core';
6
6
  import { fs } from '@mikro-orm/core/fs-utils';
7
7
  /**
8
8
  * @internal
9
9
  */
10
10
  export class CLIHelper {
11
- /**
12
- * Gets a named configuration
13
- *
14
- * @param contextName Load a config with the given `contextName` value. Used when config file exports array or factory function. Setting it to "default" matches also config objects without `contextName` set.
15
- * @param paths Array of possible paths for a configuration file. Files will be checked in order, and the first existing one will be used. Defaults to the output of {@link fs.getConfigPaths}.
16
- * @param options Additional options to augment the final configuration with.
17
- */
18
- static async getConfiguration(contextName, paths, options = {}) {
19
- this.commonJSCompat(options);
20
- paths ??= await this.getConfigPaths();
21
- const deps = fs.getORMPackages();
22
- if (!deps.has('@mikro-orm/cli') && !process.env.MIKRO_ORM_ALLOW_GLOBAL_CLI) {
23
- throw new Error('@mikro-orm/cli needs to be installed as a local dependency!');
24
- }
25
- contextName ??= process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default';
26
- const env = await this.loadEnvironmentVars();
27
- await loadOptionalDependencies(options);
28
- // oxfmt-ignore
29
- const configFinder = (cfg) => {
11
+ /**
12
+ * Gets a named configuration
13
+ *
14
+ * @param contextName Load a config with the given `contextName` value. Used when config file exports array or factory function. Setting it to "default" matches also config objects without `contextName` set.
15
+ * @param paths Array of possible paths for a configuration file. Files will be checked in order, and the first existing one will be used. Defaults to the output of {@link fs.getConfigPaths}.
16
+ * @param options Additional options to augment the final configuration with.
17
+ */
18
+ static async getConfiguration(contextName, paths, options = {}) {
19
+ this.commonJSCompat(options);
20
+ paths ??= await this.getConfigPaths();
21
+ const deps = fs.getORMPackages();
22
+ if (!deps.has('@mikro-orm/cli') && !process.env.MIKRO_ORM_ALLOW_GLOBAL_CLI) {
23
+ throw new Error('@mikro-orm/cli needs to be installed as a local dependency!');
24
+ }
25
+ contextName ??= process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default';
26
+ const env = await this.loadEnvironmentVars();
27
+ await loadOptionalDependencies(options);
28
+ // oxfmt-ignore
29
+ const configFinder = (cfg) => {
30
30
  return typeof cfg === 'object' && cfg !== null && ('contextName' in cfg ? cfg.contextName === contextName : contextName === 'default');
31
31
  };
32
- const isValidConfigFactoryResult = (cfg) => {
33
- return typeof cfg === 'object' && cfg !== null && (!('contextName' in cfg) || cfg.contextName === contextName);
34
- };
35
- const result = await this.getConfigFile(paths);
36
- if (!result[0]) {
37
- if (Utils.hasObjectKeys(env)) {
38
- return new Configuration(Utils.mergeConfig({ contextName }, options.preferEnvVars ? options : env, options.preferEnvVars ? env : options));
39
- }
40
- throw new Error(`MikroORM config file not found in ['${paths.join(`', '`)}']`);
32
+ const isValidConfigFactoryResult = cfg => {
33
+ return typeof cfg === 'object' && cfg !== null && (!('contextName' in cfg) || cfg.contextName === contextName);
34
+ };
35
+ const result = await this.getConfigFile(paths);
36
+ if (!result[0]) {
37
+ if (Utils.hasObjectKeys(env)) {
38
+ return new Configuration(
39
+ Utils.mergeConfig(
40
+ { contextName },
41
+ options.preferEnvVars ? options : env,
42
+ options.preferEnvVars ? env : options,
43
+ ),
44
+ );
45
+ }
46
+ throw new Error(`MikroORM config file not found in ['${paths.join(`', '`)}']`);
47
+ }
48
+ const path = result[0];
49
+ let tmp = result[1];
50
+ if (Array.isArray(tmp)) {
51
+ const tmpFirstIndex = tmp.findIndex(configFinder);
52
+ if (tmpFirstIndex === -1) {
53
+ // Static config not found. Try factory functions
54
+ let configCandidate;
55
+ for (let i = 0, l = tmp.length; i < l; ++i) {
56
+ const f = tmp[i];
57
+ if (typeof f !== 'function') {
58
+ continue;
59
+ }
60
+ configCandidate = await f(contextName);
61
+ if (!isValidConfigFactoryResult(configCandidate)) {
62
+ continue;
63
+ }
64
+ tmp = configCandidate;
65
+ break;
41
66
  }
42
- const path = result[0];
43
- let tmp = result[1];
44
67
  if (Array.isArray(tmp)) {
45
- const tmpFirstIndex = tmp.findIndex(configFinder);
46
- if (tmpFirstIndex === -1) {
47
- // Static config not found. Try factory functions
48
- let configCandidate;
49
- for (let i = 0, l = tmp.length; i < l; ++i) {
50
- const f = tmp[i];
51
- if (typeof f !== 'function') {
52
- continue;
53
- }
54
- configCandidate = await f(contextName);
55
- if (!isValidConfigFactoryResult(configCandidate)) {
56
- continue;
57
- }
58
- tmp = configCandidate;
59
- break;
60
- }
61
- if (Array.isArray(tmp)) {
62
- 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.`);
63
- }
64
- }
65
- else {
66
- const tmpLastIndex = tmp.findLastIndex(configFinder);
67
- if (tmpLastIndex !== tmpFirstIndex) {
68
- throw new Error(`MikroORM config '${contextName}' is not unique within the array exported by '${path}' (first occurrence index: ${tmpFirstIndex}; last occurrence index: ${tmpLastIndex})`);
69
- }
70
- tmp = tmp[tmpFirstIndex];
71
- }
72
- }
73
- else {
74
- if (tmp instanceof Function) {
75
- tmp = await tmp(contextName);
76
- if (!isValidConfigFactoryResult(tmp)) {
77
- 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.`);
78
- }
79
- }
80
- else {
81
- if (!configFinder(tmp)) {
82
- throw new Error(`MikroORM config '${contextName}' was not what the default export from '${path}' provided.`);
83
- }
84
- }
68
+ throw new Error(
69
+ `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.`,
70
+ );
85
71
  }
86
- const esmConfigOptions = this.isESM() ? { entityGenerator: { esmImport: true } } : {};
87
- await loadOptionalDependencies(tmp);
88
- const preferEnvVars = options.preferEnvVars ?? tmp.preferEnvVars;
89
- return new Configuration(Utils.mergeConfig({}, esmConfigOptions, tmp, preferEnvVars ? options : env, preferEnvVars ? env : options));
90
- }
91
- static commonJSCompat(options) {
92
- if (this.isESM()) {
93
- return;
72
+ } else {
73
+ const tmpLastIndex = tmp.findLastIndex(configFinder);
74
+ if (tmpLastIndex !== tmpFirstIndex) {
75
+ throw new Error(
76
+ `MikroORM config '${contextName}' is not unique within the array exported by '${path}' (first occurrence index: ${tmpFirstIndex}; last occurrence index: ${tmpLastIndex})`,
77
+ );
94
78
  }
95
- /* v8 ignore next */
96
- options.dynamicImportProvider ??=
97
- globalThis.dynamicImportProvider ??
98
- ((id) => {
99
- return createRequire(process.cwd())(fileURLToPath(id));
100
- });
101
- globalThis.dynamicImportProvider = options.dynamicImportProvider;
102
- }
103
- static async getORM(contextName, configPaths, opts = {}) {
104
- const options = await this.getConfiguration(contextName, configPaths, opts);
105
- const settings = this.getSettings();
106
- options.set('allowGlobalContext', true);
107
- options.set('debug', !!settings.verbose);
108
- options.getLogger().setDebugMode(!!settings.verbose);
109
- if (settings.preferTs !== false) {
110
- options.set('preferTs', true);
79
+ tmp = tmp[tmpFirstIndex];
80
+ }
81
+ } else {
82
+ if (tmp instanceof Function) {
83
+ tmp = await tmp(contextName);
84
+ if (!isValidConfigFactoryResult(tmp)) {
85
+ throw new Error(
86
+ `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.`,
87
+ );
111
88
  }
112
- // The only times when we don't care to have a warning about no entities is also the time when we ignore entities.
113
- if (opts.discovery?.warnWhenNoEntities === false) {
114
- options.set('entities', []);
115
- options.set('entitiesTs', []);
89
+ } else {
90
+ if (!configFinder(tmp)) {
91
+ throw new Error(`MikroORM config '${contextName}' was not what the default export from '${path}' provided.`);
116
92
  }
117
- return MikroORM.init(options.getAll());
93
+ }
118
94
  }
119
- static async isDBConnected(config, reason = false) {
120
- try {
121
- await config.getDriver().connect();
122
- const isConnected = await config.getDriver().getConnection().checkConnection();
123
- await config.getDriver().close();
124
- return isConnected.ok || (reason ? isConnected.reason : false);
125
- }
126
- catch {
127
- return false;
128
- }
95
+ const esmConfigOptions = this.isESM() ? { entityGenerator: { esmImport: true } } : {};
96
+ await loadOptionalDependencies(tmp);
97
+ const preferEnvVars = options.preferEnvVars ?? tmp.preferEnvVars;
98
+ return new Configuration(
99
+ Utils.mergeConfig({}, esmConfigOptions, tmp, preferEnvVars ? options : env, preferEnvVars ? env : options),
100
+ );
101
+ }
102
+ static commonJSCompat(options) {
103
+ if (this.isESM()) {
104
+ return;
129
105
  }
130
- static getDriverDependencies(config) {
131
- try {
132
- return config.getDriver().getDependencies();
133
- }
134
- catch {
135
- return [];
136
- }
106
+ /* v8 ignore next */
107
+ options.dynamicImportProvider ??=
108
+ globalThis.dynamicImportProvider ??
109
+ (id => {
110
+ return createRequire(process.cwd())(fileURLToPath(id));
111
+ });
112
+ globalThis.dynamicImportProvider = options.dynamicImportProvider;
113
+ }
114
+ static async getORM(contextName, configPaths, opts = {}) {
115
+ const options = await this.getConfiguration(contextName, configPaths, opts);
116
+ const settings = this.getSettings();
117
+ options.set('allowGlobalContext', true);
118
+ options.set('debug', !!settings.verbose);
119
+ options.getLogger().setDebugMode(!!settings.verbose);
120
+ if (settings.preferTs !== false) {
121
+ options.set('preferTs', true);
137
122
  }
138
- static dump(text, config) {
139
- if (config?.get('highlighter')) {
140
- text = config.get('highlighter').highlight(text);
141
- }
142
- // eslint-disable-next-line no-console
143
- console.log(text);
123
+ // The only times when we don't care to have a warning about no entities is also the time when we ignore entities.
124
+ if (opts.discovery?.warnWhenNoEntities === false) {
125
+ options.set('entities', []);
126
+ options.set('entitiesTs', []);
144
127
  }
145
- static getSettings() {
146
- const config = fs.getPackageConfig();
147
- const settings = { ...config['mikro-orm'] };
148
- const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
149
- settings.preferTs =
150
- process.env.MIKRO_ORM_CLI_PREFER_TS != null ? bool(process.env.MIKRO_ORM_CLI_PREFER_TS) : settings.preferTs;
151
- settings.tsLoader = process.env.MIKRO_ORM_CLI_TS_LOADER ?? settings.tsLoader;
152
- settings.tsConfigPath = process.env.MIKRO_ORM_CLI_TS_CONFIG_PATH ?? settings.tsConfigPath;
153
- settings.verbose =
154
- process.env.MIKRO_ORM_CLI_VERBOSE != null ? bool(process.env.MIKRO_ORM_CLI_VERBOSE) : settings.verbose;
155
- if (process.env.MIKRO_ORM_CLI_CONFIG?.endsWith('.ts')) {
156
- settings.preferTs = true;
157
- }
158
- return settings;
128
+ return MikroORM.init(options.getAll());
129
+ }
130
+ static async isDBConnected(config, reason = false) {
131
+ try {
132
+ await config.getDriver().connect();
133
+ const isConnected = await config.getDriver().getConnection().checkConnection();
134
+ await config.getDriver().close();
135
+ return isConnected.ok || (reason ? isConnected.reason : false);
136
+ } catch {
137
+ return false;
159
138
  }
160
- static async getConfigPaths() {
161
- const settings = this.getSettings();
162
- const typeScriptSupport = settings.preferTs ?? Utils.detectTypeScriptSupport();
163
- const paths = [];
164
- if (process.env.MIKRO_ORM_CLI_CONFIG) {
165
- paths.push(process.env.MIKRO_ORM_CLI_CONFIG);
166
- }
167
- paths.push(...(settings.configPaths || []));
168
- if (typeScriptSupport) {
169
- paths.push('./src/mikro-orm.config.ts');
170
- paths.push('./mikro-orm.config.ts');
171
- }
172
- const distDir = fs.pathExists(process.cwd() + '/dist');
173
- const buildDir = fs.pathExists(process.cwd() + '/build');
174
- /* v8 ignore next */
175
- const path = distDir ? 'dist' : buildDir ? 'build' : 'src';
176
- paths.push(`./${path}/mikro-orm.config.js`);
177
- paths.push('./mikro-orm.config.js');
178
- /* v8 ignore next */
179
- return Utils.unique(paths).filter(p => !/\.[mc]?ts$/.exec(p) || typeScriptSupport);
139
+ }
140
+ static getDriverDependencies(config) {
141
+ try {
142
+ return config.getDriver().getDependencies();
143
+ } catch {
144
+ return [];
180
145
  }
181
- static async getConfigFile(paths) {
182
- for (let path of paths) {
183
- path = fs.absolutePath(path);
184
- path = fs.normalizePath(path);
185
- if (fs.pathExists(path)) {
186
- const config = await fs.dynamicImport(path);
187
- /* v8 ignore next */
188
- return [path, await (config.default ?? config)];
189
- }
190
- }
191
- return [];
146
+ }
147
+ static dump(text, config) {
148
+ if (config?.get('highlighter')) {
149
+ text = config.get('highlighter').highlight(text);
150
+ }
151
+ // eslint-disable-next-line no-console
152
+ console.log(text);
153
+ }
154
+ static getSettings() {
155
+ const config = fs.getPackageConfig();
156
+ const settings = { ...config['mikro-orm'] };
157
+ const bool = v => ['true', 't', '1'].includes(v.toLowerCase());
158
+ settings.preferTs =
159
+ process.env.MIKRO_ORM_CLI_PREFER_TS != null ? bool(process.env.MIKRO_ORM_CLI_PREFER_TS) : settings.preferTs;
160
+ settings.tsLoader = process.env.MIKRO_ORM_CLI_TS_LOADER ?? settings.tsLoader;
161
+ settings.tsConfigPath = process.env.MIKRO_ORM_CLI_TS_CONFIG_PATH ?? settings.tsConfigPath;
162
+ settings.verbose =
163
+ process.env.MIKRO_ORM_CLI_VERBOSE != null ? bool(process.env.MIKRO_ORM_CLI_VERBOSE) : settings.verbose;
164
+ if (process.env.MIKRO_ORM_CLI_CONFIG?.endsWith('.ts')) {
165
+ settings.preferTs = true;
166
+ }
167
+ return settings;
168
+ }
169
+ static async getConfigPaths() {
170
+ const settings = this.getSettings();
171
+ const typeScriptSupport = settings.preferTs ?? Utils.detectTypeScriptSupport();
172
+ const paths = [];
173
+ if (process.env.MIKRO_ORM_CLI_CONFIG) {
174
+ paths.push(process.env.MIKRO_ORM_CLI_CONFIG);
192
175
  }
193
- static async loadEnvironmentVars() {
194
- const ret = loadEnvironmentVars();
176
+ paths.push(...(settings.configPaths || []));
177
+ if (typeScriptSupport) {
178
+ paths.push('./src/mikro-orm.config.ts');
179
+ paths.push('./mikro-orm.config.ts');
180
+ }
181
+ const distDir = fs.pathExists(process.cwd() + '/dist');
182
+ const buildDir = fs.pathExists(process.cwd() + '/build');
183
+ /* v8 ignore next */
184
+ const path = distDir ? 'dist' : buildDir ? 'build' : 'src';
185
+ paths.push(`./${path}/mikro-orm.config.js`);
186
+ paths.push('./mikro-orm.config.js');
187
+ /* v8 ignore next */
188
+ return Utils.unique(paths).filter(p => !/\.[mc]?ts$/.exec(p) || typeScriptSupport);
189
+ }
190
+ static async getConfigFile(paths) {
191
+ for (let path of paths) {
192
+ path = fs.absolutePath(path);
193
+ path = fs.normalizePath(path);
194
+ if (fs.pathExists(path)) {
195
+ const config = await fs.dynamicImport(path);
195
196
  /* v8 ignore next */
196
- switch (process.env.MIKRO_ORM_TYPE) {
197
- case 'mongo':
198
- ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
199
- break;
200
- case 'mysql':
201
- ret.driver ??= await import('@mikro-orm/mysql').then(m => m.MySqlDriver);
202
- break;
203
- case 'mssql':
204
- ret.driver ??= await import('@mikro-orm/mssql').then(m => m.MsSqlDriver);
205
- break;
206
- case 'mariadb':
207
- ret.driver ??= await import('@mikro-orm/mariadb').then(m => m.MariaDbDriver);
208
- break;
209
- case 'postgresql':
210
- ret.driver ??= await import('@mikro-orm/postgresql').then(m => m.PostgreSqlDriver);
211
- break;
212
- case 'sqlite':
213
- ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
214
- break;
215
- case 'libsql':
216
- ret.driver ??= await import('@mikro-orm/libsql').then(m => m.LibSqlDriver);
217
- break;
218
- case 'oracledb':
219
- ret.driver ??= await import('@mikro-orm/oracledb').then(m => m.OracleDriver);
220
- break;
221
- }
222
- return ret;
197
+ return [path, await (config.default ?? config)];
198
+ }
223
199
  }
224
- static dumpDependencies() {
225
- const version = Utils.getORMVersion();
226
- CLIHelper.dump(' - dependencies:');
227
- CLIHelper.dump(` - mikro-orm ${colors.green(version)}`);
228
- CLIHelper.dump(` - node ${colors.green(process.versions.node)}`);
229
- if (fs.pathExists(process.cwd() + '/package.json')) {
230
- /* v8 ignore if */
231
- if (process.versions.bun) {
232
- CLIHelper.dump(` - typescript via bun`);
233
- }
234
- else {
235
- CLIHelper.dump(` - typescript ${CLIHelper.getModuleVersion('typescript')}`);
236
- }
237
- CLIHelper.dump(' - package.json ' + colors.green('found'));
238
- }
239
- else {
240
- CLIHelper.dump(' - package.json ' + colors.red('not found'));
241
- }
200
+ return [];
201
+ }
202
+ static async loadEnvironmentVars() {
203
+ const ret = loadEnvironmentVars();
204
+ /* v8 ignore next */
205
+ switch (process.env.MIKRO_ORM_TYPE) {
206
+ case 'mongo':
207
+ ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
208
+ break;
209
+ case 'mysql':
210
+ ret.driver ??= await import('@mikro-orm/mysql').then(m => m.MySqlDriver);
211
+ break;
212
+ case 'mssql':
213
+ ret.driver ??= await import('@mikro-orm/mssql').then(m => m.MsSqlDriver);
214
+ break;
215
+ case 'mariadb':
216
+ ret.driver ??= await import('@mikro-orm/mariadb').then(m => m.MariaDbDriver);
217
+ break;
218
+ case 'postgresql':
219
+ ret.driver ??= await import('@mikro-orm/postgresql').then(m => m.PostgreSqlDriver);
220
+ break;
221
+ case 'sqlite':
222
+ ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
223
+ break;
224
+ case 'libsql':
225
+ ret.driver ??= await import('@mikro-orm/libsql').then(m => m.LibSqlDriver);
226
+ break;
227
+ case 'oracledb':
228
+ ret.driver ??= await import('@mikro-orm/oracledb').then(m => m.OracleDriver);
229
+ break;
242
230
  }
243
- static getModuleVersion(name) {
244
- try {
245
- const path = `${this.resolveModulePath(name)}/package.json`;
246
- const pkg = fs.readJSONSync(path);
247
- return colors.green(pkg.version);
248
- }
249
- catch {
250
- return '';
251
- }
231
+ return ret;
232
+ }
233
+ static dumpDependencies() {
234
+ const version = Utils.getORMVersion();
235
+ CLIHelper.dump(' - dependencies:');
236
+ CLIHelper.dump(` - mikro-orm ${colors.green(version)}`);
237
+ CLIHelper.dump(` - node ${colors.green(process.versions.node)}`);
238
+ if (fs.pathExists(process.cwd() + '/package.json')) {
239
+ /* v8 ignore if */
240
+ if (process.versions.bun) {
241
+ CLIHelper.dump(` - typescript via bun`);
242
+ } else {
243
+ CLIHelper.dump(` - typescript ${CLIHelper.getModuleVersion('typescript')}`);
244
+ }
245
+ CLIHelper.dump(' - package.json ' + colors.green('found'));
246
+ } else {
247
+ CLIHelper.dump(' - package.json ' + colors.red('not found'));
252
248
  }
253
- /**
254
- * Resolve path to a module.
255
- * @param id The module to require
256
- * @param [from] Location to start the node resolution
257
- */
258
- static resolveModulePath(id, from = process.cwd()) {
259
- if (!extname(from)) {
260
- from = join(from, '__fake.js');
261
- }
262
- const path = fs.normalizePath(import.meta.resolve(id, pathToFileURL(from)));
263
- const parts = path.split('/');
264
- const idx = parts.lastIndexOf(id) + 1;
265
- parts.splice(idx, parts.length - idx);
266
- return parts.join('/');
249
+ }
250
+ static getModuleVersion(name) {
251
+ try {
252
+ const path = `${this.resolveModulePath(name)}/package.json`;
253
+ const pkg = fs.readJSONSync(path);
254
+ return colors.green(pkg.version);
255
+ } catch {
256
+ return '';
267
257
  }
268
- static dumpTable(options) {
269
- if (options.rows.length === 0) {
270
- return CLIHelper.dump(options.empty);
271
- }
272
- const data = [options.columns, ...options.rows];
273
- const lengths = options.columns.map(() => 0);
274
- data.forEach(row => {
275
- row.forEach((cell, idx) => {
276
- lengths[idx] = Math.max(lengths[idx], cell.length + 2);
277
- });
278
- });
279
- let ret = '';
280
- ret += colors.grey('┌' + lengths.map(length => '─'.repeat(length)).join('┬') + '┐\n');
281
- ret +=
282
- colors.grey('│') +
283
- lengths
284
- .map((length, idx) => ' ' + colors.red(options.columns[idx]) + ' '.repeat(length - options.columns[idx].length - 1))
285
- .join(colors.grey('│')) +
286
- colors.grey('│\n');
287
- ret += colors.grey('├' + lengths.map(length => '─'.repeat(length)).join('┼') + '┤\n');
288
- options.rows.forEach(row => {
289
- ret +=
290
- colors.grey('│') +
291
- lengths.map((length, idx) => ' ' + row[idx] + ' '.repeat(length - row[idx].length - 1)).join(colors.grey('│')) +
292
- colors.grey('│\n');
293
- });
294
- ret += colors.grey('└' + lengths.map(length => '─'.repeat(length)).join('┴') + '┘');
295
- CLIHelper.dump(ret);
258
+ }
259
+ /**
260
+ * Resolve path to a module.
261
+ * @param id The module to require
262
+ * @param [from] Location to start the node resolution
263
+ */
264
+ static resolveModulePath(id, from = process.cwd()) {
265
+ if (!extname(from)) {
266
+ from = join(from, '__fake.js');
296
267
  }
297
- /**
298
- * Tries to register TS support in the following order: swc, tsx, jiti, tsimp
299
- * Use `MIKRO_ORM_CLI_TS_LOADER` env var to set the loader explicitly.
300
- * This method is used only in CLI context.
301
- */
302
- static async registerTypeScriptSupport(configPath = 'tsconfig.json', tsLoader) {
303
- /* v8 ignore if */
304
- if (process.versions.bun) {
305
- return true;
306
- }
307
- process.env.SWC_NODE_PROJECT ??= configPath;
308
- process.env.TSIMP_PROJECT ??= configPath;
309
- process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS ??= '1';
310
- const explicitLoader = tsLoader ?? process.env.MIKRO_ORM_CLI_TS_LOADER ?? 'auto';
311
- const setEsmImportProvider = () => {
312
- return (globalThis.dynamicImportProvider = (id) => import(id).then(mod => mod?.default ?? mod));
313
- };
314
- const loaders = {
315
- swc: { esm: '@swc-node/register/esm-register', cjs: '@swc-node/register' },
316
- tsx: { esm: 'tsx/esm/api', cjs: 'tsx/cjs/api', cb: (tsx) => tsx.register({ tsconfig: configPath }) },
317
- jiti: { cjs: 'jiti/register', cb: setEsmImportProvider },
318
- tsimp: { cjs: 'tsimp/import', cb: setEsmImportProvider },
319
- };
320
- for (const loader of Utils.keys(loaders)) {
321
- if (explicitLoader !== 'auto' && loader !== explicitLoader) {
322
- continue;
323
- }
324
- const { esm, cjs, cb } = loaders[loader];
325
- const isEsm = this.isESM();
326
- const module = isEsm && esm ? esm : cjs;
327
- const mod = await Utils.tryImport({ module });
328
- if (mod) {
329
- cb?.(mod);
330
- process.env.MIKRO_ORM_CLI_TS_LOADER = loader;
331
- return true;
332
- }
333
- }
334
- // eslint-disable-next-line no-console
335
- console.warn('Neither `swc`, `tsx`, `jiti` nor `tsimp` found in the project dependencies, support for working with TypeScript files might not work. To use `swc`, you need to install both `@swc-node/register` and `@swc/core`.');
336
- return false;
268
+ const path = fs.normalizePath(import.meta.resolve(id, pathToFileURL(from)));
269
+ const parts = path.split('/');
270
+ const idx = parts.lastIndexOf(id) + 1;
271
+ parts.splice(idx, parts.length - idx);
272
+ return parts.join('/');
273
+ }
274
+ static dumpTable(options) {
275
+ if (options.rows.length === 0) {
276
+ return CLIHelper.dump(options.empty);
337
277
  }
338
- static isESM() {
339
- const config = fs.getPackageConfig();
340
- const type = config?.type ?? '';
341
- return type === 'module';
278
+ const data = [options.columns, ...options.rows];
279
+ const lengths = options.columns.map(() => 0);
280
+ data.forEach(row => {
281
+ row.forEach((cell, idx) => {
282
+ lengths[idx] = Math.max(lengths[idx], cell.length + 2);
283
+ });
284
+ });
285
+ let ret = '';
286
+ ret += colors.grey('┌' + lengths.map(length => '─'.repeat(length)).join('┬') + '┐\n');
287
+ ret +=
288
+ colors.grey('│') +
289
+ lengths
290
+ .map(
291
+ (length, idx) =>
292
+ ' ' + colors.red(options.columns[idx]) + ' '.repeat(length - options.columns[idx].length - 1),
293
+ )
294
+ .join(colors.grey('│')) +
295
+ colors.grey('│\n');
296
+ ret += colors.grey('├' + lengths.map(length => '─'.repeat(length)).join('┼') + '┤\n');
297
+ options.rows.forEach(row => {
298
+ ret +=
299
+ colors.grey('│') +
300
+ lengths.map((length, idx) => ' ' + row[idx] + ' '.repeat(length - row[idx].length - 1)).join(colors.grey('│')) +
301
+ colors.grey('│\n');
302
+ });
303
+ ret += colors.grey('└' + lengths.map(length => '─'.repeat(length)).join('┴') + '┘');
304
+ CLIHelper.dump(ret);
305
+ }
306
+ /**
307
+ * Tries to register TS support in the following order: swc, tsx, jiti, tsimp
308
+ * Use `MIKRO_ORM_CLI_TS_LOADER` env var to set the loader explicitly.
309
+ * This method is used only in CLI context.
310
+ */
311
+ static async registerTypeScriptSupport(configPath = 'tsconfig.json', tsLoader) {
312
+ /* v8 ignore if */
313
+ if (process.versions.bun) {
314
+ return true;
342
315
  }
343
- /* v8 ignore next */
344
- static showHelp() {
345
- yargs(process.argv.slice(2)).showHelp();
316
+ process.env.SWC_NODE_PROJECT ??= configPath;
317
+ process.env.TSIMP_PROJECT ??= configPath;
318
+ process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS ??= '1';
319
+ const explicitLoader = tsLoader ?? process.env.MIKRO_ORM_CLI_TS_LOADER ?? 'auto';
320
+ const setEsmImportProvider = () => {
321
+ return (globalThis.dynamicImportProvider = id => import(id).then(mod => mod?.default ?? mod));
322
+ };
323
+ const loaders = {
324
+ swc: { esm: '@swc-node/register/esm-register', cjs: '@swc-node/register' },
325
+ tsx: { esm: 'tsx/esm/api', cjs: 'tsx/cjs/api', cb: tsx => tsx.register({ tsconfig: configPath }) },
326
+ jiti: { cjs: 'jiti/register', cb: setEsmImportProvider },
327
+ tsimp: { cjs: 'tsimp/import', cb: setEsmImportProvider },
328
+ };
329
+ for (const loader of Utils.keys(loaders)) {
330
+ if (explicitLoader !== 'auto' && loader !== explicitLoader) {
331
+ continue;
332
+ }
333
+ const { esm, cjs, cb } = loaders[loader];
334
+ const isEsm = this.isESM();
335
+ const module = isEsm && esm ? esm : cjs;
336
+ const mod = await Utils.tryImport({ module });
337
+ if (mod) {
338
+ cb?.(mod);
339
+ process.env.MIKRO_ORM_CLI_TS_LOADER = loader;
340
+ return true;
341
+ }
346
342
  }
343
+ // eslint-disable-next-line no-console
344
+ console.warn(
345
+ 'Neither `swc`, `tsx`, `jiti` nor `tsimp` found in the project dependencies, support for working with TypeScript files might not work. To use `swc`, you need to install both `@swc-node/register` and `@swc/core`.',
346
+ );
347
+ return false;
348
+ }
349
+ static isESM() {
350
+ const config = fs.getPackageConfig();
351
+ const type = config?.type ?? '';
352
+ return type === 'module';
353
+ }
354
+ /* v8 ignore next */
355
+ static showHelp() {
356
+ yargs(process.argv.slice(2)).showHelp();
357
+ }
347
358
  }