@meghjs/cli 0.5.2 → 0.5.4

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 (61) hide show
  1. package/dist/commands/migrate.d.ts +23 -5
  2. package/dist/commands/migrate.js +44 -6
  3. package/dist/commands/new.js +7 -1
  4. package/dist/generators/auth-files.d.ts +37 -0
  5. package/dist/generators/auth-files.js +198 -0
  6. package/dist/generators/auth.d.ts +26 -0
  7. package/dist/generators/auth.js +542 -0
  8. package/dist/generators/factory.d.ts +25 -0
  9. package/dist/generators/factory.js +159 -0
  10. package/dist/generators/make.d.ts +38 -0
  11. package/dist/generators/make.js +176 -0
  12. package/dist/generators/migration-schema.d.ts +5 -0
  13. package/dist/generators/migration-schema.js +25 -2
  14. package/dist/generators/orm-model.d.ts +6 -1
  15. package/dist/generators/orm-model.js +31 -2
  16. package/dist/generators/resource.d.ts +21 -0
  17. package/dist/generators/resource.js +17 -3
  18. package/dist/generators/scaffold.d.ts +76 -0
  19. package/dist/generators/scaffold.js +353 -0
  20. package/dist/generators/update-model.d.ts +21 -0
  21. package/dist/generators/update-model.js +129 -0
  22. package/dist/program.js +175 -6
  23. package/dist/templates/cascade.d.ts +37 -0
  24. package/dist/templates/cascade.js +87 -0
  25. package/dist/templates/catalog/common.d.ts +1 -0
  26. package/dist/templates/catalog/common.js +63 -0
  27. package/dist/templates/catalog/construction.d.ts +1 -0
  28. package/dist/templates/catalog/construction.js +138 -0
  29. package/dist/templates/catalog/crm.d.ts +1 -0
  30. package/dist/templates/catalog/crm.js +81 -0
  31. package/dist/templates/catalog/ecommerce.d.ts +1 -0
  32. package/dist/templates/catalog/ecommerce.js +143 -0
  33. package/dist/templates/catalog/education.d.ts +1 -0
  34. package/dist/templates/catalog/education.js +80 -0
  35. package/dist/templates/catalog/hr.d.ts +1 -0
  36. package/dist/templates/catalog/hr.js +83 -0
  37. package/dist/templates/catalog/logistics.d.ts +1 -0
  38. package/dist/templates/catalog/logistics.js +60 -0
  39. package/dist/templates/catalog/marketing.d.ts +1 -0
  40. package/dist/templates/catalog/marketing.js +104 -0
  41. package/dist/templates/catalog/medical.d.ts +1 -0
  42. package/dist/templates/catalog/medical.js +147 -0
  43. package/dist/templates/catalog/pos.d.ts +1 -0
  44. package/dist/templates/catalog/pos.js +110 -0
  45. package/dist/templates/catalog/real-estate.d.ts +1 -0
  46. package/dist/templates/catalog/real-estate.js +171 -0
  47. package/dist/templates/fields.d.ts +64 -0
  48. package/dist/templates/fields.js +331 -0
  49. package/dist/templates/index.d.ts +27 -0
  50. package/dist/templates/index.js +175 -0
  51. package/dist/templates/migration.d.ts +7 -0
  52. package/dist/templates/migration.js +80 -0
  53. package/dist/templates/template.d.ts +37 -0
  54. package/dist/templates/template.js +36 -0
  55. package/dist/utils/dialect.d.ts +8 -0
  56. package/dist/utils/dialect.js +57 -0
  57. package/package.json +17 -5
  58. package/readme.md +30 -1
  59. package/stubs/controllers/model-controller.stub +10 -1
  60. package/stubs/seeders/database-seeder.stub +8 -0
  61. package/stubs/seeders/seeder.stub +10 -0
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fakeValue = fakeValue;
4
+ exports.renderFactory = renderFactory;
5
+ const has = (name, pattern) => pattern.test(name);
6
+ /** A Faker expression for a column, or `undefined` when none fits. */
7
+ function fakeValue(field, model) {
8
+ const name = field.name.toLowerCase();
9
+ const sql = (field.sqlType ?? "").toLowerCase();
10
+ const length = Number(sql.match(/^n?(?:var)?char\((\d+)\)/)?.[1]) || undefined;
11
+ if (field.ts === "boolean")
12
+ return "faker.datatype.boolean()";
13
+ if (field.ts === "Date") {
14
+ if (has(name, /birth|born|dob/))
15
+ return "faker.date.birthdate()";
16
+ if (has(name, /expire|expiry|due|until|ends?_|deadline|scheduled/))
17
+ return "faker.date.future()";
18
+ return "faker.date.recent()";
19
+ }
20
+ if (field.ts === "number") {
21
+ if (has(name, /price|amount|cost|total|balance|credit|debit|salary|fee|rate|latitude|longitude/) ||
22
+ /^(decimal|numeric|real|float|double|money)/.test(sql)) {
23
+ if (has(name, /latitude/))
24
+ return "faker.location.latitude()";
25
+ if (has(name, /longitude/))
26
+ return "faker.location.longitude()";
27
+ return "faker.number.float({ min: 0, max: 1000, fractionDigits: 2 })";
28
+ }
29
+ if (has(name, /(^|_)age$/))
30
+ return "faker.number.int({ min: 18, max: 90 })";
31
+ if (has(name, /year/))
32
+ return "faker.date.past({ years: 30 }).getFullYear()";
33
+ if (has(name, /quantity|qty|count|stock/))
34
+ return "faker.number.int({ min: 0, max: 100 })";
35
+ return "faker.number.int({ min: 1, max: 1000 })";
36
+ }
37
+ if (field.ts === "string") {
38
+ const value = fakeString(name, sql, length, model);
39
+ // Keep values within a short varchar(n): faker's can run longer.
40
+ const fixed = /^faker\.string\.(uuid|alphanumeric)\(/.test(value);
41
+ return length !== undefined && length < 60 && !fixed ? `${value}.slice(0, ${length})` : value;
42
+ }
43
+ if (field.ts.startsWith("Record<") || field.ts === "object")
44
+ return "{}";
45
+ return undefined;
46
+ }
47
+ function fakeString(name, sql, length, model) {
48
+ {
49
+ if (has(name, /email/))
50
+ return "faker.internet.email()";
51
+ if (has(name, /^first_?name$/))
52
+ return "faker.person.firstName()";
53
+ if (has(name, /^last_?name$|surname/))
54
+ return "faker.person.lastName()";
55
+ if (has(name, /user_?name|login|handle/))
56
+ return "faker.internet.username()";
57
+ if (has(name, /password|secret/))
58
+ return "faker.internet.password()";
59
+ if (has(name, /phone|mobile|tel/))
60
+ return 'faker.phone.number({ style: "international" })';
61
+ if (has(name, /uuid|guid/) || sql === "uuid" || sql === "uniqueidentifier")
62
+ return "faker.string.uuid()";
63
+ if (has(name, /avatar/))
64
+ return "faker.image.avatar()";
65
+ if (has(name, /image|photo|picture|thumbnail/))
66
+ return "faker.image.url()";
67
+ if (has(name, /url|website|link|homepage/))
68
+ return "faker.internet.url()";
69
+ if (has(name, /slug/))
70
+ return "faker.lorem.slug()";
71
+ if (has(name, /street|address/))
72
+ return "faker.location.streetAddress()";
73
+ if (has(name, /city|town/))
74
+ return "faker.location.city()";
75
+ if (has(name, /country/))
76
+ return "faker.location.country()";
77
+ if (has(name, /zip|postal|postcode/))
78
+ return "faker.location.zipCode()";
79
+ if (has(name, /company|organi[sz]ation|employer/))
80
+ return "faker.company.name()";
81
+ if (has(name, /job|position|occupation/))
82
+ return "faker.person.jobTitle()";
83
+ if (has(name, /color|colour/))
84
+ return "faker.color.human()";
85
+ if (has(name, /currency/))
86
+ return "faker.finance.currencyCode()";
87
+ if (has(name, /(^|_)ip(_|$)|ip_?address/))
88
+ return "faker.internet.ip()";
89
+ if (has(name, /(^|_)(code|sku|reference|ref)$/)) {
90
+ return `faker.string.alphanumeric(${Math.min(length ?? 8, 8)}).toUpperCase()`;
91
+ }
92
+ if (has(name, /title|subject|headline/))
93
+ return "faker.lorem.sentence()";
94
+ if (has(name, /description|body|content|bio|about|text|notes?|summary|message|comment/) ||
95
+ /^(n?text|longtext|mediumtext)$/.test(sql)) {
96
+ return "faker.lorem.paragraph()";
97
+ }
98
+ if (has(name, /(^|_)name$/) || name === "name")
99
+ return nameFor(model);
100
+ if (length !== undefined && length < 24)
101
+ return `faker.string.alphanumeric(${Math.min(length, 10)})`;
102
+ return "faker.lorem.words(3)";
103
+ }
104
+ }
105
+ /** `name` means a person on a user, a word on a role, a product on a product… */
106
+ function nameFor(model) {
107
+ const m = model.toLowerCase();
108
+ if (/role|category|tag|group|team|permission|status|type|label/.test(m))
109
+ return "faker.word.noun()";
110
+ if (/product|item|article|good/.test(m))
111
+ return "faker.commerce.productName()";
112
+ if (/company|organi[sz]ation|account|vendor|supplier|tenant|brand/.test(m))
113
+ return "faker.company.name()";
114
+ if (/city|town/.test(m))
115
+ return "faker.location.city()";
116
+ if (/country/.test(m))
117
+ return "faker.location.country()";
118
+ return "faker.person.fullName()";
119
+ }
120
+ const key = (name) => (/^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name));
121
+ function renderFactory(opts) {
122
+ const fk = new Map(opts.foreignKeys.map((f) => [f.column, f]));
123
+ const lines = [];
124
+ const imports = new Map(); // factory → import path
125
+ for (const field of opts.fields) {
126
+ const foreign = fk.get(field.name);
127
+ if (foreign) {
128
+ if (foreign.factory) {
129
+ lines.push(`${key(field.name)}: ${foreign.factory},`);
130
+ imports.set(foreign.factory, foreign.factoryImport);
131
+ }
132
+ else if (field.nullable) {
133
+ lines.push(`${key(field.name)}: null,`);
134
+ }
135
+ else {
136
+ lines.push(`// ${key(field.name)}: ${pascal(foreign.model)}Factory, (create it: megh make:factory ${foreign.model})`);
137
+ }
138
+ continue;
139
+ }
140
+ const value = fakeValue(field, opts.model);
141
+ if (value)
142
+ lines.push(`${key(field.name)}: ${value},`);
143
+ else
144
+ lines.push(`// ${key(field.name)}: set a value (no fake value fits ${field.ts}),`);
145
+ }
146
+ const usesFaker = lines.some((l) => !l.startsWith("//") && l.includes("faker."));
147
+ const header = [
148
+ `import { defineFactory } from "@meghjs/core";`,
149
+ `import { ${opts.model} } from "${opts.modelImport}";`,
150
+ ...[...imports].map(([name, from]) => `import { ${name} } from "${from}";`),
151
+ ];
152
+ return (header.join("\n") +
153
+ "\n\n" +
154
+ `export const ${opts.model}Factory = defineFactory(${opts.model}, (${usesFaker ? "{ faker }" : ""}) => ({\n` +
155
+ lines.map((l) => ` ${l}`).join("\n") +
156
+ (lines.length ? "\n" : "") +
157
+ `}));\n`);
158
+ }
159
+ const pascal = (snake) => snake.replace(/(^|_)(\w)/g, (_, __, c) => c.toUpperCase());
@@ -1,3 +1,4 @@
1
+ import { type ModelChanges } from "./update-model";
1
2
  export type MakeBaseOptions = {
2
3
  /** Directory to start the project-root search from. Defaults to `process.cwd()`. */
3
4
  cwd?: string;
@@ -19,12 +20,34 @@ export type MakeServiceOptions = MakeBaseOptions & {
19
20
  export type MakeControllerOptions = MakeServiceOptions & {
20
21
  basePath?: boolean;
21
22
  };
23
+ /** Files `make:model` / `make:resource` / `make:factory` write for model `name`. */
24
+ export declare function generatedFiles(projectRoot: string, name: string): {
25
+ model: string;
26
+ dto: string;
27
+ service: string;
28
+ controller: string;
29
+ factory: string;
30
+ };
22
31
  /**
23
32
  * Create a Megh ORM model (or, with `orm`, a TypeORM entity). The model's
24
33
  * columns come from the migration that creates its table, if there is one;
25
34
  * otherwise it gets placeholder columns.
26
35
  */
27
36
  export declare function makeModel(name: string, opts?: MakeModelOptions): string;
37
+ export type UpdateModelOptions = Pick<MakeBaseOptions, "cwd" | "root"> & {
38
+ /** Table to read (default: the model's `@Table`, else the plural snake_case name). */
39
+ table?: string;
40
+ /** Also rewrite the model's DTO file from the updated columns. */
41
+ dto?: boolean;
42
+ /** Report the changes without writing anything. */
43
+ dryRun?: boolean;
44
+ };
45
+ /**
46
+ * `update:model user`: sync an existing model's column fields with its table
47
+ * as the migrations now leave it (after an alter-table migration, say). Only
48
+ * the column declarations change; relations, methods and other code stay.
49
+ */
50
+ export declare function updateModel(name: string, opts?: UpdateModelOptions): ModelChanges;
28
51
  export declare function makeService(name: string, opts?: MakeServiceOptions): string;
29
52
  export declare function makeController(name: string, opts?: MakeControllerOptions): string;
30
53
  export type MakeResourceOptions = Pick<MakeBaseOptions, "cwd" | "force"> & {
@@ -58,3 +81,18 @@ export declare function migrationTimestamp(date?: Date): string;
58
81
  * remove/drop/alter/change/update) an alter-table one, anything else a blank one.
59
82
  */
60
83
  export declare function makeMigration(name: string, opts?: MakeMigrationOptions): string;
84
+ export type MakeSeederOptions = Pick<MakeBaseOptions, "cwd" | "force">;
85
+ /**
86
+ * Create `<seeders>/<name>.seeder.ts`. `make:seeder database` writes the
87
+ * entry seeder that `db:seed` runs, calling the seeders that already exist.
88
+ */
89
+ export declare function makeSeeder(name: string, opts?: MakeSeederOptions): string;
90
+ /** The `database` seeder, calling `others` in order. */
91
+ export declare function renderEntrySeeder(others: string[]): string;
92
+ export type MakeFactoryOptions = Pick<MakeBaseOptions, "cwd" | "force">;
93
+ /**
94
+ * `make:factory user`: `<factories>/user.factory.ts` exporting `UserFactory`,
95
+ * with a Faker value for each of the model's columns. Foreign keys use the
96
+ * related model's factory when it exists.
97
+ */
98
+ export declare function makeFactory(name: string, opts?: MakeFactoryOptions): string;
@@ -3,7 +3,9 @@ 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.generatedFiles = generatedFiles;
6
7
  exports.makeModel = makeModel;
8
+ exports.updateModel = updateModel;
7
9
  exports.makeService = makeService;
8
10
  exports.makeController = makeController;
9
11
  exports.makeResource = makeResource;
@@ -12,6 +14,9 @@ exports.makeMiddleware = makeMiddleware;
12
14
  exports.makeDto = makeDto;
13
15
  exports.migrationTimestamp = migrationTimestamp;
14
16
  exports.makeMigration = makeMigration;
17
+ exports.makeSeeder = makeSeeder;
18
+ exports.renderEntrySeeder = renderEntrySeeder;
19
+ exports.makeFactory = makeFactory;
15
20
  const fs_1 = __importDefault(require("fs"));
16
21
  const path_1 = __importDefault(require("path"));
17
22
  const errors_1 = require("../errors");
@@ -23,6 +28,8 @@ const migrate_1 = require("../commands/migrate");
23
28
  const migration_schema_1 = require("./migration-schema");
24
29
  const orm_model_1 = require("./orm-model");
25
30
  const resource_1 = require("./resource");
31
+ const update_model_1 = require("./update-model");
32
+ const factory_1 = require("./factory");
26
33
  const DEFAULT_DIRS = {
27
34
  model: "models",
28
35
  service: "services",
@@ -37,6 +44,17 @@ function targetDir(projectRoot, kind, dirs, root) {
37
44
  throw new errors_1.CliError(`Invalid --root "${root}".`);
38
45
  return path_1.default.join(projectRoot, "src", ...folder, ...dirs);
39
46
  }
47
+ /** Files `make:model` / `make:resource` / `make:factory` write for model `name`. */
48
+ function generatedFiles(projectRoot, name) {
49
+ const n = (0, names_1.resolveName)(name, "Model");
50
+ return {
51
+ model: path_1.default.join(targetDir(projectRoot, "model", n.dirs), `${n.fileBase}.model.ts`),
52
+ dto: path_1.default.join(targetDir(projectRoot, "dto", n.dirs), `${n.fileBase}.dto.ts`),
53
+ service: path_1.default.join(targetDir(projectRoot, "service", n.dirs), `${n.fileBase}.service.ts`),
54
+ controller: path_1.default.join(targetDir(projectRoot, "controller", n.dirs), `${n.fileBase}.controller.ts`),
55
+ factory: path_1.default.join((0, migrate_1.databasePaths)(projectRoot).factories, ...n.dirs, `${n.fileBase}.factory.ts`),
56
+ };
57
+ }
40
58
  /** A relative module specifier from `fromFile` to `toFile` (without extension), always using `/`. */
41
59
  function importPath(fromFile, toFile) {
42
60
  let rel = path_1.default.relative(path_1.default.dirname(fromFile), toFile).replace(/\.ts$/, "").split(path_1.default.sep).join("/");
@@ -89,6 +107,71 @@ function makeModel(name, opts = {}) {
89
107
  }
90
108
  return file;
91
109
  }
110
+ /**
111
+ * `update:model user`: sync an existing model's column fields with its table
112
+ * as the migrations now leave it (after an alter-table migration, say). Only
113
+ * the column declarations change; relations, methods and other code stay.
114
+ */
115
+ function updateModel(name, opts = {}) {
116
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
117
+ const n = (0, names_1.resolveName)(name, "Model");
118
+ const file = path_1.default.join(targetDir(projectRoot, "model", n.dirs, opts.root), `${n.fileBase}.model.ts`);
119
+ const rel = (p) => relPath(projectRoot, p);
120
+ if (!fs_1.default.existsSync(file)) {
121
+ throw new errors_1.CliError(`There is no ${n.base} model (${rel(file)}). Create it: megh make:model ${name}`);
122
+ }
123
+ const source = fs_1.default.readFileSync(file, "utf8");
124
+ if (/@Entity\s*\(/.test(source)) {
125
+ throw new errors_1.CliError(`${rel(file)} is a TypeORM entity; update:model only updates Megh ORM models.`);
126
+ }
127
+ if (!/@Table\s*\(/.test(source)) {
128
+ throw new errors_1.CliError(`${rel(file)} declares its columns without decorators (static table/casts), which update:model ` +
129
+ `can't edit safely. Regenerate it with: megh make:model ${name} --force (then re-add relations and methods).`);
130
+ }
131
+ const { migrations } = (0, migrate_1.databasePaths)(projectRoot);
132
+ const snake = (0, names_1.snakeCase)(n.base);
133
+ const declared = source.match(/@Table\s*\(\s*["'`]([^"'`]+)["'`]/)?.[1];
134
+ const candidates = opts.table ? [opts.table] : [declared, (0, orm_model_1.pluralize)(snake), snake].filter((t) => !!t);
135
+ const tables = (0, migration_schema_1.readMigrationSchema)(migrations);
136
+ const table = candidates.map((t) => tables.get(t)).find((t) => t !== undefined);
137
+ if (!table) {
138
+ throw new errors_1.CliError(`No migration in ${rel(migrations)} creates the "${candidates[0]}" table, so there is nothing to sync. ` +
139
+ `Pass the table with --table if it has another name.`);
140
+ }
141
+ const result = (0, update_model_1.syncModelSource)(source, table);
142
+ const { added, removed, updated, kept } = result.changes;
143
+ const changed = result.source !== source;
144
+ const prefix = opts.dryRun ? "Would update" : "Model updated";
145
+ if (!changed) {
146
+ log_1.log.info(`${rel(file)} already matches the "${table.name}" table.`);
147
+ }
148
+ else {
149
+ if (!opts.dryRun)
150
+ fs_1.default.writeFileSync(file, result.source, "utf8");
151
+ log_1.log.success(`${prefix}: ${rel(file)}`);
152
+ }
153
+ for (const c of added)
154
+ log_1.log.info(` + ${c}`);
155
+ for (const c of removed)
156
+ log_1.log.info(` - ${c}`);
157
+ for (const c of updated)
158
+ log_1.log.info(` ~ ${c}`);
159
+ for (const c of kept) {
160
+ log_1.log.warn(` ${c} has hand-made changes, so it was kept as written; check it against the migration.`);
161
+ }
162
+ const dtoFile = path_1.default.join(targetDir(projectRoot, "dto", n.dirs), `${n.fileBase}.dto.ts`);
163
+ if (opts.dto) {
164
+ const model = { name: n, file, schema: (0, resource_1.readModelSchema)(result.source, table), typeorm: false };
165
+ if (opts.dryRun)
166
+ log_1.log.info(` Would rewrite ${rel(dtoFile)}`);
167
+ else
168
+ write(dtoFile, renderDtoFor(model), true, "DTO", projectRoot);
169
+ }
170
+ else if (changed && fs_1.default.existsSync(dtoFile)) {
171
+ log_1.log.info(` ${rel(dtoFile)} may be out of date: rerun with --dto to rewrite it.`);
172
+ }
173
+ return result.changes;
174
+ }
92
175
  function renderEntityModel(model) {
93
176
  return (0, stubs_1.renderStub)("models/entity-model.stub", { Model: model, table: (0, names_1.snakeCase)(model) });
94
177
  }
@@ -161,6 +244,7 @@ function renderResourceController(model, controllerFile, className, route, servi
161
244
  const numeric = model.schema.primaryKeyType === "number";
162
245
  return (0, stubs_1.renderStub)("controllers/model-controller.stub", {
163
246
  ...vars,
247
+ modelImport: importPath(controllerFile, model.file),
164
248
  Plural: (0, names_1.pascalCase)((0, orm_model_1.pluralize)((0, names_1.snakeCase)(m.base))),
165
249
  dtoImport: importPath(controllerFile, dtoFile),
166
250
  primaryKeyType: numeric ? "number" : "string",
@@ -323,3 +407,95 @@ function makeMigration(name, opts = {}) {
323
407
  const file = path_1.default.join(migrations, `${migrationTimestamp(opts.now)}_${snake}.ts`);
324
408
  return write(file, content, opts.force, "Migration", projectRoot);
325
409
  }
410
+ /**
411
+ * Create `<seeders>/<name>.seeder.ts`. `make:seeder database` writes the
412
+ * entry seeder that `db:seed` runs, calling the seeders that already exist.
413
+ */
414
+ function makeSeeder(name, opts = {}) {
415
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
416
+ if (/[\/]/.test(name))
417
+ throw new errors_1.CliError(`Seeders live in one folder: use a plain name, not "${name}".`);
418
+ // `UserSeeder`, `user_seeder` and `users` all name the file after the table.
419
+ const snake = (0, names_1.snakeCase)(name.replace(/[-_]?seeder$/i, ""));
420
+ if (!snake)
421
+ throw new errors_1.CliError(`Invalid seeder name "${name}".`);
422
+ const { seeders } = (0, migrate_1.databasePaths)(projectRoot);
423
+ const file = path_1.default.join(seeders, `${snake}.seeder.ts`);
424
+ const rel = (p) => relPath(projectRoot, p);
425
+ let content;
426
+ if (snake === "database") {
427
+ content = renderEntrySeeder(existingSeeders(seeders).filter((s) => s !== "database"));
428
+ }
429
+ else {
430
+ content = (0, stubs_1.renderStub)("seeders/seeder.stub", { table: (0, orm_model_1.pluralRoute)(snake) });
431
+ }
432
+ write(file, content, opts.force, "Seeder", projectRoot);
433
+ if (snake !== "database") {
434
+ const entry = path_1.default.join(seeders, "database.seeder.ts");
435
+ if (fs_1.default.existsSync(entry)) {
436
+ log_1.log.info(` Run it from ${rel(entry)}: await call(${JSON.stringify(snake)});`);
437
+ }
438
+ else {
439
+ log_1.log.info(" megh db:seed runs every seeder in file-name order. To choose the order, " +
440
+ "create the entry seeder: megh make:seeder database");
441
+ }
442
+ }
443
+ return file;
444
+ }
445
+ /** The `database` seeder, calling `others` in order. */
446
+ function renderEntrySeeder(others) {
447
+ return (0, stubs_1.renderStub)("seeders/database-seeder.stub", {
448
+ params: others.length ? "{ call }" : "",
449
+ body: others.length
450
+ ? `await call(${others.map((s) => JSON.stringify(s)).join(", ")});`
451
+ : `// Add { call } to run()'s parameters, then: await call("roles", "users");`,
452
+ });
453
+ }
454
+ /** Names of the seeders in `folder`, in file-name order. */
455
+ function existingSeeders(folder) {
456
+ if (!fs_1.default.existsSync(folder))
457
+ return [];
458
+ return fs_1.default
459
+ .readdirSync(folder)
460
+ .filter((f) => /\.(c?js|mjs|c?ts|mts)$/.test(f) && !/\.d\.[cm]?ts$/.test(f))
461
+ .sort()
462
+ .map((f) => f.replace(/\.(c?js|mjs|c?ts|mts)$/, "").replace(/\.seeder$/, ""));
463
+ }
464
+ /**
465
+ * `make:factory user`: `<factories>/user.factory.ts` exporting `UserFactory`,
466
+ * with a Faker value for each of the model's columns. Foreign keys use the
467
+ * related model's factory when it exists.
468
+ */
469
+ function makeFactory(name, opts = {}) {
470
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
471
+ const n = (0, names_1.resolveName)(name.replace(/[-_.]?factory$/i, ""), "Model");
472
+ const modelFile = path_1.default.join(targetDir(projectRoot, "model", n.dirs), `${n.fileBase}.model.ts`);
473
+ if (!fs_1.default.existsSync(modelFile)) {
474
+ throw new errors_1.CliError(`There is no ${n.base} model (${relPath(projectRoot, modelFile)}) to build a factory for. ` +
475
+ `Create it first: megh make:model ${n.base}`);
476
+ }
477
+ const model = resolveResourceModel(projectRoot, [...n.dirs, n.base].join("/"));
478
+ if (model.typeorm)
479
+ throw new errors_1.CliError(`${relPath(projectRoot, modelFile)} is a TypeORM entity; factories build Megh ORM models.`);
480
+ const { factories } = (0, migrate_1.databasePaths)(projectRoot);
481
+ const file = path_1.default.join(factories, ...n.dirs, `${n.fileBase}.factory.ts`);
482
+ const fields = model.schema.inputFields;
483
+ const foreignKeys = fields
484
+ .filter((f) => /_id$/.test(f.name) && (f.ts === "number" || f.ts === "string"))
485
+ .map((f) => {
486
+ const related = (0, names_1.resolveName)(f.name.replace(/_id$/, ""), "Model");
487
+ const factoryFile = path_1.default.join(factories, `${related.fileBase}.factory.ts`);
488
+ const exists = fs_1.default.existsSync(factoryFile);
489
+ return {
490
+ column: f.name,
491
+ model: (0, names_1.snakeCase)(related.base),
492
+ ...(exists ? { factory: `${related.base}Factory`, factoryImport: importPath(file, factoryFile) } : {}),
493
+ };
494
+ });
495
+ write(file, (0, factory_1.renderFactory)({ model: n.base, modelImport: importPath(file, modelFile), fields, foreignKeys }), opts.force, "Factory", projectRoot);
496
+ log_1.log.info(` Use it in a seeder or test: await ${n.base}Factory.createMany(10);`);
497
+ if (!(0, project_1.installedVersion)("@faker-js/faker", projectRoot)) {
498
+ log_1.log.warn("Factories use Faker for fake values. Install it: npm install -D @faker-js/faker");
499
+ }
500
+ return file;
501
+ }
@@ -18,6 +18,11 @@ export interface MigrationColumn {
18
18
  generated: boolean;
19
19
  /** Auto-increment / identity / serial (as opposed to a default value). */
20
20
  autoIncrement: boolean;
21
+ /** The foreign key, when the migration declares one on the column. */
22
+ references?: {
23
+ table: string;
24
+ onDelete?: string;
25
+ };
21
26
  }
22
27
  export interface MigrationTable {
23
28
  name: string;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.readMigrationSchema = readMigrationSchema;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
+ const orm_model_1 = require("./orm-model");
9
10
  const EXTENSIONS = /\.(c?js|mjs|c?ts|mts)$/;
10
11
  const DECLARATION = /\.d\.[cm]?ts$/;
11
12
  /** Every table the migrations in `folder` leave behind, keyed by name. */
@@ -111,6 +112,10 @@ function literal(arg) {
111
112
  return undefined;
112
113
  return m[2];
113
114
  }
115
+ /** The value of a plain number literal, else `undefined`. */
116
+ function literalNumber(arg) {
117
+ return arg !== undefined && /^\d+$/.test(arg.trim()) ? Number(arg.trim()) : undefined;
118
+ }
114
119
  /** A column data type argument: `"text"`, `sql\`varchar(255)\``, … */
115
120
  function dataType(arg) {
116
121
  if (!arg)
@@ -236,8 +241,23 @@ function parseColumn(name, typeArg, build) {
236
241
  primaryKey,
237
242
  autoIncrement,
238
243
  generated: autoIncrement || /\.(defaultTo|generatedAlwaysAs)\s*\(/.test(build),
244
+ ...foreignKey(name, build),
239
245
  };
240
246
  }
247
+ /** `.constrained("t")` / `.references("t.id")` and the ON DELETE action in a column's chain. */
248
+ function foreignKey(column, chain) {
249
+ const constrained = chain.match(/\.constrained\s*\(\s*(?:["'`]([^"'`]+)["'`])?/);
250
+ const references = chain.match(/\.references\s*\(\s*["'`]([^"'`.]+)/);
251
+ const table = constrained ? (constrained[1] ?? (0, orm_model_1.pluralize)(column.replace(/_id$/, ""))) : references?.[1];
252
+ if (!table)
253
+ return {};
254
+ const onDelete = /\.cascadeOnDelete\s*\(/.test(chain)
255
+ ? "cascade"
256
+ : /\.nullOnDelete\s*\(/.test(chain)
257
+ ? "set null"
258
+ : chain.match(/\.onDelete\s*\(\s*["'`]([^"'`]+)/)?.[1].toLowerCase();
259
+ return { references: onDelete ? { table, onDelete } : { table } };
260
+ }
241
261
  // ── Megh's schema builder (defineMigration) ──────────────────────────────
242
262
  const SCHEMA_STATEMENT = /\b\w+\s*\.\s*(create|table|drop|dropIfExists|rename)\s*\(/g;
243
263
  /** SQL types the builder's column methods create, as `fieldType` reads them. */
@@ -378,9 +398,11 @@ function applyBlueprintCall(table, method, args, chain) {
378
398
  return;
379
399
  }
380
400
  }
381
- const type = BUILDER_TYPES[method];
382
- if (!type)
401
+ const builderType = BUILDER_TYPES[method];
402
+ if (!builderType)
383
403
  return;
404
+ // string(name, length = 255) is a varchar(length) column.
405
+ const type = method === "string" ? `varchar(${Number(literalNumber(args[1]) ?? 255)})` : builderType;
384
406
  const columnName = name ?? (method === "id" ? "id" : undefined);
385
407
  if (!columnName)
386
408
  return;
@@ -394,5 +416,6 @@ function applyBlueprintCall(table, method, args, chain) {
394
416
  primaryKey,
395
417
  autoIncrement,
396
418
  generated: autoIncrement || /\.(default|useCurrent)\s*\(/.test(chain),
419
+ ...foreignKey(columnName, chain),
397
420
  });
398
421
  }
@@ -1,4 +1,4 @@
1
- import type { MigrationTable } from "./migration-schema";
1
+ import type { MigrationColumn, MigrationTable } from "./migration-schema";
2
2
  /** Plural of a snake_case name, inflecting the last word: `blog_post` → `blog_posts`. */
3
3
  export declare function pluralize(snake: string): string;
4
4
  /**
@@ -18,6 +18,11 @@ interface FieldType {
18
18
  export declare function fieldType(sqlType: string): FieldType;
19
19
  /** A model class for `table`, declaring the columns its migrations create. */
20
20
  export declare function renderOrmModel(model: string, table: MigrationTable): string;
21
+ /** The decorators and declaration of one column. */
22
+ export declare function renderField(column: MigrationColumn): {
23
+ decorators: string[];
24
+ field: string;
25
+ };
21
26
  /** A model class for a table with no migration yet: placeholder columns. */
22
27
  export declare function renderBlankOrmModel(model: string, table: string): string;
23
28
  export {};
@@ -5,6 +5,7 @@ exports.singularize = singularize;
5
5
  exports.pluralRoute = pluralRoute;
6
6
  exports.fieldType = fieldType;
7
7
  exports.renderOrmModel = renderOrmModel;
8
+ exports.renderField = renderField;
8
9
  exports.renderBlankOrmModel = renderBlankOrmModel;
9
10
  const stubs_1 = require("../utils/stubs");
10
11
  /**
@@ -139,8 +140,15 @@ function renderField(column) {
139
140
  options.push("nullable: true");
140
141
  if (cast && CAST_TYPES[cast])
141
142
  options.push(`type: ${q(CAST_TYPES[cast])}`);
142
- else if (cast === "number")
143
- options.push(`cast: "number"`); // e.g. Postgres bigint, read as text
143
+ else {
144
+ // A `T | null` field's emitted type is `Object`, so name the column type
145
+ // (for OpenAPI schemas); it doesn't change how values convert.
146
+ const sqlType = !column.notNull ? plainColumnType(column.type) : undefined;
147
+ if (sqlType)
148
+ options.push(`type: ${q(sqlType)}`);
149
+ if (cast === "number")
150
+ options.push(`cast: "number"`); // e.g. Postgres bigint, read as text
151
+ }
144
152
  // Key columns are already declared by @PrimaryKey / @AutoIncrement.
145
153
  if (options.length > 0 || decorators.length === 0) {
146
154
  decorators.push(options.length ? `@Column({ ${options.join(", ")} })` : "@Column()");
@@ -149,6 +157,27 @@ function renderField(column) {
149
157
  const mark = column.generated ? "?" : "!";
150
158
  return { decorators, field: `${name}${mark}: ${column.notNull ? ts : `${ts} | null`};` };
151
159
  }
160
+ /** The model column type for a SQL type that needs no cast, or `undefined`. */
161
+ function plainColumnType(sqlType) {
162
+ const base = sqlType.replace(/\(.*$/, "").trim();
163
+ if (/^(varchar|char|character|character varying|nvarchar|nchar|citext|enum|inet|cidr|macaddr)$/.test(base))
164
+ return "string";
165
+ if (/^(text|tinytext|mediumtext|longtext|ntext)$/.test(base))
166
+ return "text";
167
+ if (base === "uuid" || base === "uniqueidentifier")
168
+ return "uuid";
169
+ if (/^(int\d?|integer|smallint|mediumint|tinyint|serial\d?|smallserial)$/.test(base))
170
+ return "integer";
171
+ if (/^(bigint|bigserial)$/.test(base))
172
+ return "bigint";
173
+ if (/^(decimal|numeric|money)$/.test(base))
174
+ return "decimal";
175
+ if (/^(real|float\d?|double|double precision)$/.test(base))
176
+ return "double";
177
+ if (/^(time|timetz|time with(out)? time zone)$/.test(base))
178
+ return "time";
179
+ return undefined;
180
+ }
152
181
  /** A model class for a table with no migration yet: placeholder columns. */
153
182
  function renderBlankOrmModel(model, table) {
154
183
  return (0, stubs_1.renderStub)("models/orm-model-blank.stub", { Model: model, table: q(table) });
@@ -26,6 +26,27 @@ export interface ResourceSchema {
26
26
  /** Columns a client may send when creating or updating a row. */
27
27
  inputFields: ResourceField[];
28
28
  }
29
+ export interface Declared {
30
+ name: string;
31
+ ts: string;
32
+ /** `| null`, `| undefined` or `?`. */
33
+ nullable: boolean;
34
+ /** Declared with `?`. */
35
+ optional: boolean;
36
+ /** `| null` or `| undefined` in the type. */
37
+ nullInType: boolean;
38
+ decorators: string[];
39
+ /** First line (0-based) of the declaration, including its decorators. */
40
+ startLine: number;
41
+ /** Line (0-based) of the property itself. */
42
+ endLine: number;
43
+ }
44
+ /**
45
+ * Property declarations of the model class (`name!: string;`), with the
46
+ * decorators above each one. Initialised properties (relations such as
47
+ * `posts = hasMany(...)`), statics and methods are skipped.
48
+ */
49
+ export declare function declaredProperties(source: string): Declared[];
29
50
  /** Read a model (Megh ORM or TypeORM) for resource generation. */
30
51
  export declare function readModelSchema(source: string, table?: MigrationTable): ResourceSchema;
31
52
  /** `src/dtos/<model>.dto.ts`: create, update and list-query DTOs. */
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.declaredProperties = declaredProperties;
3
4
  exports.readModelSchema = readModelSchema;
4
5
  exports.renderResourceDto = renderResourceDto;
5
6
  const orm_model_1 = require("./orm-model");
@@ -63,11 +64,13 @@ function leadingDecorators(line) {
63
64
  function declaredProperties(source) {
64
65
  const out = [];
65
66
  let decorators = [];
67
+ let startLine = -1;
66
68
  // Bracket depth at the start of each line: properties sit directly in the
67
69
  // class body (depth 1), not inside object literals or decorator arguments.
68
70
  let depth = 0;
69
- for (const raw of source.split(/\r?\n/)) {
70
- const line = withoutLineComment(raw).trim();
71
+ const lines = source.split(/\r?\n/);
72
+ for (let index = 0; index < lines.length; index++) {
73
+ const line = withoutLineComment(lines[index]).trim();
71
74
  const atDepth = depth;
72
75
  depth += bracketDelta(line);
73
76
  if (atDepth !== 1) {
@@ -77,6 +80,8 @@ function declaredProperties(source) {
77
80
  continue;
78
81
  }
79
82
  const split = leadingDecorators(line);
83
+ if (split.decorators.length > 0 && decorators.length === 0)
84
+ startLine = index;
80
85
  decorators.push(...split.decorators);
81
86
  // A decorator on its own line, possibly continued on the next lines.
82
87
  if (split.decorators.length > 0 && !split.rest)
@@ -88,7 +93,16 @@ function declaredProperties(source) {
88
93
  const nullInType = parts.includes("null") || parts.includes("undefined");
89
94
  const optional = prop[2] === "?";
90
95
  const ts = parts.filter((p) => p !== "null" && p !== "undefined").join(" | ") || "unknown";
91
- out.push({ name, ts, nullable: optional || nullInType, optional, nullInType, decorators });
96
+ out.push({
97
+ name,
98
+ ts,
99
+ nullable: optional || nullInType,
100
+ optional,
101
+ nullInType,
102
+ decorators,
103
+ startLine: decorators.length > 0 ? startLine : index,
104
+ endLine: index,
105
+ });
92
106
  }
93
107
  if (line && !line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
94
108
  decorators = [];