@meghjs/cli 0.5.0 → 0.5.2

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.
@@ -1,8 +1,17 @@
1
- export declare const DEFAULT_CONNECTION = "src/database/connection.ts";
1
+ /** Where apps used to export their own Kysely instance. Still used when present. */
2
+ export declare const LEGACY_CONNECTION = "src/database/connection.ts";
2
3
  export declare const DEFAULT_MIGRATIONS = "src/database/migrations";
3
4
  export type DatabasePaths = {
4
- /** Module exporting the app's Kysely instance (`default` or `db`). */
5
- connection: string;
5
+ /**
6
+ * A module exporting the app's own Kysely instance (`default` or `db`),
7
+ * from before `useMeghORM`. `null` when the connection comes from settings.
8
+ */
9
+ connection: string | null;
10
+ /**
11
+ * Connection settings from `megh.database` in package.json, merged over
12
+ * the environment (DATABASE_URL, DB_*) the way `app.useMeghORM()` does.
13
+ */
14
+ settings: Record<string, unknown>;
6
15
  /** Folder of migration files. */
7
16
  migrations: string;
8
17
  };
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_MIGRATIONS = exports.DEFAULT_CONNECTION = void 0;
6
+ exports.DEFAULT_MIGRATIONS = exports.LEGACY_CONNECTION = void 0;
7
7
  exports.databasePaths = databasePaths;
8
8
  exports.runMigrations = runMigrations;
9
9
  exports.migrate = migrate;
@@ -20,26 +20,35 @@ const errors_1 = require("../errors");
20
20
  const entry_1 = require("../utils/entry");
21
21
  const log_1 = require("../utils/log");
22
22
  const project_1 = require("../utils/project");
23
- exports.DEFAULT_CONNECTION = "src/database/connection.ts";
23
+ /** Where apps used to export their own Kysely instance. Still used when present. */
24
+ exports.LEGACY_CONNECTION = "src/database/connection.ts";
24
25
  exports.DEFAULT_MIGRATIONS = "src/database/migrations";
25
26
  /** `megh.database` / `megh.migrations` from package.json, else the defaults. */
26
27
  function databasePaths(root, pkg = (0, project_1.readPackageJson)(root)) {
27
28
  const conf = pkg?.megh ?? {};
29
+ const legacy = path_1.default.resolve(root, exports.LEGACY_CONNECTION);
30
+ let connection = null;
31
+ if (typeof conf.database === "string")
32
+ connection = path_1.default.resolve(root, conf.database);
33
+ else if (!conf.database && fs_1.default.existsSync(legacy))
34
+ connection = legacy;
28
35
  return {
29
- connection: path_1.default.resolve(root, typeof conf.database === "string" ? conf.database : exports.DEFAULT_CONNECTION),
36
+ connection,
37
+ settings: conf.database && typeof conf.database === "object" ? conf.database : {},
30
38
  migrations: path_1.default.resolve(root, typeof conf.migrations === "string" ? conf.migrations : exports.DEFAULT_MIGRATIONS),
31
39
  };
32
40
  }
33
41
  const MARKER = "__MEGH_MIGRATE__";
34
42
  /**
35
- * Runs in a child process: loads `.env`, the compiled connection module and
36
- * @meghjs/core from the project, runs the action, prints the result as JSON
37
- * after MARKER and closes the connection.
43
+ * Runs in a child process: loads `.env` and @meghjs/core from the project,
44
+ * connects from the settings (or loads a legacy connection module), runs
45
+ * the action, prints the result as JSON after MARKER and closes the
46
+ * connection.
38
47
  */
39
48
  const WORKER = `
40
49
  const fs = require("fs");
41
50
  const path = require("path");
42
- const [root, connection, folder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
51
+ const [root, connection, settings, folder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
43
52
  const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(value));
44
53
  (async () => {
45
54
  let db;
@@ -50,10 +59,17 @@ const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(v
50
59
  try { core = require(require.resolve("@meghjs/core", { paths: [root] })); }
51
60
  catch { throw new Error("@meghjs/core is not installed in this project."); }
52
61
  if (typeof core.Migrations !== "function") throw new Error("This @meghjs/core version has no migrations; upgrade it.");
53
- const mod = require(connection);
54
- db = mod && (mod.default || mod.db);
55
- if (!db || typeof db.schema !== "object" || typeof db.destroy !== "function") {
56
- throw new Error("The connection module must export a Kysely instance as its default export or as \`db\`.");
62
+ if (connection) {
63
+ const mod = require(connection);
64
+ db = mod && (mod.default || mod.db);
65
+ if (!db || typeof db.schema !== "object" || typeof db.destroy !== "function") {
66
+ throw new Error("The connection module must export a Kysely instance as its default export or as \`db\`.");
67
+ }
68
+ } else {
69
+ if (typeof core.createDatabase !== "function") {
70
+ throw new Error("This @meghjs/core version can't connect from DATABASE_URL; upgrade it, or export a Kysely instance from src/database/connection.ts.");
71
+ }
72
+ db = core.createDatabase(core.resolveDatabaseOptions(settings));
57
73
  }
58
74
  const migrations = new core.Migrations(db, { folder });
59
75
  send({ ok: true, result: await migrations[action](...args) });
@@ -69,10 +85,9 @@ function compiled(root) {
69
85
  const layout = (0, entry_1.projectLayout)(root);
70
86
  const paths = databasePaths(root);
71
87
  const rel = (p) => path_1.default.relative(root, p).split(path_1.default.sep).join("/");
72
- if (!fs_1.default.existsSync(paths.connection)) {
88
+ if (paths.connection && !fs_1.default.existsSync(paths.connection)) {
73
89
  throw new errors_1.CliError(`No database connection module at ${rel(paths.connection)}.\n` +
74
- "Create it and export your Kysely instance (export default db), or point " +
75
- '"megh.database" in package.json at it.');
90
+ 'Remove "megh.database" from package.json to connect from DATABASE_URL, as app.useMeghORM() does.');
76
91
  }
77
92
  const cacheDir = path_1.default.join(root, "node_modules", ".cache", "megh", "migrate");
78
93
  fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
@@ -94,11 +109,12 @@ function compiled(root) {
94
109
  const list = [...failures].map(([f, e]) => `${rel(f)}: ${e.split("\n")[0]}`).join("\n ");
95
110
  throw new errors_1.CliError(`Compilation failed:\n ${list}`);
96
111
  }
97
- if (!inside(layout.srcDir, paths.connection)) {
112
+ if (paths.connection && !inside(layout.srcDir, paths.connection)) {
98
113
  throw new errors_1.CliError(`The connection module ${rel(paths.connection)} must be inside ${rel(layout.srcDir)}/.`);
99
114
  }
100
115
  return {
101
- connection: app.outFileFor(paths.connection),
116
+ connection: paths.connection ? app.outFileFor(paths.connection) : null,
117
+ settings: paths.settings,
102
118
  // outFileFor maps a file; map a placeholder inside the folder and take its directory.
103
119
  migrations: path_1.default.dirname(migrationsCompiler.outFileFor(path_1.default.join(paths.migrations, "x.ts"))),
104
120
  };
@@ -108,7 +124,7 @@ function runMigrations(action, opts = {}) {
108
124
  const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
109
125
  const files = compiled(root);
110
126
  const args = action === "rollback" ? [opts.step ?? 1] : [];
111
- const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.migrations, action, args])], {
127
+ const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.settings, files.migrations, action, args])], {
112
128
  cwd: root,
113
129
  encoding: "utf8",
114
130
  env: { ...process.env, NODE_ENV: process.env.NODE_ENV ?? "development" },
@@ -1,7 +1,10 @@
1
1
  export declare const PACKAGE_MANAGERS: readonly ["npm", "yarn", "pnpm"];
2
2
  export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
3
- export declare const FEATURES: readonly ["openapi", "cors", "typeorm", "knex", "scalar"];
3
+ export declare const FEATURES: readonly ["openapi", "cors", "orm", "typeorm", "knex", "scalar"];
4
4
  export type Feature = (typeof FEATURES)[number];
5
+ /** Databases MeghORM (the `orm` feature) can connect to. */
6
+ export declare const DATABASES: readonly ["postgres", "mysql", "sqlite", "mssql"];
7
+ export type DatabaseKind = (typeof DATABASES)[number];
5
8
  export type NewOptions = {
6
9
  cwd?: string;
7
10
  minimal?: boolean;
@@ -10,10 +13,12 @@ export type NewOptions = {
10
13
  yes?: boolean;
11
14
  pm?: string;
12
15
  features?: string[];
16
+ /** Database for the `orm` feature: postgres, mysql, sqlite or mssql. Implies `orm`. */
17
+ database?: string;
13
18
  /** Skip `<pm> install`. Also enabled by the `MEGH_SKIP_INSTALL=1` environment variable. */
14
19
  skipInstall?: boolean;
15
20
  };
16
- export declare function packageJson(name: string, features: Feature[], minimal: boolean): string;
21
+ export declare function packageJson(name: string, features: Feature[], minimal: boolean, database?: DatabaseKind): string;
17
22
  export declare function installCommand(pm: PackageManager): string;
18
23
  export declare function devCommand(pm: PackageManager): string;
19
24
  export declare function createApplication(name: string, opts?: NewOptions): Promise<string>;
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.FEATURES = exports.PACKAGE_MANAGERS = void 0;
39
+ exports.DATABASES = exports.FEATURES = exports.PACKAGE_MANAGERS = void 0;
40
40
  exports.packageJson = packageJson;
41
41
  exports.installCommand = installCommand;
42
42
  exports.devCommand = devCommand;
@@ -50,8 +50,22 @@ const names_1 = require("../utils/names");
50
50
  const stubs_1 = require("../utils/stubs");
51
51
  const env_types_1 = require("../utils/env-types");
52
52
  exports.PACKAGE_MANAGERS = ["npm", "yarn", "pnpm"];
53
- exports.FEATURES = ["openapi", "cors", "typeorm", "knex", "scalar"];
53
+ exports.FEATURES = ["openapi", "cors", "orm", "typeorm", "knex", "scalar"];
54
54
  const DEFAULT_FEATURES = ["openapi"];
55
+ /** Databases MeghORM (the `orm` feature) can connect to. */
56
+ exports.DATABASES = ["postgres", "mysql", "sqlite", "mssql"];
57
+ /** SQLite needs no server, so a project made with `--yes` runs straight away. */
58
+ const DEFAULT_DATABASE = "sqlite";
59
+ /** Per database: the driver packages, and the `DATABASE_URL` written to `.env`. */
60
+ const DATABASE_SETUP = {
61
+ postgres: { drivers: ["pg"], url: "postgres://postgres:postgres@localhost:5432/{name}" },
62
+ mysql: { drivers: ["mysql2"], url: "mysql://root:root@localhost:3306/{name}" },
63
+ sqlite: { drivers: ["better-sqlite3"], url: "sqlite:./database.sqlite" },
64
+ mssql: {
65
+ drivers: ["tedious", "tarn"],
66
+ url: "mssql://sa:YourStrong!Passw0rd@localhost:1433/{name}?trustServerCertificate=true",
67
+ },
68
+ };
55
69
  /** Third-party versions for generated projects. */
56
70
  const DEP_VERSIONS = {
57
71
  "class-transformer": "^0.5.1",
@@ -60,10 +74,14 @@ const DEP_VERSIONS = {
60
74
  "@fastify/cors": "^11.0.0",
61
75
  typeorm: "^0.3.20",
62
76
  pg: "^8.11.0",
77
+ mysql2: "^3.11.0",
78
+ "better-sqlite3": "^12.0.0",
79
+ tedious: "^19.0.0",
80
+ tarn: "^3.0.2",
63
81
  knex: "^3.1.0",
64
82
  "@scalar/fastify-api-reference": "^1.0.0",
65
83
  typescript: "^5.7.2",
66
- "@types/node": "^22.9.3",
84
+ "@types/node": "^22.20.5",
67
85
  vitest: "^4.1.12",
68
86
  "@vitest/coverage-v8": "^4.1.12",
69
87
  "unplugin-swc": "^2.0.0",
@@ -83,11 +101,21 @@ async function prompt(opts) {
83
101
  if (opts.pm && !exports.PACKAGE_MANAGERS.includes(opts.pm)) {
84
102
  throw new errors_1.CliError(`Unknown package manager "${opts.pm}". Choose from: ${exports.PACKAGE_MANAGERS.join(", ")}.`);
85
103
  }
104
+ if (opts.database && !exports.DATABASES.includes(opts.database)) {
105
+ throw new errors_1.CliError(`Unknown database "${opts.database}". Choose from: ${exports.DATABASES.join(", ")}.`);
106
+ }
107
+ if (opts.database && opts.minimal) {
108
+ throw new errors_1.CliError("--database sets up MeghORM, which needs a full project. Leave out --minimal.");
109
+ }
86
110
  const interactive = !opts.yes && process.stdin.isTTY === true && process.stdout.isTTY === true;
87
111
  let pm = opts.pm;
88
112
  let features = opts.features ? validateFeatures(opts.features) : undefined;
89
113
  if (opts.minimal)
90
114
  features = [];
115
+ let database = opts.database;
116
+ // --database implies the ORM.
117
+ if (database && features && !features.includes("orm"))
118
+ features = [...features, "orm"];
91
119
  if (interactive && (!pm || !features)) {
92
120
  const { default: inquirer } = await Promise.resolve().then(() => __importStar(require("inquirer")));
93
121
  if (!pm) {
@@ -110,6 +138,7 @@ async function prompt(opts) {
110
138
  choices: [
111
139
  { name: "OpenAPI / Swagger docs", value: "openapi", checked: true },
112
140
  { name: "CORS support", value: "cors" },
141
+ { name: "MeghORM: models, migrations and a query builder", value: "orm", checked: !!database },
113
142
  { name: "TypeORM", value: "typeorm" },
114
143
  { name: "Knex", value: "knex" },
115
144
  { name: "Scalar UI (replaces Swagger UI)", value: "scalar" },
@@ -117,10 +146,31 @@ async function prompt(opts) {
117
146
  },
118
147
  ]));
119
148
  }
149
+ if (features.includes("orm") && !database) {
150
+ ({ database } = await inquirer.prompt([
151
+ {
152
+ type: "list",
153
+ name: "database",
154
+ message: "Database:",
155
+ choices: [
156
+ { name: "PostgreSQL", value: "postgres" },
157
+ { name: "MySQL / MariaDB", value: "mysql" },
158
+ { name: "SQLite (a file, no server)", value: "sqlite" },
159
+ { name: "SQL Server", value: "mssql" },
160
+ ],
161
+ default: DEFAULT_DATABASE,
162
+ },
163
+ ]));
164
+ }
120
165
  }
121
- return { pm: pm ?? "npm", features: features ?? DEFAULT_FEATURES };
166
+ const chosen = features ?? (database ? [...DEFAULT_FEATURES, "orm"] : DEFAULT_FEATURES);
167
+ return {
168
+ pm: pm ?? "npm",
169
+ features: chosen,
170
+ database: chosen.includes("orm") ? (database ?? DEFAULT_DATABASE) : undefined,
171
+ };
122
172
  }
123
- function packageJson(name, features, minimal) {
173
+ function packageJson(name, features, minimal, database = DEFAULT_DATABASE) {
124
174
  const v = (0, stubs_1.cliVersion)();
125
175
  const deps = {
126
176
  "@meghjs/core": (0, stubs_1.coreRange)(),
@@ -136,6 +186,8 @@ function packageJson(name, features, minimal) {
136
186
  pick("typeorm", "pg");
137
187
  if (features.includes("knex"))
138
188
  pick("knex", "pg");
189
+ if (features.includes("orm"))
190
+ pick(...DATABASE_SETUP[database].drivers);
139
191
  if (features.includes("scalar"))
140
192
  pick("@scalar/fastify-api-reference");
141
193
  const devDeps = {};
@@ -164,7 +216,7 @@ function packageJson(name, features, minimal) {
164
216
  main: "dist/serve.js",
165
217
  scripts,
166
218
  keywords: ["megh", "nodejs", "typescript"],
167
- engines: { node: ">=20" },
219
+ engines: { node: ">=22" },
168
220
  dependencies: sortKeys(deps),
169
221
  devDependencies: sortKeys(devDeps),
170
222
  };
@@ -187,6 +239,9 @@ function appSource(features) {
187
239
  setup.push(`app.useCors({ origin: '*' });`);
188
240
  if (imports.length)
189
241
  setup.push(`if (app.isDevelopment()) {\n app.useOpenApi(OpenApiConfig);\n}`);
242
+ if (features.includes("orm")) {
243
+ setup.push(`// Connects from DATABASE_URL in .env; megh migrate uses the same setting.\napp.useMeghORM();`);
244
+ }
190
245
  if (features.includes("typeorm")) {
191
246
  setup.push(`// TODO: pass your TypeORM DataSourceOptions (or an @AppConfig class)\n` +
192
247
  `// await app.useTypeORM({ type: 'postgres', url: process.env.DATABASE_URL, entities: [] });`);
@@ -227,7 +282,8 @@ async function createApplication(name, opts = {}) {
227
282
  throw new errors_1.CliError(`Directory ${root} is not empty. Use -f or --force to scaffold into it anyway.`);
228
283
  }
229
284
  }
230
- const { pm, features } = await prompt(opts);
285
+ const { pm, features, database } = await prompt(opts);
286
+ const orm = features.includes("orm") && database ? DATABASE_SETUP[database] : undefined;
231
287
  console.log();
232
288
  console.log(log_1.c.bold(log_1.c.cyan(" Megh")) + log_1.c.dim(` v${(0, stubs_1.cliVersion)()}`));
233
289
  console.log(` ${log_1.c.dim("Creating project:")} ${log_1.c.bold(appName)}${minimal ? log_1.c.dim(" (minimal)") : ""}`);
@@ -252,12 +308,21 @@ async function createApplication(name, opts = {}) {
252
308
  add("vitest.e2e.config.mts", (0, stubs_1.renderStub)("project/vitest-e2e.config.stub"));
253
309
  }
254
310
  add("src/serve.ts", (0, stubs_1.renderStub)("project/serve.stub"));
255
- add("package.json", packageJson(appName, features, minimal));
311
+ add("package.json", packageJson(appName, features, minimal, database));
256
312
  add("tsconfig.json", (0, stubs_1.renderStub)("project/tsconfig.stub"));
257
313
  add(env_types_1.ENV_TYPES_FILE, (0, env_types_1.envTypesFile)(usesData(features) ? ["@meghjs/data"] : []));
258
314
  add("tsconfig.build.json", (0, stubs_1.renderStub)("project/tsconfig.build.stub"));
259
- add(".gitignore", (0, stubs_1.renderStub)("project/gitignore.stub"));
260
- add(".env", (0, stubs_1.renderStub)("project/env.stub"));
315
+ let gitignore = (0, stubs_1.renderStub)("project/gitignore.stub");
316
+ let env = (0, stubs_1.renderStub)("project/env.stub");
317
+ if (orm) {
318
+ const url = orm.url.replace("{name}", (0, names_1.kebabCase)(appName).replace(/-/g, "_") || "app");
319
+ env = env.replace(/\n*$/, "\n") + `\n# MeghORM: app.useMeghORM() and megh migrate connect with this.\nDATABASE_URL=${url}\n`;
320
+ if (database === "sqlite")
321
+ gitignore = gitignore.replace(/\n*$/, "\n") + "database.sqlite\n";
322
+ add("src/database/migrations/.gitkeep", "");
323
+ }
324
+ add(".gitignore", gitignore);
325
+ add(".env", env);
261
326
  add("README.md", (0, stubs_1.renderStub)("project/readme.stub", {
262
327
  AppTitle: (0, names_1.titleCase)(appName) || appName,
263
328
  InstallCmd: installCommand(pm),
@@ -297,6 +362,12 @@ async function createApplication(name, opts = {}) {
297
362
  console.log(log_1.c.cyan(` cd ${rel(root)}`));
298
363
  if (skipInstall)
299
364
  console.log(log_1.c.cyan(` ${installCommand(pm)}`));
365
+ if (orm) {
366
+ if (database !== "sqlite")
367
+ console.log(log_1.c.dim(" # set DATABASE_URL in .env"));
368
+ console.log(log_1.c.cyan(" npx megh make:migration create_users_table"));
369
+ console.log(log_1.c.cyan(" npx megh migrate"));
370
+ }
300
371
  console.log(log_1.c.cyan(` ${devCommand(pm)}`));
301
372
  if (features.includes("openapi") || features.includes("scalar")) {
302
373
  console.log(`\n ${log_1.c.dim("API docs:")} http://localhost:4000/docs`);
@@ -6,7 +6,10 @@ export type MakeBaseOptions = {
6
6
  root?: string;
7
7
  };
8
8
  export type MakeModelOptions = MakeBaseOptions & {
9
+ /** Generate a TypeORM entity instead of a Megh ORM model. */
9
10
  orm?: boolean;
11
+ /** Table name. Defaults to the plural snake_case model name, e.g. `blog_posts`. */
12
+ table?: string;
10
13
  };
11
14
  export type MakeServiceOptions = MakeBaseOptions & {
12
15
  resource?: boolean;
@@ -16,9 +19,26 @@ export type MakeServiceOptions = MakeBaseOptions & {
16
19
  export type MakeControllerOptions = MakeServiceOptions & {
17
20
  basePath?: boolean;
18
21
  };
22
+ /**
23
+ * Create a Megh ORM model (or, with `orm`, a TypeORM entity). The model's
24
+ * columns come from the migration that creates its table, if there is one;
25
+ * otherwise it gets placeholder columns.
26
+ */
19
27
  export declare function makeModel(name: string, opts?: MakeModelOptions): string;
20
28
  export declare function makeService(name: string, opts?: MakeServiceOptions): string;
21
29
  export declare function makeController(name: string, opts?: MakeControllerOptions): string;
30
+ export type MakeResourceOptions = Pick<MakeBaseOptions, "cwd" | "force"> & {
31
+ /** Table to read the columns from when the model does not exist yet. */
32
+ table?: string;
33
+ };
34
+ /**
35
+ * `make:resource user`: a REST resource for a model. The model is reused when
36
+ * it exists, otherwise generated from the migration that creates its table;
37
+ * then its DTOs, a service with the CRUD operations, and a controller exposing
38
+ * them are written. Nothing is written if any of those files already exists
39
+ * (unless `force`), or if the model's columns cannot be found.
40
+ */
41
+ export declare function makeResource(name: string, opts?: MakeResourceOptions): string[];
22
42
  export declare function makeConfig(name: string, opts?: MakeBaseOptions): string;
23
43
  export declare function makeMiddleware(name: string, opts?: MakeBaseOptions): string;
24
44
  export declare function makeDto(name: string, opts?: MakeBaseOptions): string;