@meghjs/cli 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +10 -0
  4. package/dist/commands/build.d.ts +11 -0
  5. package/dist/commands/build.js +65 -0
  6. package/dist/commands/doctor.d.ts +10 -0
  7. package/dist/commands/doctor.js +96 -0
  8. package/dist/commands/migrate.d.ts +41 -0
  9. package/dist/commands/migrate.js +193 -0
  10. package/dist/commands/new.d.ts +24 -0
  11. package/dist/commands/new.js +377 -0
  12. package/dist/commands/route-list.d.ts +19 -0
  13. package/dist/commands/route-list.js +160 -0
  14. package/dist/commands/serve.d.ts +17 -0
  15. package/dist/commands/serve.js +238 -0
  16. package/dist/commands/start.d.ts +10 -0
  17. package/dist/commands/start.js +43 -0
  18. package/dist/compiler.d.ts +24 -0
  19. package/dist/compiler.js +83 -0
  20. package/dist/errors.d.ts +8 -0
  21. package/dist/errors.js +16 -0
  22. package/dist/generators/make.d.ts +60 -0
  23. package/dist/generators/make.js +325 -0
  24. package/dist/generators/migration-schema.d.ts +29 -0
  25. package/dist/generators/migration-schema.js +398 -0
  26. package/dist/generators/orm-model.d.ts +23 -0
  27. package/dist/generators/orm-model.js +158 -0
  28. package/dist/generators/resource.d.ts +32 -0
  29. package/dist/generators/resource.js +277 -0
  30. package/dist/index.d.ts +17 -0
  31. package/dist/index.js +42 -0
  32. package/dist/program.d.ts +22 -0
  33. package/dist/program.js +224 -0
  34. package/dist/utils/entry.d.ts +15 -0
  35. package/dist/utils/entry.js +55 -0
  36. package/dist/utils/env-types.d.ts +8 -0
  37. package/dist/utils/env-types.js +19 -0
  38. package/dist/utils/log.d.ts +25 -0
  39. package/dist/utils/log.js +39 -0
  40. package/dist/utils/names.d.ts +27 -0
  41. package/dist/utils/names.js +58 -0
  42. package/dist/utils/process.d.ts +18 -0
  43. package/dist/utils/process.js +84 -0
  44. package/dist/utils/project.d.ts +17 -0
  45. package/dist/utils/project.js +91 -0
  46. package/dist/utils/stubs.d.ts +15 -0
  47. package/dist/utils/stubs.js +52 -0
  48. package/dist/utils/tsconfig.d.ts +13 -0
  49. package/dist/utils/tsconfig.js +102 -0
  50. package/package.json +61 -4
  51. package/readme.md +155 -0
  52. package/stubs/config/config.stub +9 -0
  53. package/stubs/controllers/basic-controller.stub +9 -0
  54. package/stubs/controllers/model-controller.stub +34 -0
  55. package/stubs/controllers/resource-controller.stub +45 -0
  56. package/stubs/controllers/rest-controller.stub +29 -0
  57. package/stubs/dtos/dto.stub +11 -0
  58. package/stubs/dtos/resource-dto.stub +28 -0
  59. package/stubs/middlewares/middleware.stub +9 -0
  60. package/stubs/migrations/alter-table.stub +15 -0
  61. package/stubs/migrations/create-table.stub +15 -0
  62. package/stubs/migrations/migration.stub +11 -0
  63. package/stubs/models/entity-model.stub +16 -0
  64. package/stubs/models/orm-model-blank.stub +10 -0
  65. package/stubs/models/orm-model.stub +7 -0
  66. package/stubs/project/app-minimal.stub +7 -0
  67. package/stubs/project/app.stub +8 -0
  68. package/stubs/project/env.stub +3 -0
  69. package/stubs/project/gitignore.stub +5 -0
  70. package/stubs/project/home.controller.spec.stub +19 -0
  71. package/stubs/project/home.controller.stub +12 -0
  72. package/stubs/project/home.service.stub +8 -0
  73. package/stubs/project/openapi.config.stub +15 -0
  74. package/stubs/project/readme.stub +26 -0
  75. package/stubs/project/serve.stub +10 -0
  76. package/stubs/project/tsconfig.build.stub +4 -0
  77. package/stubs/project/tsconfig.stub +18 -0
  78. package/stubs/project/vitest-e2e.config.stub +10 -0
  79. package/stubs/project/vitest.config.stub +17 -0
  80. package/stubs/services/basic-service.stub +8 -0
  81. package/stubs/services/model-service.stub +42 -0
  82. package/stubs/services/orm-rest-service.stub +61 -0
  83. package/README.md +0 -3
@@ -0,0 +1,377 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.DATABASES = exports.FEATURES = exports.PACKAGE_MANAGERS = void 0;
40
+ exports.packageJson = packageJson;
41
+ exports.installCommand = installCommand;
42
+ exports.devCommand = devCommand;
43
+ exports.createApplication = createApplication;
44
+ const child_process_1 = require("child_process");
45
+ const fs_1 = __importDefault(require("fs"));
46
+ const path_1 = __importDefault(require("path"));
47
+ const errors_1 = require("../errors");
48
+ const log_1 = require("../utils/log");
49
+ const names_1 = require("../utils/names");
50
+ const stubs_1 = require("../utils/stubs");
51
+ const env_types_1 = require("../utils/env-types");
52
+ exports.PACKAGE_MANAGERS = ["npm", "yarn", "pnpm"];
53
+ exports.FEATURES = ["openapi", "cors", "orm", "typeorm", "knex", "scalar"];
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
+ };
69
+ /** Third-party versions for generated projects. */
70
+ const DEP_VERSIONS = {
71
+ "class-transformer": "^0.5.1",
72
+ "class-validator": "^0.14.2",
73
+ "reflect-metadata": "^0.2.2",
74
+ "@fastify/cors": "^11.0.0",
75
+ typeorm: "^0.3.20",
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",
81
+ knex: "^3.1.0",
82
+ "@scalar/fastify-api-reference": "^1.0.0",
83
+ typescript: "^5.7.2",
84
+ "@types/node": "^22.20.5",
85
+ vitest: "^4.1.12",
86
+ "@vitest/coverage-v8": "^4.1.12",
87
+ "unplugin-swc": "^2.0.0",
88
+ "@swc/core": "^1.16.20",
89
+ };
90
+ function isDirEmpty(dir) {
91
+ return fs_1.default.readdirSync(dir).length === 0;
92
+ }
93
+ function validateFeatures(features) {
94
+ const unknown = features.filter((f) => !exports.FEATURES.includes(f));
95
+ if (unknown.length) {
96
+ throw new errors_1.CliError(`Unknown feature(s): ${unknown.join(", ")}. Choose from: ${exports.FEATURES.join(", ")}.`);
97
+ }
98
+ return features;
99
+ }
100
+ async function prompt(opts) {
101
+ if (opts.pm && !exports.PACKAGE_MANAGERS.includes(opts.pm)) {
102
+ throw new errors_1.CliError(`Unknown package manager "${opts.pm}". Choose from: ${exports.PACKAGE_MANAGERS.join(", ")}.`);
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
+ }
110
+ const interactive = !opts.yes && process.stdin.isTTY === true && process.stdout.isTTY === true;
111
+ let pm = opts.pm;
112
+ let features = opts.features ? validateFeatures(opts.features) : undefined;
113
+ if (opts.minimal)
114
+ features = [];
115
+ let database = opts.database;
116
+ // --database implies the ORM.
117
+ if (database && features && !features.includes("orm"))
118
+ features = [...features, "orm"];
119
+ if (interactive && (!pm || !features)) {
120
+ const { default: inquirer } = await Promise.resolve().then(() => __importStar(require("inquirer")));
121
+ if (!pm) {
122
+ ({ pm } = await inquirer.prompt([
123
+ {
124
+ type: "list",
125
+ name: "pm",
126
+ message: "Package manager:",
127
+ choices: [...exports.PACKAGE_MANAGERS],
128
+ default: "npm",
129
+ },
130
+ ]));
131
+ }
132
+ if (!features) {
133
+ ({ features } = await inquirer.prompt([
134
+ {
135
+ type: "checkbox",
136
+ name: "features",
137
+ message: "Select features to include:",
138
+ choices: [
139
+ { name: "OpenAPI / Swagger docs", value: "openapi", checked: true },
140
+ { name: "CORS support", value: "cors" },
141
+ { name: "MeghORM: models, migrations and a query builder", value: "orm", checked: !!database },
142
+ { name: "TypeORM", value: "typeorm" },
143
+ { name: "Knex", value: "knex" },
144
+ { name: "Scalar UI (replaces Swagger UI)", value: "scalar" },
145
+ ],
146
+ },
147
+ ]));
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
+ }
165
+ }
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
+ };
172
+ }
173
+ function packageJson(name, features, minimal, database = DEFAULT_DATABASE) {
174
+ const v = (0, stubs_1.cliVersion)();
175
+ const deps = {
176
+ "@meghjs/core": (0, stubs_1.coreRange)(),
177
+ "@meghjs/cli": `^${v}`,
178
+ };
179
+ const pick = (...names) => names.forEach((n) => (deps[n] = DEP_VERSIONS[n]));
180
+ pick("class-transformer", "class-validator", "reflect-metadata");
181
+ if (features.includes("cors"))
182
+ pick("@fastify/cors");
183
+ if (usesData(features))
184
+ deps["@meghjs/data"] = `^${v}`;
185
+ if (features.includes("typeorm"))
186
+ pick("typeorm", "pg");
187
+ if (features.includes("knex"))
188
+ pick("knex", "pg");
189
+ if (features.includes("orm"))
190
+ pick(...DATABASE_SETUP[database].drivers);
191
+ if (features.includes("scalar"))
192
+ pick("@scalar/fastify-api-reference");
193
+ const devDeps = {};
194
+ const pickDev = (...names) => names.forEach((n) => (devDeps[n] = DEP_VERSIONS[n]));
195
+ pickDev("@types/node", "typescript");
196
+ if (!minimal)
197
+ pickDev("@swc/core", "@vitest/coverage-v8", "unplugin-swc", "vitest");
198
+ const scripts = {
199
+ "start:dev": "megh serve",
200
+ build: "megh build",
201
+ start: "megh start",
202
+ };
203
+ if (!minimal) {
204
+ Object.assign(scripts, {
205
+ test: "vitest run",
206
+ "test:watch": "vitest",
207
+ "test:cov": "vitest run --coverage",
208
+ "test:e2e": "vitest run --config vitest.e2e.config.mts",
209
+ });
210
+ }
211
+ const pkg = {
212
+ name: (0, names_1.kebabCase)(name) || "megh-app",
213
+ version: "0.0.1",
214
+ private: true,
215
+ description: `${(0, names_1.titleCase)(name)} API built with Megh`,
216
+ main: "dist/serve.js",
217
+ scripts,
218
+ keywords: ["megh", "nodejs", "typescript"],
219
+ engines: { node: ">=22" },
220
+ dependencies: sortKeys(deps),
221
+ devDependencies: sortKeys(devDeps),
222
+ };
223
+ return JSON.stringify(pkg, null, 2) + "\n";
224
+ }
225
+ /** TypeORM and Knex come from the @meghjs/data plugin. */
226
+ function usesData(features) {
227
+ return features.includes("typeorm") || features.includes("knex");
228
+ }
229
+ function sortKeys(obj) {
230
+ return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
231
+ }
232
+ function appSource(features) {
233
+ const imports = [];
234
+ const setup = [];
235
+ if (features.includes("openapi") || features.includes("scalar")) {
236
+ imports.push(`import { OpenApiConfig } from './config/openapi.config';`);
237
+ }
238
+ if (features.includes("cors"))
239
+ setup.push(`app.useCors({ origin: '*' });`);
240
+ if (imports.length)
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
+ }
245
+ if (features.includes("typeorm")) {
246
+ setup.push(`// TODO: pass your TypeORM DataSourceOptions (or an @AppConfig class)\n` +
247
+ `// await app.useTypeORM({ type: 'postgres', url: process.env.DATABASE_URL, entities: [] });`);
248
+ }
249
+ if (features.includes("knex")) {
250
+ setup.push(`// TODO: pass your Knex config (or an @AppConfig class)\n` +
251
+ `// await app.useKnex({ client: 'pg', connection: process.env.DATABASE_URL });`);
252
+ }
253
+ return (0, stubs_1.renderStub)("project/app.stub", {
254
+ Imports: imports.map((i) => i + "\n").join(""),
255
+ Setup: setup.map((s) => "\n" + s + "\n").join(""),
256
+ });
257
+ }
258
+ function installCommand(pm) {
259
+ return `${pm} install`;
260
+ }
261
+ function devCommand(pm) {
262
+ return pm === "npm" ? "npm run start:dev" : `${pm} start:dev`;
263
+ }
264
+ function runInstall(pm, cwd) {
265
+ return new Promise((resolve, reject) => {
266
+ const child = (0, child_process_1.spawn)(pm, ["install"], { cwd, stdio: "inherit", shell: process.platform === "win32" });
267
+ child.on("error", reject);
268
+ child.on("exit", (code) => (code === 0 ? resolve() : reject(new Error(`${pm} install exited with code ${code}`))));
269
+ });
270
+ }
271
+ async function createApplication(name, opts = {}) {
272
+ if (!name || !name.trim())
273
+ throw new errors_1.CliError("Please provide a project name, e.g. `megh new my-api`.");
274
+ const cwd = opts.cwd ?? process.cwd();
275
+ const root = path_1.default.resolve(cwd, name);
276
+ const appName = path_1.default.basename(root);
277
+ const minimal = !!opts.minimal;
278
+ if (fs_1.default.existsSync(root)) {
279
+ if (!fs_1.default.statSync(root).isDirectory())
280
+ throw new errors_1.CliError(`${root} exists and is not a directory.`);
281
+ if (!isDirEmpty(root) && !opts.force) {
282
+ throw new errors_1.CliError(`Directory ${root} is not empty. Use -f or --force to scaffold into it anyway.`);
283
+ }
284
+ }
285
+ const { pm, features, database } = await prompt(opts);
286
+ const orm = features.includes("orm") && database ? DATABASE_SETUP[database] : undefined;
287
+ console.log();
288
+ console.log(log_1.c.bold(log_1.c.cyan(" Megh")) + log_1.c.dim(` v${(0, stubs_1.cliVersion)()}`));
289
+ console.log(` ${log_1.c.dim("Creating project:")} ${log_1.c.bold(appName)}${minimal ? log_1.c.dim(" (minimal)") : ""}`);
290
+ const rel = (f) => path_1.default.relative(cwd, f) || ".";
291
+ const files = [];
292
+ const add = (file, content) => files.push([path_1.default.join(root, file), content]);
293
+ if (minimal) {
294
+ add("src/app.ts", (0, stubs_1.renderStub)("project/app-minimal.stub"));
295
+ }
296
+ else {
297
+ add("src/services/home.service.ts", (0, stubs_1.renderStub)("project/home.service.stub"));
298
+ add("src/controllers/home.controller.ts", (0, stubs_1.renderStub)("project/home.controller.stub"));
299
+ add("src/controllers/home.controller.spec.ts", (0, stubs_1.renderStub)("project/home.controller.spec.stub"));
300
+ if (features.includes("openapi") || features.includes("scalar")) {
301
+ add("src/config/openapi.config.ts", (0, stubs_1.renderStub)("project/openapi.config.stub", {
302
+ AppTitle: (0, names_1.titleCase)(appName) || appName,
303
+ Provider: features.includes("scalar") ? "\n provider: 'scalar'," : "",
304
+ }));
305
+ }
306
+ add("src/app.ts", appSource(features));
307
+ add("vitest.config.mts", (0, stubs_1.renderStub)("project/vitest.config.stub"));
308
+ add("vitest.e2e.config.mts", (0, stubs_1.renderStub)("project/vitest-e2e.config.stub"));
309
+ }
310
+ add("src/serve.ts", (0, stubs_1.renderStub)("project/serve.stub"));
311
+ add("package.json", packageJson(appName, features, minimal, database));
312
+ add("tsconfig.json", (0, stubs_1.renderStub)("project/tsconfig.stub"));
313
+ add(env_types_1.ENV_TYPES_FILE, (0, env_types_1.envTypesFile)(usesData(features) ? ["@meghjs/data"] : []));
314
+ add("tsconfig.build.json", (0, stubs_1.renderStub)("project/tsconfig.build.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);
326
+ add("README.md", (0, stubs_1.renderStub)("project/readme.stub", {
327
+ AppTitle: (0, names_1.titleCase)(appName) || appName,
328
+ InstallCmd: installCommand(pm),
329
+ DevCmd: devCommand(pm),
330
+ TestRow: minimal ? "" : "| `test` | Run unit tests |\n",
331
+ Tree: minimal
332
+ ? ""
333
+ : "├── controllers/ # Route controllers\n├── services/ # Business logic\n├── config/ # App configuration\n",
334
+ }));
335
+ log_1.log.section("Generating files");
336
+ for (const [file, content] of files) {
337
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
338
+ fs_1.default.writeFileSync(file, content, "utf8");
339
+ log_1.log.step(path_1.default.relative(root, file).split(path_1.default.sep).join("/"), "");
340
+ }
341
+ if (!minimal)
342
+ fs_1.default.mkdirSync(path_1.default.join(root, "public"), { recursive: true });
343
+ const skipInstall = opts.skipInstall || process.env.MEGH_SKIP_INSTALL === "1";
344
+ if (skipInstall) {
345
+ log_1.log.section("Skipping dependency install");
346
+ }
347
+ else {
348
+ log_1.log.section(`Installing dependencies (${pm})`);
349
+ try {
350
+ await runInstall(pm, root);
351
+ log_1.log.success("Dependencies installed");
352
+ }
353
+ catch (err) {
354
+ log_1.log.error(`Install failed: ${err instanceof Error ? err.message : err}`);
355
+ log_1.log.info(` Run it manually: cd ${rel(root)} && ${installCommand(pm)}`);
356
+ }
357
+ }
358
+ console.log();
359
+ log_1.log.success(log_1.c.green("Project created."));
360
+ console.log(`\n ${log_1.c.dim("Next steps:")}`);
361
+ if (rel(root) !== ".")
362
+ console.log(log_1.c.cyan(` cd ${rel(root)}`));
363
+ if (skipInstall)
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
+ }
371
+ console.log(log_1.c.cyan(` ${devCommand(pm)}`));
372
+ if (features.includes("openapi") || features.includes("scalar")) {
373
+ console.log(`\n ${log_1.c.dim("API docs:")} http://localhost:4000/docs`);
374
+ }
375
+ console.log();
376
+ return root;
377
+ }
@@ -0,0 +1,19 @@
1
+ export type Route = {
2
+ method: string;
3
+ path: string;
4
+ controller: string;
5
+ handler: string;
6
+ file: string;
7
+ };
8
+ export type RouteListOptions = {
9
+ cwd?: string;
10
+ json?: boolean;
11
+ static?: boolean;
12
+ };
13
+ export declare function joinRoute(...parts: string[]): string;
14
+ export declare function runtimeRoutes(root: string): Route[];
15
+ /** Scan `@ApiController` classes and their `@Get`/`@Post`/... methods without running any code. */
16
+ export declare function scanRoutes(source: string, file: string): Route[];
17
+ export declare function staticRoutes(root: string): Route[];
18
+ export declare function formatRoutes(routes: Route[]): string;
19
+ export declare function routeList(opts?: RouteListOptions): Route[];
@@ -0,0 +1,160 @@
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.joinRoute = joinRoute;
7
+ exports.runtimeRoutes = runtimeRoutes;
8
+ exports.scanRoutes = scanRoutes;
9
+ exports.staticRoutes = staticRoutes;
10
+ exports.formatRoutes = formatRoutes;
11
+ exports.routeList = routeList;
12
+ const child_process_1 = require("child_process");
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const compiler_1 = require("../compiler");
16
+ const errors_1 = require("../errors");
17
+ const entry_1 = require("../utils/entry");
18
+ const log_1 = require("../utils/log");
19
+ const project_1 = require("../utils/project");
20
+ function joinRoute(...parts) {
21
+ const joined = "/" + parts.join("/");
22
+ const normalized = joined.replace(/\/{2,}/g, "/");
23
+ return normalized.length > 1 ? normalized.replace(/\/$/, "") : normalized;
24
+ }
25
+ function controllerFiles(srcDir) {
26
+ if (!fs_1.default.existsSync(srcDir))
27
+ return [];
28
+ return fs_1.default
29
+ .readdirSync(srcDir, { withFileTypes: true, recursive: true })
30
+ .filter((e) => e.isFile() && e.name.endsWith(".controller.ts"))
31
+ .map((e) => path_1.default.join(e.parentPath ?? e.path, e.name))
32
+ .sort();
33
+ }
34
+ // ── Runtime: compile, require, read Megh's route metadata ───────────────
35
+ const MARKER = "__MEGH_ROUTES__";
36
+ /**
37
+ * Runs in a child process (so the app's import side effects cannot affect the
38
+ * CLI). Requires each compiled controller and reads the metadata written by
39
+ * `@ApiController` (symbol "icontroller:options") and `@Get`/`@Post`/...
40
+ * ("route:method", "route:path").
41
+ */
42
+ const WORKER = `
43
+ const files = JSON.parse(process.argv[process.argv.length - 1]);
44
+ const out = [];
45
+ const errors = [];
46
+ for (const [src, compiled] of files) {
47
+ let mod;
48
+ try { mod = require(compiled); } catch (e) { errors.push(src + ": " + (e && e.message || e)); continue; }
49
+ if (typeof Reflect.getOwnMetadataKeys !== "function") {
50
+ errors.push("reflect-metadata is not loaded; is @meghjs/core installed?");
51
+ break;
52
+ }
53
+ for (const value of Object.values(mod)) {
54
+ if (typeof value !== "function") continue;
55
+ const key = Reflect.getOwnMetadataKeys(value).find(
56
+ (k) => typeof k === "symbol" && k.description === "icontroller:options");
57
+ if (!key) continue;
58
+ const meta = Reflect.getOwnMetadata(key, value) || {};
59
+ const proto = value.prototype;
60
+ for (const name of Object.getOwnPropertyNames(proto)) {
61
+ if (name === "constructor") continue;
62
+ const method = Reflect.getMetadata("route:method", proto, name);
63
+ if (!method) continue;
64
+ out.push({ controllerPath: meta.path || "/", method, path: Reflect.getMetadata("route:path", proto, name) || "/",
65
+ controller: value.name, handler: name, file: src });
66
+ }
67
+ }
68
+ }
69
+ console.log(${JSON.stringify(MARKER)} + JSON.stringify({ routes: out, errors }));
70
+ process.exit(0);
71
+ `;
72
+ function runtimeRoutes(root) {
73
+ const layout = (0, entry_1.projectLayout)(root);
74
+ const cacheDir = path_1.default.join(root, "node_modules", ".cache", "megh", "route-list");
75
+ fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
76
+ const compiler = new compiler_1.SwcCompiler(layout.srcDir, cacheDir, layout.compilerOptions);
77
+ const failures = compiler.compileAll();
78
+ if (failures.size) {
79
+ const list = [...failures].map(([f, e]) => `${path_1.default.relative(root, f)}: ${e.split("\n")[0]}`).join("\n ");
80
+ throw new errors_1.CliError(`Compilation failed:\n ${list}`);
81
+ }
82
+ const files = controllerFiles(layout.srcDir).map((f) => [path_1.default.relative(root, f), compiler.outFileFor(f)]);
83
+ if (!files.length)
84
+ return [];
85
+ const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify(files)], {
86
+ cwd: root,
87
+ encoding: "utf8",
88
+ env: { ...process.env, NODE_ENV: process.env.NODE_ENV ?? "development" },
89
+ maxBuffer: 64 * 1024 * 1024,
90
+ });
91
+ const line = (result.stdout ?? "").split(/\r?\n/).find((l) => l.startsWith(MARKER));
92
+ if (!line) {
93
+ throw new errors_1.CliError(`Could not load controllers:\n${result.stderr || result.stdout || result.error?.message}`);
94
+ }
95
+ const { routes, errors } = JSON.parse(line.slice(MARKER.length));
96
+ if (errors.length) {
97
+ throw new errors_1.CliError(`Could not load controllers:\n ${errors.join("\n ")}\nTry --static to scan the source instead.`);
98
+ }
99
+ return routes.map((r) => ({
100
+ method: String(r.method).toUpperCase(),
101
+ path: joinRoute(r.controllerPath, r.path),
102
+ controller: r.controller,
103
+ handler: r.handler,
104
+ file: r.file.split(path_1.default.sep).join("/"),
105
+ }));
106
+ }
107
+ // ── Static: scan decorators in the source ─────────────────────────────────
108
+ const STRING = /^\s*(['"`])((?:(?!\1).)*)\1/;
109
+ function decoratorPath(args) {
110
+ if (!args)
111
+ return "/";
112
+ const literal = args.match(STRING);
113
+ if (literal)
114
+ return literal[2] || "/";
115
+ const objPath = args.match(/path\s*:\s*(['"`])((?:(?!\1).)*)\1/);
116
+ return objPath ? objPath[2] : "/";
117
+ }
118
+ /** Scan `@ApiController` classes and their `@Get`/`@Post`/... methods without running any code. */
119
+ function scanRoutes(source, file) {
120
+ const routes = [];
121
+ const ctrlRe = /@ApiController\b(?:\s*\(([^)]*)\))?[\s\S]*?\bclass\s+([A-Za-z_$][\w$]*)/g;
122
+ const ctrls = [...source.matchAll(ctrlRe)];
123
+ ctrls.forEach((m, i) => {
124
+ const start = m.index + m[0].length;
125
+ const end = i + 1 < ctrls.length ? ctrls[i + 1].index : source.length;
126
+ const body = source.slice(start, end);
127
+ const base = decoratorPath(m[1]);
128
+ const methodRe = /@(Get|Post|Put|Patch|Delete|Options|All)\s*\(([^)]*)\)[\s\S]*?(?<![@\w$])([A-Za-z_$][\w$]*)\s*\(/g;
129
+ for (const r of body.matchAll(methodRe)) {
130
+ routes.push({
131
+ method: r[1].toUpperCase(),
132
+ path: joinRoute(base, decoratorPath(r[2])),
133
+ controller: m[2],
134
+ handler: r[3],
135
+ file,
136
+ });
137
+ }
138
+ });
139
+ return routes;
140
+ }
141
+ function staticRoutes(root) {
142
+ const layout = (0, entry_1.projectLayout)(root);
143
+ return controllerFiles(layout.srcDir).flatMap((f) => scanRoutes(fs_1.default.readFileSync(f, "utf8"), path_1.default.relative(root, f).split(path_1.default.sep).join("/")));
144
+ }
145
+ // ── Command ───────────────────────────────────────────────────────────────
146
+ function formatRoutes(routes) {
147
+ if (!routes.length)
148
+ return "No routes found.";
149
+ const rows = routes.map((r) => [r.method, r.path, `${r.controller}.${r.handler}`]);
150
+ const head = ["METHOD", "PATH", "HANDLER"];
151
+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
152
+ const fmt = (row) => row.map((cell, i) => cell.padEnd(widths[i])).join(" ").trimEnd();
153
+ return [log_1.c.bold(fmt(head)), ...rows.map(fmt)].join("\n");
154
+ }
155
+ function routeList(opts = {}) {
156
+ const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
157
+ const routes = (opts.static ? staticRoutes(root) : runtimeRoutes(root)).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));
158
+ console.log(opts.json ? JSON.stringify(routes, null, 2) : formatRoutes(routes));
159
+ return routes;
160
+ }
@@ -0,0 +1,17 @@
1
+ export type ServeOptions = {
2
+ cwd?: string;
3
+ /** Entry file (relative to the project root), overriding package.json. */
4
+ entry?: string;
5
+ /** Run `tsc --noEmit --watch` alongside the server. Default true. */
6
+ typeCheck?: boolean;
7
+ /** Milliseconds to wait for more file events before rebuilding. Default 200. */
8
+ debounce?: number;
9
+ };
10
+ /**
11
+ * Development server: transpiles `src/` with SWC into the output dir, copies
12
+ * assets, runs the entry file, and restarts it on changes to sources, assets
13
+ * or `.env*` files. Type errors are reported by a parallel `tsc --watch` and
14
+ * never block a reload; syntax errors do, and stop the running app so stale
15
+ * JS never keeps serving.
16
+ */
17
+ export declare function serve(opts?: ServeOptions): Promise<void>;