@meghjs/cli 0.5.3 → 0.5.5

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,64 @@
1
+ /**
2
+ * The fields library: column definitions shared by the model templates and
3
+ * the `--fields` option.
4
+ *
5
+ * A field is written as a short spec, `name[?][:type[(args)]][:modifier]...`:
6
+ *
7
+ * title a preset (see FIELD_PRESETS)
8
+ * email:unique a preset with an extra modifier
9
+ * address? a preset group, every column nullable
10
+ * nickname?:string(50) an explicit column, nullable
11
+ * price:money a type alias: decimal(12,2)
12
+ * status:in(draft|published) the status preset limited to these values
13
+ * category_id a foreign key to `categories` (from the name)
14
+ * owner_id:foreign(users):cascade
15
+ *
16
+ * Modifiers: `nullable`, `unique`, `index`, `default(value)`, `in(a|b|c)`,
17
+ * and for foreign keys `cascade`, `nullOnDelete` and `restrict`.
18
+ */
19
+ /** Megh schema builder column methods a field can use. */
20
+ export declare const COLUMN_TYPES: readonly ["string", "text", "integer", "bigInteger", "decimal", "float", "double", "boolean", "date", "datetime", "timestamp", "time", "json", "uuid", "foreignId"];
21
+ export type ColumnType = (typeof COLUMN_TYPES)[number];
22
+ export type OnDelete = "cascade" | "set null" | "restrict";
23
+ export interface FieldDef {
24
+ name: string;
25
+ type: ColumnType;
26
+ /** `string(length)`. */
27
+ length?: number;
28
+ /** `decimal(precision, scale)`. */
29
+ precision?: number;
30
+ scale?: number;
31
+ nullable?: boolean;
32
+ unique?: boolean;
33
+ index?: boolean;
34
+ default?: string | number | boolean;
35
+ /** Allowed values, written next to the column (the column itself is a string). */
36
+ enum?: string[];
37
+ /** Foreign key target, for `foreignId` columns. */
38
+ references?: {
39
+ table: string;
40
+ onDelete?: OnDelete;
41
+ };
42
+ /** Written next to the column in the migration. */
43
+ comment?: string;
44
+ }
45
+ type Preset = Omit<FieldDef, "name"> & {
46
+ name?: string;
47
+ };
48
+ /**
49
+ * Columns used across models, by the name they are written as. A preset is
50
+ * one column, or a group of columns (`address`, `geo`, `person`).
51
+ */
52
+ export declare const FIELD_PRESETS: Record<string, Preset | Record<string, Preset>>;
53
+ /** `category_id` → `categories`. */
54
+ export declare function foreignTable(column: string): string;
55
+ /**
56
+ * Parse one field spec into its columns (a preset group gives several).
57
+ * Throws a CliError explaining what is wrong.
58
+ */
59
+ export declare function parseFieldSpec(spec: string): FieldDef[];
60
+ /** Parse a comma-separated `--fields` list. */
61
+ export declare function parseFieldList(list: string | string[]): FieldDef[];
62
+ /** `base` with `extra` fields added; a field of the same name replaces the template's. */
63
+ export declare function mergeFields(base: FieldDef[], extra: FieldDef[]): FieldDef[];
64
+ export {};
@@ -0,0 +1,331 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FIELD_PRESETS = exports.COLUMN_TYPES = void 0;
4
+ exports.foreignTable = foreignTable;
5
+ exports.parseFieldSpec = parseFieldSpec;
6
+ exports.parseFieldList = parseFieldList;
7
+ exports.mergeFields = mergeFields;
8
+ const errors_1 = require("../errors");
9
+ const orm_model_1 = require("../generators/orm-model");
10
+ /**
11
+ * The fields library: column definitions shared by the model templates and
12
+ * the `--fields` option.
13
+ *
14
+ * A field is written as a short spec, `name[?][:type[(args)]][:modifier]...`:
15
+ *
16
+ * title a preset (see FIELD_PRESETS)
17
+ * email:unique a preset with an extra modifier
18
+ * address? a preset group, every column nullable
19
+ * nickname?:string(50) an explicit column, nullable
20
+ * price:money a type alias: decimal(12,2)
21
+ * status:in(draft|published) the status preset limited to these values
22
+ * category_id a foreign key to `categories` (from the name)
23
+ * owner_id:foreign(users):cascade
24
+ *
25
+ * Modifiers: `nullable`, `unique`, `index`, `default(value)`, `in(a|b|c)`,
26
+ * and for foreign keys `cascade`, `nullOnDelete` and `restrict`.
27
+ */
28
+ /** Megh schema builder column methods a field can use. */
29
+ exports.COLUMN_TYPES = [
30
+ "string",
31
+ "text",
32
+ "integer",
33
+ "bigInteger",
34
+ "decimal",
35
+ "float",
36
+ "double",
37
+ "boolean",
38
+ "date",
39
+ "datetime",
40
+ "timestamp",
41
+ "time",
42
+ "json",
43
+ "uuid",
44
+ "foreignId",
45
+ ];
46
+ /** Shorthand types: `price:money` is `decimal(12,2)`. */
47
+ const TYPE_ALIASES = {
48
+ foreign: { type: "foreignId" },
49
+ bigint: { type: "bigInteger" },
50
+ int: { type: "integer" },
51
+ bool: { type: "boolean" },
52
+ money: { type: "decimal", precision: 12, scale: 2 },
53
+ percent: { type: "decimal", precision: 5, scale: 2 },
54
+ email: { type: "string", length: 255 },
55
+ phone: { type: "string", length: 32 },
56
+ url: { type: "string", length: 2048 },
57
+ };
58
+ const str = (length = 255, extra = {}) => ({ type: "string", length, ...extra });
59
+ const money = (extra = {}) => ({ type: "decimal", precision: 12, scale: 2, ...extra });
60
+ const opt = (preset) => ({ ...preset, nullable: true });
61
+ /**
62
+ * Columns used across models, by the name they are written as. A preset is
63
+ * one column, or a group of columns (`address`, `geo`, `person`).
64
+ */
65
+ exports.FIELD_PRESETS = {
66
+ // Names and text
67
+ name: str(),
68
+ title: str(),
69
+ slug: str(255, { unique: true }),
70
+ code: str(32, { unique: true }),
71
+ sku: str(64, { unique: true }),
72
+ reference: str(64, { unique: true }),
73
+ description: opt({ type: "text" }),
74
+ notes: opt({ type: "text" }),
75
+ body: { type: "text" },
76
+ summary: opt(str(500)),
77
+ first_name: str(100),
78
+ last_name: str(100),
79
+ middle_name: opt(str(100)),
80
+ username: str(64, { unique: true }),
81
+ // Contact
82
+ email: str(255),
83
+ phone: opt(str(32)),
84
+ mobile: opt(str(32)),
85
+ website: opt(str(2048)),
86
+ url: opt(str(2048)),
87
+ image: opt(str(2048)),
88
+ avatar: opt(str(2048)),
89
+ logo: opt(str(2048)),
90
+ // Auth
91
+ password: str(255),
92
+ remember_token: opt(str(100)),
93
+ email_verified_at: opt({ type: "timestamp" }),
94
+ last_login_at: opt({ type: "timestamp" }),
95
+ // State
96
+ status: str(32, { default: "active", index: true }),
97
+ type: str(32, { index: true }),
98
+ priority: str(16, { default: "normal", enum: ["low", "normal", "high", "urgent"] }),
99
+ is_active: { type: "boolean", default: true },
100
+ is_featured: { type: "boolean", default: false },
101
+ sort_order: { type: "integer", default: 0 },
102
+ color: opt(str(32)),
103
+ rating: { type: "integer", default: 0 },
104
+ // Money and quantities
105
+ price: money(),
106
+ cost: money({ nullable: true }),
107
+ amount: money(),
108
+ subtotal: money({ default: 0 }),
109
+ discount: money({ default: 0 }),
110
+ tax: money({ default: 0 }),
111
+ total: money({ default: 0 }),
112
+ balance: money({ default: 0 }),
113
+ tax_rate: { type: "decimal", precision: 5, scale: 2, default: 0 },
114
+ currency: str(3, { default: "USD" }),
115
+ quantity: { type: "integer", default: 1 },
116
+ stock: { type: "integer", default: 0 },
117
+ weight: { type: "decimal", precision: 10, scale: 3, nullable: true },
118
+ // People
119
+ gender: opt(str(16, { enum: ["male", "female", "other"] })),
120
+ date_of_birth: opt({ type: "date" }),
121
+ national_id: opt(str(64)),
122
+ // Dates
123
+ date: { type: "date" },
124
+ due_date: opt({ type: "date" }),
125
+ starts_at: opt({ type: "timestamp" }),
126
+ ends_at: opt({ type: "timestamp" }),
127
+ published_at: opt({ type: "timestamp" }),
128
+ paid_at: opt({ type: "timestamp" }),
129
+ // Other
130
+ uuid: { type: "uuid", unique: true },
131
+ ip_address: opt(str(45)),
132
+ metadata: opt({ type: "json" }),
133
+ settings: opt({ type: "json" }),
134
+ // Groups
135
+ address: {
136
+ address_line1: str(),
137
+ address_line2: opt(str()),
138
+ city: str(100),
139
+ state: opt(str(100)),
140
+ postal_code: opt(str(20)),
141
+ country: str(100),
142
+ },
143
+ geo: {
144
+ latitude: { type: "decimal", precision: 10, scale: 7, nullable: true },
145
+ longitude: { type: "decimal", precision: 10, scale: 7, nullable: true },
146
+ },
147
+ person: {
148
+ first_name: str(100),
149
+ last_name: str(100),
150
+ },
151
+ };
152
+ const isGroup = (p) => typeof p.type !== "string";
153
+ /** Split on `sep` outside parentheses. */
154
+ function splitTop(spec, sep) {
155
+ const out = [];
156
+ let depth = 0;
157
+ let start = 0;
158
+ for (let i = 0; i < spec.length; i++) {
159
+ const ch = spec[i];
160
+ if (ch === "(")
161
+ depth++;
162
+ else if (ch === ")")
163
+ depth--;
164
+ else if (ch === sep && depth === 0) {
165
+ out.push(spec.slice(start, i).trim());
166
+ start = i + 1;
167
+ }
168
+ }
169
+ out.push(spec.slice(start).trim());
170
+ return out.filter((s) => s !== "");
171
+ }
172
+ /** `money(10, 2)` → `{ head: "money", args: ["10", "2"] }`. */
173
+ function call(segment) {
174
+ const m = segment.match(/^(\w+)\s*(?:\((.*)\))?$/s);
175
+ if (!m)
176
+ throw new errors_1.CliError(`Invalid field part "${segment}".`);
177
+ return { head: m[1], args: m[2] === undefined ? [] : m[2].split(/[,|]/).map((a) => a.trim()) };
178
+ }
179
+ function parseValue(raw) {
180
+ if (raw === "true")
181
+ return true;
182
+ if (raw === "false")
183
+ return false;
184
+ if (/^-?\d+(\.\d+)?$/.test(raw))
185
+ return Number(raw);
186
+ return raw.replace(/^["']|["']$/g, "");
187
+ }
188
+ /** Model instance members a column would shadow. */
189
+ const RESERVED = new Set(["key", "save", "fill", "delete", "restore", "related", "constructor"]);
190
+ const MODIFIERS = new Set(["nullable", "unique", "index", "default", "in", "cascade", "nullOnDelete", "restrict"]);
191
+ function applyModifier(field, segment, spec) {
192
+ const { head, args } = call(segment);
193
+ switch (head) {
194
+ case "nullable":
195
+ field.nullable = true;
196
+ return;
197
+ case "unique":
198
+ field.unique = true;
199
+ return;
200
+ case "index":
201
+ field.index = true;
202
+ return;
203
+ case "default":
204
+ if (args.length === 0)
205
+ throw new errors_1.CliError(`"${spec}": default needs a value, e.g. default(0).`);
206
+ field.default = parseValue(args.join(","));
207
+ return;
208
+ case "in":
209
+ if (args.length === 0)
210
+ throw new errors_1.CliError(`"${spec}": in needs values, e.g. in(draft|published).`);
211
+ field.enum = args;
212
+ if (field.type !== "string")
213
+ Object.assign(field, { type: "string", length: 32 });
214
+ return;
215
+ case "cascade":
216
+ case "nullOnDelete":
217
+ case "restrict": {
218
+ if (field.type !== "foreignId")
219
+ throw new errors_1.CliError(`"${spec}": ${head} only applies to foreign keys.`);
220
+ const onDelete = head === "cascade" ? "cascade" : head === "restrict" ? "restrict" : "set null";
221
+ field.references = { ...field.references, onDelete };
222
+ if (onDelete === "set null")
223
+ field.nullable = true;
224
+ return;
225
+ }
226
+ default:
227
+ throw new errors_1.CliError(`"${spec}": unknown modifier "${head}". Use nullable, unique, index, default(x), in(a|b), cascade, nullOnDelete or restrict.`);
228
+ }
229
+ }
230
+ /** The column for `name:type(args)`. */
231
+ function typedField(name, segment, spec) {
232
+ const { head, args } = call(segment);
233
+ const alias = TYPE_ALIASES[head];
234
+ const type = (alias?.type ?? head);
235
+ if (!alias && !exports.COLUMN_TYPES.includes(head)) {
236
+ throw new errors_1.CliError(`"${spec}": unknown type "${head}". Use one of: ${[...exports.COLUMN_TYPES, ...Object.keys(TYPE_ALIASES)].join(", ")}.`);
237
+ }
238
+ const field = { ...alias, name, type };
239
+ const num = (i) => {
240
+ const n = Number(args[i]);
241
+ if (!Number.isInteger(n) || n <= 0)
242
+ throw new errors_1.CliError(`"${spec}": "${args[i]}" is not a positive integer.`);
243
+ return n;
244
+ };
245
+ if (type === "string" && args.length)
246
+ field.length = num(0);
247
+ if (type === "decimal" && args.length) {
248
+ field.precision = num(0);
249
+ field.scale = args[1] === undefined ? 2 : Number(args[1]);
250
+ }
251
+ if (type === "foreignId") {
252
+ field.references = { table: args[0] || foreignTable(name) };
253
+ }
254
+ return field;
255
+ }
256
+ /** `category_id` → `categories`. */
257
+ function foreignTable(column) {
258
+ return (0, orm_model_1.pluralize)(column.replace(/_id$/, ""));
259
+ }
260
+ /**
261
+ * Parse one field spec into its columns (a preset group gives several).
262
+ * Throws a CliError explaining what is wrong.
263
+ */
264
+ function parseFieldSpec(spec) {
265
+ const parts = splitTop(spec.trim(), ":");
266
+ if (parts.length === 0)
267
+ throw new errors_1.CliError("Empty field spec.");
268
+ const rawName = parts[0];
269
+ const nullable = rawName.endsWith("?");
270
+ const name = rawName.replace(/\?$/, "");
271
+ if (!/^[a-z_][a-z0-9_]*$/.test(name)) {
272
+ throw new errors_1.CliError(`"${spec}": field names are snake_case, e.g. first_name.`);
273
+ }
274
+ if (RESERVED.has(name)) {
275
+ throw new errors_1.CliError(`"${spec}": "${name}" is a Model method, so it can't be a column. Use another name, e.g. ${name}_value.`);
276
+ }
277
+ let rest = parts.slice(1);
278
+ let fields;
279
+ const next = rest[0] ? call(rest[0]).head : undefined;
280
+ if (next && !MODIFIERS.has(next)) {
281
+ fields = [typedField(name, rest[0], spec)];
282
+ rest = rest.slice(1);
283
+ }
284
+ else if (exports.FIELD_PRESETS[name]) {
285
+ const preset = exports.FIELD_PRESETS[name];
286
+ fields = isGroup(preset)
287
+ ? Object.entries(preset).map(([n, p]) => ({ ...p, name: n }))
288
+ : [{ ...preset, name }];
289
+ }
290
+ else if (/_id$/.test(name)) {
291
+ fields = [{ name, type: "foreignId", references: { table: foreignTable(name) } }];
292
+ }
293
+ else if (rest.some((s) => call(s).head === "in")) {
294
+ // `kind:in(a|b)` needs no type: a short string column.
295
+ fields = [{ name, type: "string", length: 32 }];
296
+ }
297
+ else {
298
+ throw new errors_1.CliError(`"${spec}": "${name}" is not a field preset, so give it a type, e.g. ${name}:string.`);
299
+ }
300
+ const explicitDefault = rest.some((s) => call(s).head === "default");
301
+ for (const field of fields) {
302
+ if (nullable)
303
+ field.nullable = true;
304
+ for (const segment of rest)
305
+ applyModifier(field, segment, spec);
306
+ // A preset's default (status: "active") becomes the first allowed value,
307
+ // as does an explicit default outside them.
308
+ if (field.enum && field.default !== undefined) {
309
+ if (!explicitDefault || !field.enum.includes(String(field.default)))
310
+ field.default = field.enum[0];
311
+ }
312
+ }
313
+ return fields;
314
+ }
315
+ /** Parse a comma-separated `--fields` list. */
316
+ function parseFieldList(list) {
317
+ const specs = Array.isArray(list) ? list : splitTop(list, ",");
318
+ return specs.flatMap((s) => splitTop(s, ",")).flatMap(parseFieldSpec);
319
+ }
320
+ /** `base` with `extra` fields added; a field of the same name replaces the template's. */
321
+ function mergeFields(base, extra) {
322
+ const out = base.map((f) => ({ ...f }));
323
+ for (const field of extra) {
324
+ const i = out.findIndex((f) => f.name === field.name);
325
+ if (i === -1)
326
+ out.push(field);
327
+ else
328
+ out[i] = field;
329
+ }
330
+ return out;
331
+ }
@@ -0,0 +1,27 @@
1
+ import { type Domain, type ModelTemplate } from "./template";
2
+ export type { Domain, ModelTemplate } from "./template";
3
+ export { dependencies } from "./template";
4
+ /** The built-in domains, in the order they are listed. */
5
+ export declare const BUILTIN_DOMAINS: readonly Domain[];
6
+ /** Where a project keeps its own templates, one JSON file per domain. */
7
+ export declare const PROJECT_TEMPLATES_DIR: string;
8
+ /** Domains from `.megh/templates/*.json` in the project. */
9
+ export declare function readProjectDomains(projectRoot: string): Domain[];
10
+ /** Built-in domains merged with the project's: a project template replaces a built-in one of the same name. */
11
+ export declare function allDomains(projectRoot?: string): Domain[];
12
+ export declare function findDomain(domains: Domain[], name: string): Domain;
13
+ /**
14
+ * The template for `ecommerce/product`, or for a bare `product` when only
15
+ * one domain has it (a common template wins over the others).
16
+ */
17
+ export declare function findTemplate(domains: Domain[], ref: string): ModelTemplate;
18
+ /** The template that creates `table`: from `domain` first, then common, then any other domain. */
19
+ export declare function templateForTable(domains: Domain[], table: string, domain?: string): ModelTemplate | undefined;
20
+ /**
21
+ * Order `templates` so each comes after the tables its foreign keys point
22
+ * to (when those are in the list too). Throws on a cycle.
23
+ */
24
+ export declare function orderByDependencies<T extends {
25
+ template: ModelTemplate;
26
+ table: string;
27
+ }>(items: T[]): T[];
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PROJECT_TEMPLATES_DIR = exports.BUILTIN_DOMAINS = exports.dependencies = void 0;
7
+ exports.readProjectDomains = readProjectDomains;
8
+ exports.allDomains = allDomains;
9
+ exports.findDomain = findDomain;
10
+ exports.findTemplate = findTemplate;
11
+ exports.templateForTable = templateForTable;
12
+ exports.orderByDependencies = orderByDependencies;
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const errors_1 = require("../errors");
16
+ const common_1 = require("./catalog/common");
17
+ const construction_1 = require("./catalog/construction");
18
+ const crm_1 = require("./catalog/crm");
19
+ const ecommerce_1 = require("./catalog/ecommerce");
20
+ const education_1 = require("./catalog/education");
21
+ const hr_1 = require("./catalog/hr");
22
+ const logistics_1 = require("./catalog/logistics");
23
+ const marketing_1 = require("./catalog/marketing");
24
+ const medical_1 = require("./catalog/medical");
25
+ const pos_1 = require("./catalog/pos");
26
+ const real_estate_1 = require("./catalog/real-estate");
27
+ const template_1 = require("./template");
28
+ var template_2 = require("./template");
29
+ Object.defineProperty(exports, "dependencies", { enumerable: true, get: function () { return template_2.dependencies; } });
30
+ /** The built-in domains, in the order they are listed. */
31
+ exports.BUILTIN_DOMAINS = [
32
+ common_1.common,
33
+ ecommerce_1.ecommerce,
34
+ pos_1.pos,
35
+ medical_1.medical,
36
+ construction_1.construction,
37
+ marketing_1.marketing,
38
+ real_estate_1.realEstate,
39
+ hr_1.hr,
40
+ crm_1.crm,
41
+ education_1.education,
42
+ logistics_1.logistics,
43
+ ];
44
+ /** Where a project keeps its own templates, one JSON file per domain. */
45
+ exports.PROJECT_TEMPLATES_DIR = path_1.default.join(".megh", "templates");
46
+ /** Domains from `.megh/templates/*.json` in the project. */
47
+ function readProjectDomains(projectRoot) {
48
+ const dir = path_1.default.join(projectRoot, exports.PROJECT_TEMPLATES_DIR);
49
+ if (!fs_1.default.existsSync(dir))
50
+ return [];
51
+ return fs_1.default
52
+ .readdirSync(dir)
53
+ .filter((f) => f.endsWith(".json"))
54
+ .sort()
55
+ .map((file) => {
56
+ const rel = path_1.default.join(exports.PROJECT_TEMPLATES_DIR, file).split(path_1.default.sep).join("/");
57
+ let data;
58
+ try {
59
+ data = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, file), "utf8"));
60
+ }
61
+ catch (err) {
62
+ throw new errors_1.CliError(`${rel} is not valid JSON: ${err.message}`);
63
+ }
64
+ const name = data.domain ?? file.replace(/\.json$/, "");
65
+ if (!Array.isArray(data.templates)) {
66
+ throw new errors_1.CliError(`${rel} needs a "templates" array: [{ "name": "ticket", "fields": ["title", "status:in(open|closed)"] }]`);
67
+ }
68
+ const templates = data.templates.map((t, i) => {
69
+ if (!t || typeof t.name !== "string" || !Array.isArray(t.fields)) {
70
+ throw new errors_1.CliError(`${rel}: templates[${i}] needs a "name" and a "fields" array.`);
71
+ }
72
+ try {
73
+ return (0, template_1.template)(name, t.name, t.description ?? "", t.fields, t);
74
+ }
75
+ catch (err) {
76
+ throw new errors_1.CliError(`${rel} (${t.name}): ${err.message}`);
77
+ }
78
+ });
79
+ return { name, title: data.title ?? name, description: data.description ?? "", templates };
80
+ });
81
+ }
82
+ /** Built-in domains merged with the project's: a project template replaces a built-in one of the same name. */
83
+ function allDomains(projectRoot) {
84
+ const domains = exports.BUILTIN_DOMAINS.map((d) => ({ ...d, templates: [...d.templates] }));
85
+ for (const own of projectRoot ? readProjectDomains(projectRoot) : []) {
86
+ const existing = domains.find((d) => d.name === own.name);
87
+ if (!existing) {
88
+ domains.push(own);
89
+ continue;
90
+ }
91
+ for (const t of own.templates) {
92
+ const i = existing.templates.findIndex((x) => x.name === t.name);
93
+ if (i === -1)
94
+ existing.templates.push(t);
95
+ else
96
+ existing.templates[i] = t;
97
+ }
98
+ }
99
+ return domains;
100
+ }
101
+ function findDomain(domains, name) {
102
+ const domain = domains.find((d) => d.name === name);
103
+ if (!domain) {
104
+ throw new errors_1.CliError(`Unknown domain "${name}". Choose from: ${domains.map((d) => d.name).join(", ")}.`);
105
+ }
106
+ return domain;
107
+ }
108
+ /**
109
+ * The template for `ecommerce/product`, or for a bare `product` when only
110
+ * one domain has it (a common template wins over the others).
111
+ */
112
+ function findTemplate(domains, ref) {
113
+ const [domainName, name] = ref.includes("/") ? ref.split("/", 2) : [undefined, ref];
114
+ const key = name.replace(/-/g, "_");
115
+ if (domainName) {
116
+ const domain = findDomain(domains, domainName);
117
+ const found = domain.templates.find((t) => t.name === key);
118
+ if (!found) {
119
+ throw new errors_1.CliError(`The ${domain.name} domain has no "${name}" template. It has: ${domain.templates.map((t) => t.name).join(", ")}.`);
120
+ }
121
+ return found;
122
+ }
123
+ const matches = domains.flatMap((d) => d.templates.filter((t) => t.name === key));
124
+ if (matches.length === 0) {
125
+ throw new errors_1.CliError(`No template is named "${name}". List them with: megh template:list`);
126
+ }
127
+ if (matches.length > 1) {
128
+ const commonMatch = matches.find((t) => t.domain === "common");
129
+ if (commonMatch)
130
+ return commonMatch;
131
+ throw new errors_1.CliError(`"${name}" is in several domains: ${matches.map((t) => `${t.domain}/${t.name}`).join(", ")}. Pick one.`);
132
+ }
133
+ return matches[0];
134
+ }
135
+ /** The template that creates `table`: from `domain` first, then common, then any other domain. */
136
+ function templateForTable(domains, table, domain) {
137
+ const order = [
138
+ ...domains.filter((d) => d.name === domain),
139
+ ...domains.filter((d) => d.name === "common" && d.name !== domain),
140
+ ...domains.filter((d) => d.name !== domain && d.name !== "common"),
141
+ ];
142
+ for (const d of order) {
143
+ const found = d.templates.find((t) => t.table === table);
144
+ if (found)
145
+ return found;
146
+ }
147
+ return undefined;
148
+ }
149
+ /**
150
+ * Order `templates` so each comes after the tables its foreign keys point
151
+ * to (when those are in the list too). Throws on a cycle.
152
+ */
153
+ function orderByDependencies(items) {
154
+ const byTable = new Map(items.map((i) => [i.table, i]));
155
+ const out = [];
156
+ const state = new Map();
157
+ const visit = (item, trail) => {
158
+ const s = state.get(item.table);
159
+ if (s === "done")
160
+ return;
161
+ if (s === "visiting")
162
+ throw new errors_1.CliError(`Foreign keys form a cycle: ${[...trail, item.table].join(" → ")}.`);
163
+ state.set(item.table, "visiting");
164
+ for (const dep of (0, template_1.dependencies)(item.template)) {
165
+ const target = byTable.get(dep);
166
+ if (target && target !== item)
167
+ visit(target, [...trail, item.table]);
168
+ }
169
+ state.set(item.table, "done");
170
+ out.push(item);
171
+ };
172
+ for (const item of items)
173
+ visit(item, []);
174
+ return out;
175
+ }
@@ -0,0 +1,7 @@
1
+ import type { Dialect } from "../utils/dialect";
2
+ import type { FieldDef } from "./fields";
3
+ import type { ModelTemplate } from "./template";
4
+ /** The schema builder call for one column, e.g. `table.string("name", 100).nullable();`. */
5
+ export declare function renderColumn(field: FieldDef, dialect?: Dialect): string;
6
+ /** A `defineMigration` file creating the template's table. */
7
+ export declare function renderCreateMigration(t: ModelTemplate, table?: string, dialect?: Dialect): string;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderColumn = renderColumn;
4
+ exports.renderCreateMigration = renderCreateMigration;
5
+ /** The schema builder call for one column, e.g. `table.string("name", 100).nullable();`. */
6
+ function renderColumn(field, dialect) {
7
+ const name = JSON.stringify(field.name);
8
+ let call;
9
+ switch (field.type) {
10
+ case "string":
11
+ call = field.length && field.length !== 255 ? `string(${name}, ${field.length})` : `string(${name})`;
12
+ break;
13
+ case "decimal":
14
+ call = field.precision ? `decimal(${name}, ${field.precision}, ${field.scale ?? 2})` : `decimal(${name})`;
15
+ break;
16
+ default:
17
+ call = `${field.type}(${name})`;
18
+ }
19
+ let line = `table.${call}`;
20
+ const setNull = field.references?.onDelete === "set null";
21
+ if (field.nullable && !setNull)
22
+ line += ".nullable()";
23
+ if (field.unique)
24
+ line += ".unique()";
25
+ if (field.default !== undefined)
26
+ line += `.default(${JSON.stringify(field.default)})`;
27
+ if (field.references) {
28
+ line += `.constrained(${JSON.stringify(field.references.table)})`;
29
+ if (field.references.onDelete === "cascade")
30
+ line += ".cascadeOnDelete()";
31
+ else if (setNull)
32
+ line += ".nullOnDelete()";
33
+ // SQL Server has no RESTRICT; NO ACTION also refuses the delete.
34
+ else if (field.references.onDelete === "restrict") {
35
+ line += dialect === "mssql" ? `.onDelete("no action")` : `.onDelete("restrict")`;
36
+ }
37
+ }
38
+ line += ";";
39
+ const comments = [field.enum?.join(" | "), field.comment].filter(Boolean);
40
+ if (comments.length)
41
+ line += ` // ${comments.join("; ")}`;
42
+ return line;
43
+ }
44
+ /** A `defineMigration` file creating the template's table. */
45
+ function renderCreateMigration(t, table = t.table, dialect) {
46
+ const lines = [];
47
+ if (!t.pivot)
48
+ lines.push("table.id();");
49
+ for (const field of t.fields)
50
+ lines.push(renderColumn(field, dialect));
51
+ if (t.timestamps)
52
+ lines.push("table.timestamps();");
53
+ if (t.softDeletes)
54
+ lines.push("table.softDeletes();");
55
+ const list = (columns) => `[${columns.map((c) => JSON.stringify(c)).join(", ")}]`;
56
+ if (t.pivot) {
57
+ const keys = t.fields.filter((f) => f.type === "foreignId").map((f) => f.name);
58
+ if (keys.length >= 2)
59
+ lines.push(`table.primary(${list(keys.slice(0, 2))});`);
60
+ }
61
+ for (const field of t.fields)
62
+ if (field.index && !field.unique)
63
+ lines.push(`table.index(${JSON.stringify(field.name)});`);
64
+ for (const columns of t.unique)
65
+ lines.push(`table.unique(${list(columns)});`);
66
+ return `import { defineMigration } from "@meghjs/core";
67
+
68
+ export default defineMigration({
69
+ async up(schema) {
70
+ await schema.create(${JSON.stringify(table)}, (table) => {
71
+ ${lines.map((l) => ` ${l}`).join("\n")}
72
+ });
73
+ },
74
+
75
+ async down(schema) {
76
+ await schema.drop(${JSON.stringify(table)});
77
+ },
78
+ });
79
+ `;
80
+ }