@mikro-orm/cli 7.1.0-dev.0 → 7.1.0-dev.10

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.
@@ -8,6 +8,7 @@ import { DatabaseSeedCommand } from './commands/DatabaseSeedCommand.js';
8
8
  import { DebugCommand } from './commands/DebugCommand.js';
9
9
  import { GenerateCacheCommand } from './commands/GenerateCacheCommand.js';
10
10
  import { CompileCommand } from './commands/CompileCommand.js';
11
+ import { DiscoveryExportCommand } from './commands/DiscoveryExportCommand.js';
11
12
  import { GenerateEntitiesCommand } from './commands/GenerateEntitiesCommand.js';
12
13
  import { ImportCommand } from './commands/ImportCommand.js';
13
14
  import { MigrationCommandFactory } from './commands/MigrationCommandFactory.js';
@@ -53,6 +54,7 @@ export async function configure() {
53
54
  .command(new ClearCacheCommand())
54
55
  .command(new GenerateCacheCommand())
55
56
  .command(new CompileCommand())
57
+ .command(new DiscoveryExportCommand())
56
58
  .command(new GenerateEntitiesCommand())
57
59
  .command(new CreateDatabaseCommand())
58
60
  .command(new ImportCommand())
@@ -69,5 +71,8 @@ export async function configure() {
69
71
  .command(MigrationCommandFactory.create('check'))
70
72
  .command(MigrationCommandFactory.create('pending'))
71
73
  .command(MigrationCommandFactory.create('fresh'))
74
+ .command(MigrationCommandFactory.create('log'))
75
+ .command(MigrationCommandFactory.create('unlog'))
76
+ .command(MigrationCommandFactory.create('rollup'))
72
77
  .command(new DebugCommand());
73
78
  }
@@ -0,0 +1,23 @@
1
+ import type { ArgumentsCamelCase, Argv } from 'yargs';
2
+ import type { BaseArgs, BaseCommand } from '../CLIConfigurator.js';
3
+ type DiscoveryExportArgs = BaseArgs & {
4
+ path?: string[];
5
+ out?: string;
6
+ dump?: boolean;
7
+ };
8
+ export declare class DiscoveryExportCommand implements BaseCommand<DiscoveryExportArgs> {
9
+ command: string;
10
+ describe: string;
11
+ builder: (args: Argv<BaseArgs>) => Argv<DiscoveryExportArgs>;
12
+ /**
13
+ * @inheritDoc
14
+ */
15
+ handler: (args: ArgumentsCamelCase<DiscoveryExportArgs>) => Promise<void>;
16
+ private resolvePaths;
17
+ private discoverExports;
18
+ private inferNameFromDefault;
19
+ private resolveOutputPath;
20
+ private resolveDriverPackage;
21
+ private generateFile;
22
+ }
23
+ export {};
@@ -0,0 +1,219 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join, relative, resolve } from 'node:path';
3
+ import { colors, EntitySchema, MetadataStorage } from '@mikro-orm/core';
4
+ import { fs } from '@mikro-orm/core/fs-utils';
5
+ import { CLIHelper } from '../CLIHelper.js';
6
+ const driverPackageMap = {
7
+ PostgreSqlDriver: '@mikro-orm/postgresql',
8
+ MySqlDriver: '@mikro-orm/mysql',
9
+ MariaDbDriver: '@mikro-orm/mariadb',
10
+ SqliteDriver: '@mikro-orm/sqlite',
11
+ LibSqlDriver: '@mikro-orm/libsql',
12
+ MsSqlDriver: '@mikro-orm/mssql',
13
+ OracleDriver: '@mikro-orm/oracledb',
14
+ MongoDriver: '@mikro-orm/mongodb',
15
+ };
16
+ export class DiscoveryExportCommand {
17
+ command = 'discovery:export';
18
+ describe = 'Generate a TypeScript barrel file with entity exports for typed Kysely and ORM config';
19
+ builder = (args) => {
20
+ args.option('path', {
21
+ alias: 'p',
22
+ type: 'string',
23
+ array: true,
24
+ desc: 'Glob patterns for entity source files',
25
+ });
26
+ args.option('out', {
27
+ alias: 'o',
28
+ type: 'string',
29
+ desc: 'Output file path (defaults to next to ORM config)',
30
+ });
31
+ args.option('dump', {
32
+ alias: 'd',
33
+ type: 'boolean',
34
+ desc: 'Print to stdout instead of writing a file',
35
+ default: false,
36
+ });
37
+ return args;
38
+ };
39
+ /**
40
+ * @inheritDoc
41
+ */
42
+ handler = async (args) => {
43
+ const config = await CLIHelper.getConfiguration(args.contextName, args.config);
44
+ const paths = this.resolvePaths(args, config);
45
+ const baseDir = fs.absolutePath(config.get('baseDir') ?? process.cwd());
46
+ const discovered = await this.discoverExports(paths, baseDir);
47
+ if (discovered.length === 0) {
48
+ CLIHelper.dump(colors.yellow('No entities found in the specified paths.'));
49
+ return;
50
+ }
51
+ const esm = CLIHelper.isESM();
52
+ const driverPackage = this.resolveDriverPackage(config);
53
+ if (args.dump) {
54
+ const output = this.generateFile(discovered, join(process.cwd(), 'entities.generated.ts'), esm, driverPackage);
55
+ CLIHelper.dump(output);
56
+ return;
57
+ }
58
+ const outPath = await this.resolveOutputPath(args);
59
+ const output = this.generateFile(discovered, outPath, esm, driverPackage);
60
+ mkdirSync(dirname(outPath), { recursive: true });
61
+ writeFileSync(outPath, output);
62
+ CLIHelper.dump(colors.green(`Entity exports generated to ${outPath} (${discovered.length} entities)`));
63
+ CLIHelper.dump(`\nExample usage in your ORM config:\n`);
64
+ const importExt = esm ? '.js' : '';
65
+ const importPath = `./${basename(outPath).replace(/\.ts$/, importExt)}`;
66
+ CLIHelper.dump(` import { entities } from ${colors.cyan(`'${importPath}'`)};`);
67
+ CLIHelper.dump('');
68
+ CLIHelper.dump(' export default defineConfig({ entities });\n');
69
+ };
70
+ resolvePaths(args, config) {
71
+ if (args.path && args.path.length > 0) {
72
+ return args.path;
73
+ }
74
+ const entitiesTs = config.get('entitiesTs', []);
75
+ const stringPathsTs = entitiesTs.filter((p) => typeof p === 'string');
76
+ if (stringPathsTs.length > 0) {
77
+ return stringPathsTs;
78
+ }
79
+ const entities = config.get('entities', []);
80
+ const stringPaths = entities.filter((p) => typeof p === 'string');
81
+ if (stringPaths.length > 0) {
82
+ return stringPaths;
83
+ }
84
+ throw new Error('No entity paths found in config. Use --path to specify entity source locations.');
85
+ }
86
+ async discoverExports(paths, baseDir) {
87
+ const normalizedPaths = paths.map(path => fs.normalizePath(path));
88
+ const normalizedBaseDir = fs.normalizePath(baseDir);
89
+ const files = fs.glob(normalizedPaths, normalizedBaseDir);
90
+ const discovered = [];
91
+ for (const filepath of files) {
92
+ const filename = basename(filepath);
93
+ if (!/\.[cm]?[jt]s$/.exec(filename) || /\.d\.[cm]?ts/.exec(filename)) {
94
+ continue;
95
+ }
96
+ // fs.glob returns paths relative to normalizedBaseDir
97
+ const path = fs.normalizePath(baseDir, filepath);
98
+ const exports = await fs.dynamicImport(path);
99
+ const entries = Object.entries(exports);
100
+ // Collect entity schemas and their linked classes for dedup
101
+ const schemaClasses = new Set();
102
+ for (const [, value] of entries) {
103
+ if (EntitySchema.is(value) && value.meta.class) {
104
+ schemaClasses.add(value.meta.class);
105
+ }
106
+ }
107
+ for (const [key, value] of entries) {
108
+ if (key === '__esModule') {
109
+ continue;
110
+ }
111
+ const isSchema = EntitySchema.is(value);
112
+ // Skip class implementations that are linked from an EntitySchema
113
+ if (!isSchema && schemaClasses.has(value)) {
114
+ continue;
115
+ }
116
+ const validTarget = isSchema || (value instanceof Function && MetadataStorage.isKnownEntity(value.name));
117
+ if (!validTarget) {
118
+ continue;
119
+ }
120
+ const exportName = key === 'default' ? this.inferNameFromDefault(value, isSchema) : key;
121
+ // Avoid duplicates (e.g., default + named export of same thing)
122
+ if (discovered.some(d => d.filePath === path && d.exportName === exportName)) {
123
+ continue;
124
+ }
125
+ discovered.push({
126
+ exportName,
127
+ filePath: path,
128
+ isDefault: key === 'default',
129
+ });
130
+ }
131
+ }
132
+ discovered.sort((a, b) => a.exportName.localeCompare(b.exportName));
133
+ return discovered;
134
+ }
135
+ inferNameFromDefault(value, isSchema) {
136
+ if (isSchema) {
137
+ return value.meta.className ?? value.meta.name ?? 'DefaultEntity';
138
+ }
139
+ return value.name ?? 'DefaultEntity';
140
+ }
141
+ async resolveOutputPath(args) {
142
+ if (args.out) {
143
+ return resolve(args.out);
144
+ }
145
+ const configPaths = args.config ?? (await CLIHelper.getConfigPaths());
146
+ for (const configPath of configPaths) {
147
+ const absPath = fs.absolutePath(configPath);
148
+ if (fs.pathExists(absPath)) {
149
+ return resolve(dirname(absPath), 'entities.generated.ts');
150
+ }
151
+ }
152
+ return resolve(process.cwd(), 'entities.generated.ts');
153
+ }
154
+ resolveDriverPackage(config) {
155
+ try {
156
+ const driverName = config.getDriver().constructor.name;
157
+ return driverPackageMap[driverName] ?? '@mikro-orm/sql';
158
+ }
159
+ catch {
160
+ return '@mikro-orm/sql';
161
+ }
162
+ }
163
+ generateFile(discovered, outPath, esm, driverPackage) {
164
+ const outDir = dirname(outPath);
165
+ const lines = [
166
+ '// This file was generated by MikroORM CLI. Do not edit manually.',
167
+ '// Re-run `mikro-orm discovery:export` to update.',
168
+ '',
169
+ ];
170
+ // Group by file path for imports
171
+ const byFile = new Map();
172
+ for (const item of discovered) {
173
+ const list = byFile.get(item.filePath) ?? [];
174
+ list.push(item);
175
+ byFile.set(item.filePath, list);
176
+ }
177
+ // Generate import lines
178
+ for (const [filePath, items] of byFile) {
179
+ let rel = relative(outDir, filePath);
180
+ if (!rel.startsWith('.')) {
181
+ rel = './' + rel;
182
+ }
183
+ // Remove .ts extension and optionally add .js for ESM
184
+ rel = rel.replace(/\.[cm]?[jt]s$/, '');
185
+ if (esm) {
186
+ rel += '.js';
187
+ }
188
+ const defaults = items.filter(i => i.isDefault);
189
+ const named = items.filter(i => !i.isDefault);
190
+ for (const d of defaults) {
191
+ lines.push(`import ${d.exportName} from '${rel}';`);
192
+ }
193
+ if (named.length > 0) {
194
+ const names = named.map(n => n.exportName).join(', ');
195
+ lines.push(`import { ${names} } from '${rel}';`);
196
+ }
197
+ }
198
+ const isMongo = driverPackage === '@mikro-orm/mongodb';
199
+ // Type imports (Kysely types are not available for MongoDB)
200
+ if (!isMongo) {
201
+ lines.push(`import type { EntitySchemaWithMeta, InferKyselyDB, InferClassEntityDB } from '${driverPackage}';`);
202
+ }
203
+ lines.push('');
204
+ // entities array
205
+ lines.push('export const entities = [');
206
+ for (const item of discovered) {
207
+ lines.push(` ${item.exportName},`);
208
+ }
209
+ lines.push('] as const;');
210
+ // Database type (Kysely is SQL-only, skip for MongoDB)
211
+ if (!isMongo) {
212
+ lines.push('');
213
+ lines.push('export type Database = InferKyselyDB<Extract<(typeof entities)[number], EntitySchemaWithMeta>>');
214
+ lines.push(' & InferClassEntityDB<(typeof entities)[number]>;');
215
+ }
216
+ lines.push('');
217
+ return lines.join('\n');
218
+ }
219
+ }
@@ -9,6 +9,9 @@ export declare class MigrationCommandFactory {
9
9
  check: string;
10
10
  pending: string;
11
11
  fresh: string;
12
+ log: string;
13
+ unlog: string;
14
+ rollup: string;
12
15
  };
13
16
  static create<const T extends MigratorMethod>(command: T): {
14
17
  command: string;
@@ -20,11 +23,15 @@ export declare class MigrationCommandFactory {
20
23
  check: string;
21
24
  pending: string;
22
25
  fresh: string;
26
+ log: string;
27
+ unlog: string;
28
+ rollup: string;
23
29
  }[T];
24
30
  builder: (args: Argv<BaseArgs>) => Argv<MigrationOptionsMap[T]>;
25
31
  handler: (args: ArgumentsCamelCase<MigrationOptionsMap[T]>) => Promise<void>;
26
32
  };
27
33
  static configureMigrationCommand<const T extends MigratorMethod>(args: Argv<BaseArgs>, method: T): Argv<MigrationOptionsMap[T]>;
34
+ private static configureLogUnlogCommand;
28
35
  private static configureUpDownCommand;
29
36
  private static configureCreateCommand;
30
37
  static handleMigrationCommand(args: ArgumentsCamelCase<Opts>, method: MigratorMethod): Promise<void>;
@@ -35,6 +42,8 @@ export declare class MigrationCommandFactory {
35
42
  private static handleCreateCommand;
36
43
  private static handleCheckCommand;
37
44
  private static handleFreshCommand;
45
+ private static handleLogUnlogCommand;
46
+ private static handleRollupCommand;
38
47
  private static getUpDownOptions;
39
48
  private static getUpDownSuccessMessage;
40
49
  }
@@ -54,6 +63,9 @@ type MigratorCreateOptions = BaseArgs & {
54
63
  dump?: boolean;
55
64
  name?: string;
56
65
  };
66
+ type MigratorLogUnlogOptions = BaseArgs & {
67
+ name?: string;
68
+ };
57
69
  type MigrationOptionsMap = {
58
70
  create: MigratorCreateOptions;
59
71
  check: BaseArgs;
@@ -62,7 +74,10 @@ type MigrationOptionsMap = {
62
74
  list: BaseArgs;
63
75
  pending: BaseArgs;
64
76
  fresh: MigratorFreshOptions;
77
+ log: MigratorLogUnlogOptions;
78
+ unlog: MigratorLogUnlogOptions;
79
+ rollup: BaseArgs;
65
80
  };
66
81
  type MigratorMethod = keyof MigrationOptionsMap;
67
- type Opts = BaseArgs & MigratorCreateOptions & CliUpDownOptions & MigratorFreshOptions;
82
+ type Opts = BaseArgs & MigratorCreateOptions & CliUpDownOptions & MigratorFreshOptions & MigratorLogUnlogOptions;
68
83
  export {};
@@ -9,6 +9,9 @@ export class MigrationCommandFactory {
9
9
  check: 'Check if migrations are needed. Useful for bash scripts.',
10
10
  pending: 'List all pending migrations',
11
11
  fresh: 'Clear the database and rerun all migrations',
12
+ log: 'Mark a migration as executed without running it',
13
+ unlog: 'Remove a migration from the executed list without reverting it',
14
+ rollup: 'Combine multiple migrations into a single migration',
12
15
  };
13
16
  static create(command) {
14
17
  // oxfmt-ignore
@@ -29,6 +32,18 @@ export class MigrationCommandFactory {
29
32
  if (method === 'fresh') {
30
33
  return this.configureFreshCommand(args);
31
34
  }
35
+ if (method === 'log' || method === 'unlog') {
36
+ return this.configureLogUnlogCommand(args);
37
+ }
38
+ return args;
39
+ }
40
+ static configureLogUnlogCommand(args) {
41
+ args.option('n', {
42
+ alias: 'name',
43
+ type: 'string',
44
+ desc: 'Name of the migration to log/unlog',
45
+ demandOption: true,
46
+ });
32
47
  return args;
33
48
  }
34
49
  static configureUpDownCommand(args, method) {
@@ -100,6 +115,14 @@ export class MigrationCommandFactory {
100
115
  break;
101
116
  case 'fresh':
102
117
  await this.handleFreshCommand(args, orm.migrator, orm);
118
+ break;
119
+ case 'log':
120
+ case 'unlog':
121
+ await this.handleLogUnlogCommand(args, orm.migrator, method);
122
+ break;
123
+ case 'rollup':
124
+ await this.handleRollupCommand(orm.migrator);
125
+ break;
103
126
  }
104
127
  await orm.close(true);
105
128
  }
@@ -182,6 +205,15 @@ export class MigrationCommandFactory {
182
205
  CLIHelper.dump(colors.green(`Database seeded successfully with seeder class ${seederClass}`));
183
206
  }
184
207
  }
208
+ static async handleLogUnlogCommand(args, migrator, method) {
209
+ await migrator[`${method}Migration`](args.name);
210
+ const action = method === 'log' ? 'logged' : 'unlogged';
211
+ CLIHelper.dump(colors.green(`Successfully ${action} migration '${args.name}'`));
212
+ }
213
+ static async handleRollupCommand(migrator) {
214
+ const ret = await migrator.rollup();
215
+ CLIHelper.dump(colors.green(`${ret.fileName} successfully created (rollup)`));
216
+ }
185
217
  static getUpDownOptions(flags) {
186
218
  if (!flags.to && !flags.from && flags.only) {
187
219
  return { migrations: flags.only.split(/[, ]+/) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/cli",
3
- "version": "7.1.0-dev.0",
3
+ "version": "7.1.0-dev.10",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -50,8 +50,8 @@
50
50
  "copy": "node ../../scripts/copy.mjs"
51
51
  },
52
52
  "dependencies": {
53
- "@mikro-orm/core": "7.1.0-dev.0",
54
- "mikro-orm": "7.1.0-dev.0",
53
+ "@mikro-orm/core": "7.1.0-dev.10",
54
+ "mikro-orm": "7.1.0-dev.10",
55
55
  "yargs": "17.7.2"
56
56
  },
57
57
  "engines": {