@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.
- package/dist/commands/migrate.d.ts +23 -5
- package/dist/commands/migrate.js +44 -6
- package/dist/commands/new.js +7 -1
- package/dist/generators/auth-files.d.ts +37 -0
- package/dist/generators/auth-files.js +198 -0
- package/dist/generators/auth.d.ts +26 -0
- package/dist/generators/auth.js +542 -0
- package/dist/generators/factory.d.ts +25 -0
- package/dist/generators/factory.js +159 -0
- package/dist/generators/make.d.ts +38 -0
- package/dist/generators/make.js +176 -0
- package/dist/generators/migration-schema.d.ts +5 -0
- package/dist/generators/migration-schema.js +25 -2
- package/dist/generators/orm-model.d.ts +6 -1
- package/dist/generators/orm-model.js +31 -2
- package/dist/generators/resource.d.ts +21 -0
- package/dist/generators/resource.js +17 -3
- package/dist/generators/scaffold.d.ts +76 -0
- package/dist/generators/scaffold.js +353 -0
- package/dist/generators/update-model.d.ts +21 -0
- package/dist/generators/update-model.js +129 -0
- package/dist/program.js +175 -6
- package/dist/templates/cascade.d.ts +37 -0
- package/dist/templates/cascade.js +87 -0
- package/dist/templates/catalog/common.d.ts +1 -0
- package/dist/templates/catalog/common.js +63 -0
- package/dist/templates/catalog/construction.d.ts +1 -0
- package/dist/templates/catalog/construction.js +138 -0
- package/dist/templates/catalog/crm.d.ts +1 -0
- package/dist/templates/catalog/crm.js +81 -0
- package/dist/templates/catalog/ecommerce.d.ts +1 -0
- package/dist/templates/catalog/ecommerce.js +143 -0
- package/dist/templates/catalog/education.d.ts +1 -0
- package/dist/templates/catalog/education.js +80 -0
- package/dist/templates/catalog/hr.d.ts +1 -0
- package/dist/templates/catalog/hr.js +83 -0
- package/dist/templates/catalog/logistics.d.ts +1 -0
- package/dist/templates/catalog/logistics.js +60 -0
- package/dist/templates/catalog/marketing.d.ts +1 -0
- package/dist/templates/catalog/marketing.js +104 -0
- package/dist/templates/catalog/medical.d.ts +1 -0
- package/dist/templates/catalog/medical.js +147 -0
- package/dist/templates/catalog/pos.d.ts +1 -0
- package/dist/templates/catalog/pos.js +110 -0
- package/dist/templates/catalog/real-estate.d.ts +1 -0
- package/dist/templates/catalog/real-estate.js +171 -0
- package/dist/templates/fields.d.ts +64 -0
- package/dist/templates/fields.js +331 -0
- package/dist/templates/index.d.ts +27 -0
- package/dist/templates/index.js +175 -0
- package/dist/templates/migration.d.ts +7 -0
- package/dist/templates/migration.js +80 -0
- package/dist/templates/template.d.ts +37 -0
- package/dist/templates/template.js +36 -0
- package/dist/utils/dialect.d.ts +8 -0
- package/dist/utils/dialect.js +57 -0
- package/package.json +17 -5
- package/readme.md +30 -1
- package/stubs/controllers/model-controller.stub +10 -1
- package/stubs/seeders/database-seeder.stub +8 -0
- package/stubs/seeders/seeder.stub +10 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { MigrationTable } from "./migration-schema";
|
|
2
|
+
/**
|
|
3
|
+
* Brings a decorated Megh ORM model's column fields in line with its table as
|
|
4
|
+
* the migrations leave it, for `update:model`. Only the column declarations
|
|
5
|
+
* change: new columns are added (in migration order), dropped ones removed,
|
|
6
|
+
* and fields still in the shape `make:model` writes are rewritten with the
|
|
7
|
+
* current type and nullability. Fields with hand-made changes (a `name:`
|
|
8
|
+
* mapping, a custom cast, extra options or decorators) are kept as written.
|
|
9
|
+
* Relations, methods, statics and comments are left alone.
|
|
10
|
+
*/
|
|
11
|
+
export interface ModelChanges {
|
|
12
|
+
added: string[];
|
|
13
|
+
removed: string[];
|
|
14
|
+
updated: string[];
|
|
15
|
+
/** Customized fields kept as written although the migration differs. */
|
|
16
|
+
kept: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare function syncModelSource(source: string, table: MigrationTable): {
|
|
19
|
+
source: string;
|
|
20
|
+
changes: ModelChanges;
|
|
21
|
+
};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.syncModelSource = syncModelSource;
|
|
4
|
+
const names_1 = require("../utils/names");
|
|
5
|
+
const orm_model_1 = require("./orm-model");
|
|
6
|
+
const resource_1 = require("./resource");
|
|
7
|
+
const COLUMN_DECORATOR = /^(Column|PrimaryKey|AutoIncrement|Identity|CreatedAt|UpdatedAt|DeletedAt)\b/;
|
|
8
|
+
const DECORATOR_IMPORTS = ["AutoIncrement", "Column", "CreatedAt", "DeletedAt", "Identity", "PrimaryKey", "UpdatedAt"];
|
|
9
|
+
/** `@Column({ … })` options `make:model` writes. */
|
|
10
|
+
const GENERATED_OPTIONS = new Set(["nullable", "type", "cast"]);
|
|
11
|
+
/** The column a field maps to: its `name:` option, else the property name. */
|
|
12
|
+
function columnOf(field) {
|
|
13
|
+
for (const d of field.decorators) {
|
|
14
|
+
const name = d.match(/\bname\s*:\s*["'`]([^"'`]+)["'`]/)?.[1];
|
|
15
|
+
if (name)
|
|
16
|
+
return name;
|
|
17
|
+
}
|
|
18
|
+
return field.name;
|
|
19
|
+
}
|
|
20
|
+
/** Whether a field still looks the way `make:model` wrote it. */
|
|
21
|
+
function isGenerated(field) {
|
|
22
|
+
if (columnOf(field) !== field.name)
|
|
23
|
+
return false;
|
|
24
|
+
return field.decorators.every((d) => {
|
|
25
|
+
if (/^(PrimaryKey|AutoIncrement|CreatedAt|UpdatedAt|DeletedAt)\(\s*\)$/.test(d))
|
|
26
|
+
return true;
|
|
27
|
+
const column = d.match(/^Column\(\s*(?:\{([^{}]*)\})?\s*\)$/);
|
|
28
|
+
if (!column)
|
|
29
|
+
return false;
|
|
30
|
+
const keys = [...(column[1] ?? "").matchAll(/([\w$]+)\s*:/g)].map((m) => m[1]);
|
|
31
|
+
return keys.every((k) => GENERATED_OPTIONS.has(k));
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
const normalize = (text) => text.replace(/\s+/g, " ").replace(/\s*([(){},:;])\s*/g, "$1").trim();
|
|
35
|
+
/** Comment lines directly above `line` (a doc comment for the field). */
|
|
36
|
+
function commentAbove(lines, line) {
|
|
37
|
+
let start = line;
|
|
38
|
+
while (start > 0 && /^\s*(\/\/|\/\*|\*)/.test(lines[start - 1]))
|
|
39
|
+
start--;
|
|
40
|
+
return start;
|
|
41
|
+
}
|
|
42
|
+
function syncModelSource(source, table) {
|
|
43
|
+
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
|
44
|
+
const lines = source.split(/\r?\n/);
|
|
45
|
+
const fields = (0, resource_1.declaredProperties)(source).filter((p) => p.decorators.some((d) => COLUMN_DECORATOR.test(d)));
|
|
46
|
+
const changes = { added: [], removed: [], updated: [], kept: [] };
|
|
47
|
+
const columnNames = new Set(table.columns.map((c) => c.name));
|
|
48
|
+
const byColumn = new Map(fields.map((f) => [columnOf(f), f]));
|
|
49
|
+
// A property the naming strategy maps to the column: `firstName` ↔ `first_name`.
|
|
50
|
+
const find = (column) => byColumn.get(column) ?? fields.find((f) => !columnNames.has(columnOf(f)) && (0, names_1.snakeCase)(f.name) === column);
|
|
51
|
+
const classLine = lines.findIndex((l) => /\bclass\s+[\w$]+[^{]*\{/.test(l));
|
|
52
|
+
if (classLine === -1 && fields.length === 0) {
|
|
53
|
+
throw new Error("No model class found.");
|
|
54
|
+
}
|
|
55
|
+
const indent = fields.length > 0 ? lines[fields[0].startLine].match(/^\s*/)[0] : " ";
|
|
56
|
+
const replace = new Map(); // first line of a span → its new text
|
|
57
|
+
const drop = new Set(); // lines removed
|
|
58
|
+
const insertAfter = new Map();
|
|
59
|
+
const used = new Set();
|
|
60
|
+
// New columns go after the previous column in migration order.
|
|
61
|
+
let anchor = fields.length > 0 ? commentAbove(lines, fields[0].startLine) - 1 : classLine;
|
|
62
|
+
for (const column of table.columns) {
|
|
63
|
+
const { decorators, field } = (0, orm_model_1.renderField)(column);
|
|
64
|
+
const fresh = `${decorators.join(" ")} ${field}`;
|
|
65
|
+
const existing = find(column.name);
|
|
66
|
+
if (!existing) {
|
|
67
|
+
insertAfter.set(anchor, [...(insertAfter.get(anchor) ?? []), indent + fresh]);
|
|
68
|
+
changes.added.push(column.name);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
used.add(existing);
|
|
72
|
+
anchor = existing.endLine;
|
|
73
|
+
const span = lines.slice(existing.startLine, existing.endLine + 1).join(" ");
|
|
74
|
+
if (normalize(span) === normalize(fresh))
|
|
75
|
+
continue;
|
|
76
|
+
if (!isGenerated(existing)) {
|
|
77
|
+
changes.kept.push(column.name);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
replace.set(existing.startLine, lines[existing.startLine].match(/^\s*/)[0] + fresh);
|
|
81
|
+
for (let i = existing.startLine + 1; i <= existing.endLine; i++)
|
|
82
|
+
drop.add(i);
|
|
83
|
+
changes.updated.push(column.name);
|
|
84
|
+
}
|
|
85
|
+
for (const field of fields) {
|
|
86
|
+
if (used.has(field))
|
|
87
|
+
continue;
|
|
88
|
+
for (let i = commentAbove(lines, field.startLine); i <= field.endLine; i++)
|
|
89
|
+
drop.add(i);
|
|
90
|
+
changes.removed.push(columnOf(field));
|
|
91
|
+
}
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const extra of insertAfter.get(-1) ?? [])
|
|
94
|
+
out.push(extra);
|
|
95
|
+
lines.forEach((line, i) => {
|
|
96
|
+
if (replace.has(i))
|
|
97
|
+
out.push(replace.get(i));
|
|
98
|
+
else if (!drop.has(i))
|
|
99
|
+
out.push(line);
|
|
100
|
+
for (const extra of insertAfter.get(i) ?? [])
|
|
101
|
+
out.push(extra);
|
|
102
|
+
});
|
|
103
|
+
return { source: fixImports(out.join(eol)), changes };
|
|
104
|
+
}
|
|
105
|
+
/** Import the column decorators the model uses from `@meghjs/core`, and drop unused ones. */
|
|
106
|
+
function fixImports(source) {
|
|
107
|
+
const match = source.match(/import\s*\{([^}]*)\}\s*from\s*(["'])@meghjs\/core\2\s*;?/);
|
|
108
|
+
if (!match)
|
|
109
|
+
return source;
|
|
110
|
+
const body = source.slice(match.index + match[0].length);
|
|
111
|
+
const uses = (name) => new RegExp(String.raw `@${name}\s*\(`).test(body);
|
|
112
|
+
const names = match[1]
|
|
113
|
+
.split(",")
|
|
114
|
+
.map((n) => n.trim())
|
|
115
|
+
.filter(Boolean);
|
|
116
|
+
const local = (n) => n.replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim();
|
|
117
|
+
const kept = names.filter((n) => !DECORATOR_IMPORTS.includes(local(n)) || uses(local(n)));
|
|
118
|
+
const missing = DECORATOR_IMPORTS.filter((d) => uses(d) && !names.some((n) => local(n) === d));
|
|
119
|
+
if (missing.length === 0 && kept.length === names.length)
|
|
120
|
+
return source;
|
|
121
|
+
const all = [...kept, ...missing];
|
|
122
|
+
// Keep a sorted list sorted (make:model writes one).
|
|
123
|
+
const sorted = names.every((n, i) => i === 0 || local(names[i - 1]).localeCompare(local(n)) <= 0);
|
|
124
|
+
if (sorted)
|
|
125
|
+
all.sort((a, b) => local(a).localeCompare(local(b)));
|
|
126
|
+
const quote = match[2];
|
|
127
|
+
const statement = `import { ${all.join(", ")} } from ${quote}@meghjs/core${quote};`;
|
|
128
|
+
return source.slice(0, match.index) + statement + body;
|
|
129
|
+
}
|