@meghjs/cli 0.5.3 → 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 (47) hide show
  1. package/dist/generators/auth-files.d.ts +37 -0
  2. package/dist/generators/auth-files.js +198 -0
  3. package/dist/generators/auth.d.ts +26 -0
  4. package/dist/generators/auth.js +542 -0
  5. package/dist/generators/make.d.ts +8 -0
  6. package/dist/generators/make.js +12 -0
  7. package/dist/generators/migration-schema.d.ts +5 -0
  8. package/dist/generators/migration-schema.js +17 -0
  9. package/dist/generators/scaffold.d.ts +76 -0
  10. package/dist/generators/scaffold.js +353 -0
  11. package/dist/program.js +125 -3
  12. package/dist/templates/cascade.d.ts +37 -0
  13. package/dist/templates/cascade.js +87 -0
  14. package/dist/templates/catalog/common.d.ts +1 -0
  15. package/dist/templates/catalog/common.js +63 -0
  16. package/dist/templates/catalog/construction.d.ts +1 -0
  17. package/dist/templates/catalog/construction.js +138 -0
  18. package/dist/templates/catalog/crm.d.ts +1 -0
  19. package/dist/templates/catalog/crm.js +81 -0
  20. package/dist/templates/catalog/ecommerce.d.ts +1 -0
  21. package/dist/templates/catalog/ecommerce.js +143 -0
  22. package/dist/templates/catalog/education.d.ts +1 -0
  23. package/dist/templates/catalog/education.js +80 -0
  24. package/dist/templates/catalog/hr.d.ts +1 -0
  25. package/dist/templates/catalog/hr.js +83 -0
  26. package/dist/templates/catalog/logistics.d.ts +1 -0
  27. package/dist/templates/catalog/logistics.js +60 -0
  28. package/dist/templates/catalog/marketing.d.ts +1 -0
  29. package/dist/templates/catalog/marketing.js +104 -0
  30. package/dist/templates/catalog/medical.d.ts +1 -0
  31. package/dist/templates/catalog/medical.js +147 -0
  32. package/dist/templates/catalog/pos.d.ts +1 -0
  33. package/dist/templates/catalog/pos.js +110 -0
  34. package/dist/templates/catalog/real-estate.d.ts +1 -0
  35. package/dist/templates/catalog/real-estate.js +171 -0
  36. package/dist/templates/fields.d.ts +64 -0
  37. package/dist/templates/fields.js +331 -0
  38. package/dist/templates/index.d.ts +27 -0
  39. package/dist/templates/index.js +175 -0
  40. package/dist/templates/migration.d.ts +7 -0
  41. package/dist/templates/migration.js +80 -0
  42. package/dist/templates/template.d.ts +37 -0
  43. package/dist/templates/template.js +36 -0
  44. package/dist/utils/dialect.d.ts +8 -0
  45. package/dist/utils/dialect.js +57 -0
  46. package/package.json +17 -5
  47. package/readme.md +26 -1
@@ -0,0 +1,76 @@
1
+ import { type FieldDef } from "../templates/fields";
2
+ import { type ModelTemplate } from "../templates";
3
+ /**
4
+ * Scaffolding from templates: each template becomes a create-table
5
+ * migration, and the usual generators (make:model, make:resource,
6
+ * make:factory) build the model, DTOs, service, controller and factory from
7
+ * that migration.
8
+ */
9
+ export type ScaffoldMode = "migration" | "model" | "resource";
10
+ export type ScaffoldOptions = {
11
+ cwd?: string;
12
+ /** Overwrite the requested models' files (dependencies are never overwritten). */
13
+ force?: boolean;
14
+ /** What to generate for the requested templates. Dependencies get a model. */
15
+ mode?: ScaffoldMode;
16
+ /** Also write a factory for each model. */
17
+ factory?: boolean;
18
+ /** Create the tables foreign keys point to when no migration creates them. Defaults to true. */
19
+ deps?: boolean;
20
+ /** Prompt (pick templates, confirm dependencies) when run in a terminal. */
21
+ interactive?: boolean;
22
+ /** Clock for the migrations' timestamps (tests). */
23
+ now?: Date;
24
+ /** Reuse requested models that already exist instead of failing (without `force`). */
25
+ reuseExisting?: boolean;
26
+ };
27
+ /** One table to scaffold. */
28
+ export interface Target {
29
+ template: ModelTemplate;
30
+ /** Model name, optionally nested: `admin/Product`. */
31
+ model: string;
32
+ table: string;
33
+ /** Asked for (as opposed to pulled in by a foreign key). */
34
+ requested: boolean;
35
+ }
36
+ export interface ScaffoldResult {
37
+ migrations: string[];
38
+ /** Tables whose migration already existed. */
39
+ reused: string[];
40
+ models: string[];
41
+ }
42
+ /**
43
+ * `now`, or one second after the newest migration if that is later: an
44
+ * earlier run may have numbered its migrations a few seconds ahead, and
45
+ * migrations run in file-name order.
46
+ */
47
+ export declare function firstFreeTimestamp(folder: string, now: Date): Date;
48
+ /** Scaffold these tables (and their dependencies) in a project. */
49
+ export declare function scaffold(projectRoot: string, requested: Target[], opts: ScaffoldOptions): Promise<ScaffoldResult>;
50
+ export type MakeFromTemplateOptions = ScaffoldOptions & {
51
+ /** `ecommerce/product`, `product`, or `true` to pick one. */
52
+ template?: string | boolean;
53
+ /** Columns added to (or replacing) the template's, or making up the table without a template. */
54
+ fields?: FieldDef[];
55
+ table?: string;
56
+ };
57
+ /**
58
+ * `make:model Product --template ecommerce/product` (and `make:resource`):
59
+ * a migration from the template, then the model (or resource) from it.
60
+ * `--fields` alone describes the table without a template.
61
+ */
62
+ export declare function makeFromTemplate(name: string, opts: MakeFromTemplateOptions): Promise<ScaffoldResult>;
63
+ export type ScaffoldDomainOptions = ScaffoldOptions & {
64
+ /** Templates to scaffold; default: all of the domain's (or a picked list). */
65
+ only?: string[];
66
+ /** Skip the checklist and take every template. */
67
+ all?: boolean;
68
+ };
69
+ /** `scaffold:domain ecommerce`: several templates of a domain at once. */
70
+ export declare function scaffoldDomain(domainName: string | undefined, opts?: ScaffoldDomainOptions): Promise<ScaffoldResult>;
71
+ /** `template:list`: the domains and their templates. */
72
+ export declare function listTemplates(opts?: {
73
+ cwd?: string;
74
+ domain?: string;
75
+ json?: boolean;
76
+ }): void;
@@ -0,0 +1,353 @@
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.firstFreeTimestamp = firstFreeTimestamp;
40
+ exports.scaffold = scaffold;
41
+ exports.makeFromTemplate = makeFromTemplate;
42
+ exports.scaffoldDomain = scaffoldDomain;
43
+ exports.listTemplates = listTemplates;
44
+ const fs_1 = __importDefault(require("fs"));
45
+ const path_1 = __importDefault(require("path"));
46
+ const errors_1 = require("../errors");
47
+ const migrate_1 = require("../commands/migrate");
48
+ const log_1 = require("../utils/log");
49
+ const names_1 = require("../utils/names");
50
+ const project_1 = require("../utils/project");
51
+ const make_1 = require("./make");
52
+ const migration_schema_1 = require("./migration-schema");
53
+ const orm_model_1 = require("./orm-model");
54
+ const fields_1 = require("../templates/fields");
55
+ const templates_1 = require("../templates");
56
+ const migration_1 = require("../templates/migration");
57
+ const cascade_1 = require("../templates/cascade");
58
+ const dialect_1 = require("../utils/dialect");
59
+ const rel = (root, file) => path_1.default.relative(root, file).split(path_1.default.sep).join("/");
60
+ const isInteractive = (o) => o.interactive === true && process.stdin.isTTY === true && process.stdout.isTTY === true;
61
+ async function inquirer() {
62
+ return (await Promise.resolve().then(() => __importStar(require("inquirer")))).default;
63
+ }
64
+ /** Ask for a template: a domain, then one of its templates. */
65
+ async function pickTemplate(domains) {
66
+ const prompt = await inquirer();
67
+ const { domain } = await prompt.prompt([
68
+ {
69
+ type: "list",
70
+ name: "domain",
71
+ message: "Domain:",
72
+ choices: domains.map((d) => ({ name: `${d.title} — ${d.description}`, value: d.name })),
73
+ },
74
+ ]);
75
+ const { picked } = await prompt.prompt([
76
+ {
77
+ type: "list",
78
+ name: "picked",
79
+ message: "Template:",
80
+ choices: (0, templates_1.findDomain)(domains, domain).templates.map((t) => ({ name: `${t.name} — ${t.description}`, value: t })),
81
+ },
82
+ ]);
83
+ return picked;
84
+ }
85
+ /**
86
+ * Add the targets for the tables `targets` reference that neither exist nor
87
+ * are already listed, recursively. Returns the tables nothing can create.
88
+ */
89
+ function addDependencies(targets, domains, existing) {
90
+ const unknown = new Set();
91
+ const queue = [...targets];
92
+ while (queue.length) {
93
+ const t = queue.shift();
94
+ for (const table of (0, templates_1.dependencies)(t.template)) {
95
+ if (existing.has(table) || targets.some((x) => x.table === table))
96
+ continue;
97
+ const dep = (0, templates_1.templateForTable)(domains, table, t.template.domain);
98
+ if (!dep) {
99
+ unknown.add(table);
100
+ continue;
101
+ }
102
+ const target = { template: dep, model: (0, names_1.pascalCase)(dep.name), table, requested: false };
103
+ targets.push(target);
104
+ queue.push(target);
105
+ }
106
+ }
107
+ return [...unknown];
108
+ }
109
+ /**
110
+ * `now`, or one second after the newest migration if that is later: an
111
+ * earlier run may have numbered its migrations a few seconds ahead, and
112
+ * migrations run in file-name order.
113
+ */
114
+ function firstFreeTimestamp(folder, now) {
115
+ const stamps = fs_1.default.existsSync(folder)
116
+ ? fs_1.default.readdirSync(folder).flatMap((f) => f.match(/^(\d{14})_/)?.[1] ?? [])
117
+ : [];
118
+ const latest = stamps.sort().pop();
119
+ if (!latest)
120
+ return now;
121
+ const [y, mo, d, h, mi, s] = [0, 4, 6, 8, 10, 12].map((i, k) => Number(latest.slice(i, k === 0 ? 4 : i + 2)));
122
+ const next = new Date(y, mo - 1, d, h, mi, s + 1);
123
+ return next > now ? next : now;
124
+ }
125
+ /** Scaffold these tables (and their dependencies) in a project. */
126
+ async function scaffold(projectRoot, requested, opts) {
127
+ const mode = opts.mode ?? "model";
128
+ const domains = (0, templates_1.allDomains)(projectRoot);
129
+ const { migrations: migrationsDir } = (0, migrate_1.databasePaths)(projectRoot);
130
+ const schema = (0, migration_schema_1.readMigrationSchema)(migrationsDir);
131
+ const existing = new Set(schema.keys());
132
+ let targets = [...requested];
133
+ if (opts.deps !== false) {
134
+ const withDeps = [...targets];
135
+ const unknown = addDependencies(withDeps, domains, existing);
136
+ const extra = withDeps.filter((t) => !t.requested);
137
+ let include = true;
138
+ if (extra.length && isInteractive(opts)) {
139
+ ({ include } = await (await inquirer()).prompt([
140
+ {
141
+ type: "confirm",
142
+ name: "include",
143
+ message: `Foreign keys point to tables no migration creates yet: ${extra.map((t) => t.table).join(", ")}. Create them too?`,
144
+ default: true,
145
+ },
146
+ ]));
147
+ }
148
+ if (include)
149
+ targets = withDeps;
150
+ for (const table of unknown) {
151
+ log_1.log.warn(`No template or migration creates "${table}", which a foreign key points to. Create it before migrating.`);
152
+ }
153
+ }
154
+ targets = (0, templates_1.orderByDependencies)(targets);
155
+ // Check the requested files before writing anything.
156
+ if (!opts.force && mode !== "migration") {
157
+ const taken = (t) => {
158
+ if (t.template.pivot)
159
+ return [];
160
+ const files = (0, make_1.generatedFiles)(projectRoot, t.model);
161
+ const list = mode === "resource" ? [files.dto, files.service, files.controller] : [files.model];
162
+ if (opts.factory)
163
+ list.push(files.factory);
164
+ return list.filter((f) => fs_1.default.existsSync(f));
165
+ };
166
+ if (opts.reuseExisting) {
167
+ // Already scaffolded (e.g. products, by another domain): keep what is there.
168
+ for (const t of targets) {
169
+ if (t.requested && taken(t).length) {
170
+ t.requested = false;
171
+ log_1.log.info(` ${t.model} is already scaffolded; keeping its files (use --force to regenerate).`);
172
+ }
173
+ }
174
+ }
175
+ else {
176
+ const files = requested.flatMap(taken);
177
+ if (files.length) {
178
+ throw new errors_1.CliError(`Already exists: ${files.map((f) => rel(projectRoot, f)).join(", ")}. Use -f or --force to overwrite.`);
179
+ }
180
+ }
181
+ }
182
+ // SQL Server allows one cascade path between two tables, and none back to the same table.
183
+ const dialect = (0, dialect_1.projectDialect)(projectRoot);
184
+ let sqlServerFields;
185
+ if (dialect === "mssql") {
186
+ const writing = targets.filter((t) => !schema.has(t.table));
187
+ const limited = (0, cascade_1.limitCascadePaths)((0, cascade_1.cascadeEdges)(schema), writing.map((t) => ({ table: t.table, fields: t.template.fields })));
188
+ sqlServerFields = limited.fields;
189
+ for (const d of limited.dropped) {
190
+ log_1.log.info(` SQL Server: ${d.table}.${d.column} gets no ON DELETE action (${d.reason}).`);
191
+ }
192
+ }
193
+ const result = { migrations: [], reused: [], models: [] };
194
+ const start = firstFreeTimestamp(migrationsDir, opts.now ?? new Date());
195
+ let offset = 0;
196
+ for (const t of targets) {
197
+ const table = schema.get(t.table);
198
+ if (table) {
199
+ result.reused.push(t.table);
200
+ log_1.log.info(` "${t.table}" is already created in ${table.createdIn}; keeping that migration.`);
201
+ continue;
202
+ }
203
+ // One second apart, so they run in dependency order.
204
+ const stamp = (0, make_1.migrationTimestamp)(new Date(start.getTime() + offset++ * 1000));
205
+ const file = path_1.default.join(migrationsDir, `${stamp}_create_${t.table}_table.ts`);
206
+ const template = { ...t.template, fields: sqlServerFields?.get(t.table) ?? t.template.fields };
207
+ (0, project_1.writeFileSafe)(file, (0, migration_1.renderCreateMigration)(template, t.table, dialect));
208
+ log_1.log.success(`Migration created: ${rel(projectRoot, file)}`);
209
+ result.migrations.push(file);
210
+ }
211
+ if (mode === "migration")
212
+ return result;
213
+ const cwd = projectRoot;
214
+ for (const t of targets) {
215
+ if (t.template.pivot)
216
+ continue;
217
+ const files = (0, make_1.generatedFiles)(projectRoot, t.model);
218
+ if (t.requested && mode === "resource") {
219
+ (0, make_1.makeResource)(t.model, { cwd, table: t.table, force: opts.force });
220
+ result.models.push(files.model);
221
+ }
222
+ else if (!fs_1.default.existsSync(files.model) || (t.requested && opts.force)) {
223
+ (0, make_1.makeModel)(t.model, { cwd, table: t.table, force: opts.force && t.requested });
224
+ result.models.push(files.model);
225
+ }
226
+ else if (!t.requested) {
227
+ log_1.log.info(` Model exists, reusing: ${rel(projectRoot, files.model)}`);
228
+ }
229
+ if (opts.factory && (!fs_1.default.existsSync(files.factory) || (t.requested && opts.force))) {
230
+ (0, make_1.makeFactory)(t.model, { cwd, force: opts.force && t.requested });
231
+ }
232
+ }
233
+ if (result.migrations.length)
234
+ log_1.log.info(" Create the tables with: megh migrate");
235
+ return result;
236
+ }
237
+ /**
238
+ * `make:model Product --template ecommerce/product` (and `make:resource`):
239
+ * a migration from the template, then the model (or resource) from it.
240
+ * `--fields` alone describes the table without a template.
241
+ */
242
+ async function makeFromTemplate(name, opts) {
243
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
244
+ const domains = (0, templates_1.allDomains)(projectRoot);
245
+ const n = (0, names_1.resolveName)(name, "Model");
246
+ const snake = (0, names_1.snakeCase)(n.base);
247
+ let base;
248
+ if (opts.template === true) {
249
+ if (!isInteractive(opts)) {
250
+ throw new errors_1.CliError("Name the template, e.g. --template ecommerce/product (list them with megh template:list).");
251
+ }
252
+ base = await pickTemplate(domains);
253
+ }
254
+ else if (typeof opts.template === "string") {
255
+ base = (0, templates_1.findTemplate)(domains, opts.template);
256
+ }
257
+ else {
258
+ if (!opts.fields?.length)
259
+ throw new errors_1.CliError("Pass --template <name> or --fields <list>.");
260
+ base = {
261
+ domain: "custom",
262
+ name: snake,
263
+ table: (0, orm_model_1.pluralize)(snake),
264
+ description: "",
265
+ fields: [],
266
+ timestamps: true,
267
+ softDeletes: false,
268
+ pivot: false,
269
+ unique: [],
270
+ };
271
+ }
272
+ const template = { ...base, fields: (0, fields_1.mergeFields)(base.fields, opts.fields ?? []) };
273
+ const table = opts.table ?? (snake === base.name ? base.table : (0, orm_model_1.pluralize)(snake));
274
+ if (template.pivot && opts.mode !== "migration") {
275
+ log_1.log.info(` ${base.domain}/${base.name} is a join table: writing its migration only (no model).`);
276
+ }
277
+ const created = (0, migration_schema_1.readMigrationSchema)((0, migrate_1.databasePaths)(projectRoot).migrations).get(table);
278
+ if (created && (opts.fields?.length || opts.template)) {
279
+ log_1.log.warn(`"${table}" is already created in ${created.createdIn}, so the template's columns are not applied. ` +
280
+ `Change the table with an alter-table migration: megh make:migration add_columns_to_${table}_table`);
281
+ }
282
+ return scaffold(projectRoot, [{ template, model: [...n.dirs, n.base].join("/"), table, requested: true }], opts);
283
+ }
284
+ /** `scaffold:domain ecommerce`: several templates of a domain at once. */
285
+ async function scaffoldDomain(domainName, opts = {}) {
286
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
287
+ const domains = (0, templates_1.allDomains)(projectRoot);
288
+ const interactive = isInteractive(opts);
289
+ let domain;
290
+ if (domainName)
291
+ domain = (0, templates_1.findDomain)(domains, domainName);
292
+ else if (interactive) {
293
+ const { picked } = await (await inquirer()).prompt([
294
+ {
295
+ type: "list",
296
+ name: "picked",
297
+ message: "Domain:",
298
+ choices: domains.map((d) => ({ name: `${d.title} — ${d.description}`, value: d.name })),
299
+ },
300
+ ]);
301
+ domain = (0, templates_1.findDomain)(domains, picked);
302
+ }
303
+ else {
304
+ throw new errors_1.CliError(`Name a domain: ${domains.map((d) => d.name).join(", ")}.`);
305
+ }
306
+ let templates;
307
+ if (opts.only?.length)
308
+ templates = opts.only.map((ref) => (0, templates_1.findTemplate)([domain], ref));
309
+ else if (interactive && !opts.all) {
310
+ ({ templates } = await (await inquirer()).prompt([
311
+ {
312
+ type: "checkbox",
313
+ name: "templates",
314
+ message: `${domain.title} templates:`,
315
+ choices: domain.templates.map((t) => ({ name: `${t.name} — ${t.description}`, value: t, checked: true })),
316
+ },
317
+ ]));
318
+ if (!templates.length)
319
+ throw new errors_1.CliError("No templates selected.");
320
+ }
321
+ else
322
+ templates = domain.templates;
323
+ return scaffold(projectRoot, templates.map((t) => ({ template: t, model: (0, names_1.pascalCase)(t.name), table: t.table, requested: true })), { reuseExisting: true, ...opts });
324
+ }
325
+ /** `template:list`: the domains and their templates. */
326
+ function listTemplates(opts = {}) {
327
+ const cwd = opts.cwd ?? process.cwd();
328
+ let projectRoot;
329
+ try {
330
+ projectRoot = (0, project_1.requireProjectRoot)(cwd);
331
+ }
332
+ catch {
333
+ projectRoot = undefined;
334
+ }
335
+ const domains = (0, templates_1.allDomains)(projectRoot);
336
+ const shown = opts.domain ? [(0, templates_1.findDomain)(domains, opts.domain)] : domains;
337
+ if (opts.json) {
338
+ console.log(JSON.stringify(shown, null, 2));
339
+ return;
340
+ }
341
+ for (const d of shown) {
342
+ console.log(`\n${d.title} (${d.name}) — ${d.description}`);
343
+ const width = Math.max(...d.templates.map((t) => t.name.length));
344
+ for (const t of d.templates) {
345
+ const columns = t.fields.map((f) => f.name).join(", ");
346
+ console.log(` ${t.name.padEnd(width)} ${t.description}${t.pivot ? " (join table)" : ""}`);
347
+ if (opts.domain)
348
+ console.log(` ${" ".repeat(width)} ${columns}`);
349
+ }
350
+ }
351
+ console.log("\nUse one: megh make:model Product --template ecommerce/product (or make:resource),\n" +
352
+ "or a whole domain: megh scaffold:domain ecommerce. Add your own in .megh/templates/<domain>.json.");
353
+ }
package/dist/program.js CHANGED
@@ -13,6 +13,9 @@ const start_1 = require("./commands/start");
13
13
  const errors_1 = require("./errors");
14
14
  const migrate_1 = require("./commands/migrate");
15
15
  const make_1 = require("./generators/make");
16
+ const scaffold_1 = require("./generators/scaffold");
17
+ const auth_1 = require("./generators/auth");
18
+ const fields_1 = require("./templates/fields");
16
19
  const log_1 = require("./utils/log");
17
20
  const stubs_1 = require("./utils/stubs");
18
21
  /**
@@ -180,8 +183,20 @@ function createProgram(run = {}) {
180
183
  .option("-t, --table <table>", "Table name (default: plural snake_case name, e.g. blog_posts)")
181
184
  .option("--orm", "Generate a TypeORM entity")
182
185
  .option("--root <dir>", "Folder under src/ to write to (also -rt)")
183
- .action((name, o) => {
184
- (0, make_1.makeModel)(name, { cwd: cwd(), ...o });
186
+ .option("--template [ref]", "Create the table from a template, e.g. ecommerce/product (no value: pick one)")
187
+ .option("--fields <list>", 'Columns to add or replace, e.g. "title,price:money,status:in(draft|live)"')
188
+ .option("--factory", "With --template/--fields: also write a factory")
189
+ .option("--no-deps", "With --template/--fields: don't create the tables foreign keys point to")
190
+ .option("-y, --yes", "Don't prompt")
191
+ .addHelpText("after", TEMPLATE_HELP)
192
+ .action(async (name, o) => {
193
+ if (o.template !== undefined || o.fields !== undefined) {
194
+ if (o.orm)
195
+ throw new errors_1.CliError("--template and --fields build Megh ORM models; leave out --orm.");
196
+ await (0, scaffold_1.makeFromTemplate)(name, { cwd: cwd(), mode: "model", ...templateOptions(o) });
197
+ return;
198
+ }
199
+ (0, make_1.makeModel)(name, { cwd: cwd(), force: o.force, table: o.table, orm: o.orm, root: o.root });
185
200
  });
186
201
  sub("update:model", "Sync a model's columns with its migrations, keeping relations and methods")
187
202
  .alias("u:m")
@@ -204,7 +219,16 @@ function createProgram(run = {}) {
204
219
  "there is none). Then src/dtos/<name>.dto.ts, src/services/<name>.service.ts and\n" +
205
220
  "src/controllers/<name>.controller.ts are written, e.g. for `make:resource user`:\n" +
206
221
  " GET /users?page=&perPage= POST /users GET|PUT|DELETE /users/:id")
207
- .action((name, o) => {
222
+ .option("--template [ref]", "Create the table from a template, e.g. ecommerce/product (no value: pick one)")
223
+ .option("--fields <list>", 'Columns to add or replace, e.g. "title,price:money,status:in(draft|live)"')
224
+ .option("--factory", "With --template/--fields: also write a factory")
225
+ .option("--no-deps", "With --template/--fields: don't create the tables foreign keys point to")
226
+ .option("-y, --yes", "Don't prompt")
227
+ .action(async (name, o) => {
228
+ if (o.template !== undefined || o.fields !== undefined) {
229
+ await (0, scaffold_1.makeFromTemplate)(name, { cwd: cwd(), mode: "resource", ...templateOptions(o) });
230
+ return;
231
+ }
208
232
  (0, make_1.makeResource)(name, { cwd: cwd(), force: o.force, table: o.table });
209
233
  });
210
234
  make("make:controller", ["m:c"], "Create a controller in src/controllers/<name>.controller.ts")
@@ -239,8 +263,106 @@ function createProgram(run = {}) {
239
263
  .action((name, o) => {
240
264
  (0, make_1.makeDto)(name, { cwd: cwd(), ...o });
241
265
  });
266
+ // ── Templates ───────────────────────────────────────────────────────────
267
+ sub("scaffold:domain", "Create the tables (and models or resources) of a domain's templates")
268
+ .alias("sc:domain")
269
+ .argument("[domain]", "e.g. ecommerce, pos, medical (no value: pick one)")
270
+ .option("--only <list>", "Only these templates, e.g. product,order,order_item", parseList)
271
+ .option("--all", "Every template of the domain, without the checklist")
272
+ .option("--resource", "Generate REST resources (DTOs, service, controller), not just models")
273
+ .option("--migrations-only", "Only write the migrations")
274
+ .option("--factory", "Also write a factory for each model")
275
+ .option("--no-deps", "Don't create the tables foreign keys point to")
276
+ .option("-f, --force", "Overwrite the generated models' files")
277
+ .option("-y, --yes", "Don't prompt: take every template (or --only) and their dependencies")
278
+ .addHelpText("after", TEMPLATE_HELP)
279
+ .action(async (domain, o) => {
280
+ await (0, scaffold_1.scaffoldDomain)(domain, {
281
+ cwd: cwd(),
282
+ only: o.only,
283
+ all: o.all,
284
+ mode: o.migrationsOnly ? "migration" : o.resource ? "resource" : "model",
285
+ factory: o.factory,
286
+ deps: o.deps,
287
+ force: o.force,
288
+ interactive: !o.yes,
289
+ });
290
+ });
291
+ // ── Auth ────────────────────────────────────────────────────────────────
292
+ sub("scaffold:auth", "Add sign-up and sign-in (JWT, API keys or both), optionally with roles and permissions")
293
+ .alias("sc:auth")
294
+ .option("--strategy <strategy>", `How clients sign in: ${auth_1.AUTH_STRATEGIES.join(", ")} (default: asked, else jwt)`)
295
+ .option("--roles <mode>", `Roles per user: ${auth_1.ROLE_MODES.join(", ")} (default: asked, else none)`)
296
+ .option("--permissions", "Roles grant permissions")
297
+ .option("--no-permissions", "Roles without permissions")
298
+ .option("-f, --force", "Overwrite the generated auth files")
299
+ .option("-y, --yes", "Don't prompt: use the options given and the defaults")
300
+ .addHelpText("after", [
301
+ "",
302
+ "Writes the users table (and roles, user_roles or users.role_id, permissions, api_keys",
303
+ "as chosen) as migrations and models; src/auth/ (password hashing, JWT or API-key helpers,",
304
+ "AppAuthentication, AppAuthorization, rbac.ts); an AuthService, DTOs and an AuthController",
305
+ "(POST /auth/register, POST /auth/login, GET /auth/me, /auth/api-keys); a roles seeder;",
306
+ "and registers them in src/app.ts. An existing users table gets the missing columns.",
307
+ ].join("\n"))
308
+ .action(async (o) => {
309
+ await (0, auth_1.scaffoldAuth)({
310
+ cwd: cwd(),
311
+ strategy: o.strategy,
312
+ roles: o.roles,
313
+ permissions: o.permissions,
314
+ force: o.force,
315
+ interactive: !o.yes,
316
+ });
317
+ });
318
+ sub("scaffold:rbac", "Add roles (one or many per user) and permissions to an app's users")
319
+ .alias("sc:rbac")
320
+ .option("--roles <mode>", "Roles per user: single or multiple (default: asked, else multiple)")
321
+ .option("--permissions", "Roles grant permissions")
322
+ .option("--no-permissions", "Roles without permissions")
323
+ .option("-f, --force", "Overwrite the generated files")
324
+ .option("-y, --yes", "Don't prompt: use the options given and the defaults")
325
+ .action(async (o) => {
326
+ await (0, auth_1.scaffoldRbac)({
327
+ cwd: cwd(),
328
+ roles: o.roles,
329
+ permissions: o.permissions,
330
+ force: o.force,
331
+ interactive: !o.yes,
332
+ });
333
+ });
334
+ sub("template:list", "List the model templates by domain")
335
+ .alias("templates")
336
+ .argument("[domain]", "Show one domain, with each template's columns")
337
+ .option("--json", "Print JSON")
338
+ .action((domain, o) => {
339
+ (0, scaffold_1.listTemplates)({ cwd: cwd(), domain, json: o.json });
340
+ });
242
341
  return { program, exitCode: () => exitCode };
243
342
  }
343
+ const TEMPLATE_HELP = [
344
+ "",
345
+ "Templates describe a table with fields from the fields library, e.g.",
346
+ ' megh make:model Product --template ecommerce/product --fields "barcode?:string(64)"',
347
+ ' megh make:model Ticket --fields "title,body,status:in(open|closed),user_id:cascade"',
348
+ "A field is name[?][:type[(args)]][:modifier]...: a preset (title, slug, price, address, ...),",
349
+ "or a type (string(n), text, integer, money, decimal(p,s), boolean, date, timestamp, json,",
350
+ "foreign(table), ...) with modifiers nullable, unique, index, default(x), in(a|b), cascade,",
351
+ "nullOnDelete, restrict. Columns ending in _id are foreign keys. Tables the foreign keys",
352
+ "point to are created too when no migration creates them. List templates: megh template:list",
353
+ ].join("\n");
354
+ /** The template options shared by make:model and make:resource. */
355
+ function templateOptions(o) {
356
+ return {
357
+ template: o.template,
358
+ fields: o.fields !== undefined ? (0, fields_1.parseFieldList)(o.fields) : undefined,
359
+ table: o.table,
360
+ force: o.force,
361
+ factory: o.factory,
362
+ deps: o.deps,
363
+ interactive: !o.yes,
364
+ };
365
+ }
244
366
  /**
245
367
  * Parse and run a command line (without the `node` and script entries).
246
368
  * Resolves to the process exit code instead of exiting, so it can be tested.
@@ -0,0 +1,37 @@
1
+ import type { MigrationTable } from "../generators/migration-schema";
2
+ import type { FieldDef } from "./fields";
3
+ /**
4
+ * SQL Server refuses a foreign key whose ON DELETE action (CASCADE or SET
5
+ * NULL) would form a cycle (a table referencing itself counts) or a second
6
+ * cascade path between two tables:
7
+ *
8
+ * "Introducing FOREIGN KEY constraint ... may cause cycles or multiple
9
+ * cascade paths."
10
+ *
11
+ * Such a foreign key gets no ON DELETE action instead, so deleting the
12
+ * referenced row fails while rows still point to it.
13
+ */
14
+ /** A foreign key with a cascading action: deleting in `from` changes `to`. */
15
+ export interface CascadeEdge {
16
+ from: string;
17
+ to: string;
18
+ }
19
+ /** The cascading foreign keys of the tables the migrations leave. */
20
+ export declare function cascadeEdges(schema: Map<string, MigrationTable>): CascadeEdge[];
21
+ export interface DroppedAction {
22
+ table: string;
23
+ column: string;
24
+ reason: string;
25
+ }
26
+ /**
27
+ * Walk the new tables' foreign keys (in the order given, ownership first:
28
+ * CASCADE before SET NULL) and drop the action of each one SQL Server would
29
+ * refuse. Returns the tables' fields, changed where needed.
30
+ */
31
+ export declare function limitCascadePaths(existing: CascadeEdge[], tables: {
32
+ table: string;
33
+ fields: FieldDef[];
34
+ }[]): {
35
+ fields: Map<string, FieldDef[]>;
36
+ dropped: DroppedAction[];
37
+ };