db-model-router 1.0.2 → 1.0.3

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.
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { parseSchema } = require("../../schema/schema-parser");
6
+ const {
7
+ generateFiles,
8
+ updatePackageJson,
9
+ runInstall,
10
+ printSummary,
11
+ ensurePackageJson,
12
+ } = require("../init");
13
+ const { promptUser } = require("../init/prompt");
14
+
15
+ /**
16
+ * Default answers used when --yes is provided and no schema is available.
17
+ */
18
+ const DEFAULT_ANSWERS = {
19
+ framework: "express",
20
+ database: "postgres",
21
+ session: "memory",
22
+ rateLimiting: false,
23
+ helmet: false,
24
+ logger: false,
25
+ };
26
+
27
+ /**
28
+ * Init command handler for the unified CLI.
29
+ *
30
+ * Scaffolds a new project from a schema file or interactively.
31
+ *
32
+ * @param {object} args - Parsed positional/key-value args (e.g. { from, framework, database })
33
+ * @param {object} flags - Universal flags: { yes, json, dryRun, noInstall, help }
34
+ * @param {import('../flags').OutputContext} ctx - Output context for --json support
35
+ */
36
+ async function init(args, flags, ctx) {
37
+ let answers;
38
+
39
+ if (args.from) {
40
+ // --from points to a schema file: read adapter/framework from it
41
+ const schemaPath = path.resolve(args.from);
42
+ if (!fs.existsSync(schemaPath)) {
43
+ throw new Error(`Schema file not found: ${args.from}`);
44
+ }
45
+ const raw = fs.readFileSync(schemaPath, "utf8");
46
+ const schema = parseSchema(raw);
47
+
48
+ answers = {
49
+ framework: schema.framework,
50
+ database: schema.adapter,
51
+ session: (schema.options && schema.options.session) || "memory",
52
+ rateLimiting: !!(schema.options && schema.options.rateLimiting),
53
+ helmet: !!(schema.options && schema.options.helmet),
54
+ logger: !!(schema.options && schema.options.logger),
55
+ };
56
+ } else if (flags.yes) {
57
+ // --yes with no schema: use defaults, but allow CLI overrides
58
+ answers = Object.assign({}, DEFAULT_ANSWERS);
59
+ if (args.framework) answers.framework = args.framework;
60
+ if (args.database) answers.database = args.database;
61
+ } else {
62
+ // Interactive: build prefilled from CLI args, prompt for the rest
63
+ const prefilled = {};
64
+ if (args.framework) prefilled.framework = args.framework;
65
+ if (args.database) prefilled.database = args.database;
66
+ answers = await promptUser(prefilled);
67
+ }
68
+
69
+ // --dry-run: report planned files without writing
70
+ if (flags.dryRun) {
71
+ const planned = planFiles(answers);
72
+ if (flags.json) {
73
+ ctx.result({
74
+ files: planned,
75
+ dependencies: { installed: false },
76
+ actions: ["dry-run"],
77
+ });
78
+ } else {
79
+ ctx.log("Dry run — the following files would be created:");
80
+ for (const f of planned) {
81
+ ctx.log(` ${f}`);
82
+ }
83
+ ctx.log("\nNo files were written.");
84
+ }
85
+ return;
86
+ }
87
+
88
+ // Ensure package.json exists
89
+ ensurePackageJson();
90
+
91
+ // Generate project files
92
+ const generated = generateFiles(answers);
93
+
94
+ // Update package.json with deps and scripts
95
+ updatePackageJson(answers);
96
+
97
+ // npm install (unless --no-install)
98
+ const installed = !flags.noInstall;
99
+ if (installed) {
100
+ runInstall();
101
+ }
102
+
103
+ // Output
104
+ const allFiles = [
105
+ ...generated.files,
106
+ ...generated.migrationFiles.map((m) => `migrations/${m}`),
107
+ ];
108
+
109
+ if (flags.json) {
110
+ ctx.result({
111
+ files: allFiles,
112
+ dependencies: { installed },
113
+ actions: installed ? ["scaffolded", "installed"] : ["scaffolded"],
114
+ });
115
+ } else {
116
+ printSummary(generated);
117
+ if (!installed) {
118
+ ctx.log(
119
+ "\nSkipped npm install (--no-install). Run `npm install` manually.",
120
+ );
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Compute the list of files that would be created (for --dry-run).
127
+ * This mirrors the file list from generateFiles() without writing anything.
128
+ *
129
+ * @param {object} answers
130
+ * @returns {string[]}
131
+ */
132
+ function planFiles(answers) {
133
+ const { isSql } = require("../init/generators");
134
+ const files = [
135
+ "app.js",
136
+ ".env",
137
+ ".env.example",
138
+ "middleware/logger.js",
139
+ "migrate.js",
140
+ "add_migration.js",
141
+ ".gitignore",
142
+ "migrations/<timestamp>_create_migrations_table" +
143
+ (isSql(answers.database) ? ".sql" : ".js"),
144
+ ];
145
+
146
+ if (answers.session === "database" && isSql(answers.database)) {
147
+ files.push("migrations/<timestamp>_create_sessions_table.sql");
148
+ }
149
+
150
+ return files;
151
+ }
152
+
153
+ module.exports = init;
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { printSchema } = require("../../schema/schema-printer");
6
+ const {
7
+ introspectMySQL,
8
+ introspectPostgres,
9
+ introspectSQLite3,
10
+ introspectMSSQL,
11
+ introspectOracle,
12
+ introspectCockroachDB,
13
+ } = require("../generate-model");
14
+
15
+ /**
16
+ * Map of adapter names to their introspection functions.
17
+ * Each value is an async function(db) => ModelMeta[].
18
+ */
19
+ const INTROSPECT_MAP = {
20
+ mysql: introspectMySQL,
21
+ postgres: introspectPostgres,
22
+ sqlite3: introspectSQLite3,
23
+ mssql: introspectMSSQL,
24
+ oracle: introspectOracle,
25
+ cockroachdb: introspectCockroachDB,
26
+ };
27
+
28
+ /**
29
+ * Convert a ModelMeta array (from introspection) into a ParsedSchema object.
30
+ * This is the reverse of schemaToModelMeta.
31
+ *
32
+ * @param {string} adapter - The database adapter name
33
+ * @param {string} framework - The framework name (default: "express")
34
+ * @param {Array<{table, structure, primary_key, unique, option}>} models
35
+ * @returns {object} ParsedSchema
36
+ */
37
+ function modelMetaToSchema(adapter, framework, models) {
38
+ const tables = {};
39
+
40
+ for (const m of models) {
41
+ const columns = {};
42
+
43
+ // Re-add columns from structure
44
+ for (const [col, rule] of Object.entries(m.structure)) {
45
+ columns[col] = rule;
46
+ }
47
+
48
+ const pk = m.primary_key || "id";
49
+ const unique = m.unique && m.unique.length > 0 ? [...m.unique] : [pk];
50
+
51
+ const opt = m.option || {};
52
+ const softDelete = opt.safeDelete || null;
53
+ const timestamps = {
54
+ created_at: opt.created_at || null,
55
+ modified_at: opt.modified_at || null,
56
+ };
57
+
58
+ tables[m.table] = {
59
+ name: m.table,
60
+ columns,
61
+ pk,
62
+ unique,
63
+ softDelete,
64
+ timestamps,
65
+ };
66
+ }
67
+
68
+ return {
69
+ adapter,
70
+ framework: framework || "express",
71
+ tables,
72
+ relationships: [],
73
+ options: {},
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Inspect command handler for the unified CLI.
79
+ *
80
+ * Connects to a live database, introspects its structure, converts to
81
+ * ParsedSchema, prints via schema-printer, and writes to file.
82
+ *
83
+ * Supported flags:
84
+ * --type Database adapter type (required)
85
+ * --env Path to .env file for connection params
86
+ * --out Output file path (default: dbmr.schema.json)
87
+ * --tables Comma-separated list of tables to include
88
+ * --json Output schema to stdout as JSON (no file write)
89
+ * --dry-run Output schema to stdout without writing file
90
+ *
91
+ * @param {object} args - Parsed key-value args
92
+ * @param {object} flags - Universal flags: { yes, json, dryRun, noInstall, help }
93
+ * @param {import('../flags').OutputContext} ctx - Output context
94
+ */
95
+ async function inspect(args, flags, ctx) {
96
+ const adapterType = args.type;
97
+ if (!adapterType || !INTROSPECT_MAP[adapterType]) {
98
+ const supported = Object.keys(INTROSPECT_MAP).join(", ");
99
+ const msg = adapterType
100
+ ? `Unsupported --type "${adapterType}". Supported: ${supported}`
101
+ : `Missing required --type flag. Supported: ${supported}`;
102
+ if (flags.json) {
103
+ ctx.result({ error: true, code: "INVALID_TYPE", message: msg });
104
+ } else {
105
+ ctx.log(`Error: ${msg}`);
106
+ }
107
+ process.exitCode = 1;
108
+ return;
109
+ }
110
+
111
+ // Load .env file if --env provided
112
+ if (args.env) {
113
+ require("dotenv").config({ path: path.resolve(args.env) });
114
+ }
115
+
116
+ // Connect to database
117
+ let db;
118
+ try {
119
+ const restRouter = require("../../index.js");
120
+ restRouter.init(adapterType);
121
+ db = restRouter.db;
122
+
123
+ const config = {
124
+ host: process.env.DB_HOST || "localhost",
125
+ port: process.env.DB_PORT,
126
+ database: process.env.DB_NAME,
127
+ user: process.env.DB_USER,
128
+ password: process.env.DB_PASS,
129
+ filename: process.env.DB_NAME,
130
+ server: process.env.DB_HOST || "localhost",
131
+ options: { encrypt: false, trustServerCertificate: true },
132
+ };
133
+
134
+ db.connect(config);
135
+ } catch (err) {
136
+ const msg = `Database connection failed: ${err.message}`;
137
+ if (flags.json) {
138
+ ctx.result({ error: true, code: "CONNECTION_FAILED", message: msg });
139
+ } else {
140
+ ctx.log(`Error: ${msg}`);
141
+ }
142
+ process.exitCode = 1;
143
+ return;
144
+ }
145
+
146
+ // Introspect
147
+ let models;
148
+ try {
149
+ const introspectFn = INTROSPECT_MAP[adapterType];
150
+ models = await introspectFn(db);
151
+ } catch (err) {
152
+ const msg = `Introspection failed: ${err.message}`;
153
+ if (flags.json) {
154
+ ctx.result({ error: true, code: "INTROSPECTION_FAILED", message: msg });
155
+ } else {
156
+ ctx.log(`Error: ${msg}`);
157
+ }
158
+ process.exitCode = 1;
159
+ // Disconnect
160
+ if (db.disconnect) await db.disconnect();
161
+ else if (db.close) db.close();
162
+ return;
163
+ }
164
+
165
+ // Disconnect
166
+ try {
167
+ if (db.disconnect) await db.disconnect();
168
+ else if (db.close) db.close();
169
+ } catch (_) {
170
+ // ignore disconnect errors
171
+ }
172
+
173
+ // Filter by --tables if provided
174
+ if (args.tables) {
175
+ const allowed = new Set(args.tables.split(",").map((s) => s.trim()));
176
+ models = models.filter((m) => allowed.has(m.table));
177
+ }
178
+
179
+ // Convert ModelMeta[] → ParsedSchema
180
+ const schema = modelMetaToSchema(adapterType, "express", models);
181
+
182
+ // Print via schema-printer
183
+ const output = printSchema(schema);
184
+
185
+ // Determine output path
186
+ const outPath = args.out || "dbmr.schema.json";
187
+
188
+ if (flags.json) {
189
+ // --json: output schema to stdout, no file write
190
+ ctx.result({ schema: JSON.parse(output), writtenTo: null });
191
+ } else if (flags.dryRun) {
192
+ // --dry-run: output schema to stdout, no file write
193
+ ctx.log(output);
194
+ ctx.log(`Would write to: ${outPath}`);
195
+ } else {
196
+ // Write to file
197
+ const resolvedPath = path.resolve(outPath);
198
+ fs.writeFileSync(resolvedPath, output, "utf8");
199
+ ctx.log(`Schema written to ${outPath}`);
200
+ ctx.log(output);
201
+ }
202
+ }
203
+
204
+ module.exports = inspect;
205
+ module.exports.modelMetaToSchema = modelMetaToSchema;
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { generateModelFile } = require("./generate-model.js");
6
+ const {
7
+ generateRouteFile,
8
+ generateChildRouteFile,
9
+ generateRoutesIndexFile,
10
+ generateTestFile,
11
+ generateChildTestFile,
12
+ } = require("./generate-route.js");
13
+ const { generateOpenAPISpec } = require("./generate-openapi.js");
14
+
15
+ /**
16
+ * Simple line-by-line diff between two strings.
17
+ * Returns a human-readable unified-style diff string.
18
+ */
19
+ function lineDiff(expected, actual) {
20
+ const expectedLines = expected.split("\n");
21
+ const actualLines = actual.split("\n");
22
+ const lines = [];
23
+ const maxLen = Math.max(expectedLines.length, actualLines.length);
24
+
25
+ for (let i = 0; i < maxLen; i++) {
26
+ const exp = i < expectedLines.length ? expectedLines[i] : undefined;
27
+ const act = i < actualLines.length ? actualLines[i] : undefined;
28
+
29
+ if (exp === act) continue;
30
+ if (act !== undefined && exp === undefined) {
31
+ lines.push(`+${i + 1}: ${act}`);
32
+ } else if (exp !== undefined && act === undefined) {
33
+ lines.push(`-${i + 1}: ${exp}`);
34
+ } else {
35
+ lines.push(`-${i + 1}: ${act}`);
36
+ lines.push(`+${i + 1}: ${exp}`);
37
+ }
38
+ }
39
+ return lines.join("\n");
40
+ }
41
+
42
+ /**
43
+ * Build a map of relative file path → expected content for all artifacts
44
+ * that the schema would generate.
45
+ *
46
+ * @param {Array<{table, structure, primary_key, unique, option}>} meta
47
+ * @param {Array<{parent, child, foreignKey}>} relationships
48
+ * @returns {Map<string, string>}
49
+ */
50
+ function buildExpectedFiles(meta, relationships) {
51
+ const expected = new Map();
52
+ const modelsRelPath = "../models";
53
+ const tableNames = meta.map((m) => m.table).sort();
54
+
55
+ // Model files
56
+ for (const m of meta) {
57
+ expected.set(`models/${m.table}.js`, generateModelFile(m));
58
+ }
59
+
60
+ // Route files (one per table)
61
+ for (const m of meta) {
62
+ expected.set(
63
+ `routes/${m.table}.js`,
64
+ generateRouteFile(m.table, modelsRelPath),
65
+ );
66
+ }
67
+
68
+ // Child route files (one per relationship)
69
+ for (const rel of relationships) {
70
+ const childMeta = meta.find((m) => m.table === rel.child);
71
+ const pk = childMeta ? childMeta.primary_key : "id";
72
+ expected.set(
73
+ `routes/${rel.child}_child_of_${rel.parent}.js`,
74
+ generateChildRouteFile(
75
+ rel.child,
76
+ rel.parent,
77
+ rel.foreignKey,
78
+ modelsRelPath,
79
+ ),
80
+ );
81
+ }
82
+
83
+ // Routes index file
84
+ expected.set(
85
+ "routes/index.js",
86
+ generateRoutesIndexFile(tableNames, relationships),
87
+ );
88
+
89
+ // Test files (one per table)
90
+ for (const m of meta) {
91
+ expected.set(
92
+ `test/${m.table}.test.js`,
93
+ generateTestFile(m.table, m.primary_key),
94
+ );
95
+ }
96
+
97
+ // Child test files (one per relationship)
98
+ for (const rel of relationships) {
99
+ const childMeta = meta.find((m) => m.table === rel.child);
100
+ const pk = childMeta ? childMeta.primary_key : "id";
101
+ expected.set(
102
+ `test/${rel.child}_child_of_${rel.parent}.test.js`,
103
+ generateChildTestFile(rel.child, rel.parent, rel.foreignKey, pk),
104
+ );
105
+ }
106
+
107
+ // OpenAPI spec
108
+ expected.set(
109
+ "openapi.json",
110
+ JSON.stringify(generateOpenAPISpec(meta), null, 2) + "\n",
111
+ );
112
+
113
+ return expected;
114
+ }
115
+
116
+ /**
117
+ * Scan known artifact directories on disk and return a set of relative paths
118
+ * that exist.
119
+ *
120
+ * @param {string} baseDir
121
+ * @returns {Set<string>}
122
+ */
123
+ function scanDiskFiles(baseDir) {
124
+ const files = new Set();
125
+
126
+ const dirs = [
127
+ { dir: "models", ext: ".js" },
128
+ { dir: "routes", ext: ".js" },
129
+ { dir: "test", ext: ".test.js" },
130
+ ];
131
+
132
+ for (const { dir, ext } of dirs) {
133
+ const fullDir = path.join(baseDir, dir);
134
+ if (!fs.existsSync(fullDir)) continue;
135
+ for (const file of fs.readdirSync(fullDir)) {
136
+ if (file.endsWith(ext)) {
137
+ files.add(`${dir}/${file}`);
138
+ }
139
+ }
140
+ }
141
+
142
+ // Check for openapi.json at root
143
+ const openapiPath = path.join(baseDir, "openapi.json");
144
+ if (fs.existsSync(openapiPath)) {
145
+ files.add("openapi.json");
146
+ }
147
+
148
+ return files;
149
+ }
150
+
151
+ /**
152
+ * Compare expected generated content against actual files on disk.
153
+ *
154
+ * @param {string} baseDir — project root
155
+ * @param {Array<{table, structure, primary_key, unique, option}>} meta — from schema
156
+ * @param {Array<{parent, child, foreignKey}>} relationships
157
+ * @returns {{ added: string[], modified: Array<{file: string, diff: string}>, deleted: string[] }}
158
+ */
159
+ function computeDiff(baseDir, meta, relationships) {
160
+ const expected = buildExpectedFiles(meta, relationships);
161
+ const diskFiles = scanDiskFiles(baseDir);
162
+
163
+ const added = [];
164
+ const modified = [];
165
+ const deleted = [];
166
+
167
+ // Check expected files against disk
168
+ for (const [relPath, expectedContent] of expected) {
169
+ const fullPath = path.join(baseDir, relPath);
170
+ if (!fs.existsSync(fullPath)) {
171
+ added.push(relPath);
172
+ } else {
173
+ const actualContent = fs.readFileSync(fullPath, "utf8");
174
+ if (actualContent !== expectedContent) {
175
+ modified.push({
176
+ file: relPath,
177
+ diff: lineDiff(expectedContent, actualContent),
178
+ });
179
+ }
180
+ // unchanged — not reported
181
+ }
182
+ }
183
+
184
+ // Check disk files not in expected set → deleted
185
+ for (const diskFile of diskFiles) {
186
+ if (!expected.has(diskFile)) {
187
+ deleted.push(diskFile);
188
+ }
189
+ }
190
+
191
+ return {
192
+ added: added.sort(),
193
+ modified: modified.sort((a, b) => a.file.localeCompare(b.file)),
194
+ deleted: deleted.sort(),
195
+ };
196
+ }
197
+
198
+ module.exports = { computeDiff, buildExpectedFiles, lineDiff };
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Universal flag parser and OutputContext for the db-model-router CLI.
5
+ *
6
+ * Parses --yes, --json, --dry-run, --no-install, --help from argv.
7
+ * Extracts the subcommand (first non-flag argument).
8
+ * Collects remaining key-value flags into an args object.
9
+ *
10
+ * @module cli/flags
11
+ */
12
+
13
+ /**
14
+ * Parse CLI argv into subcommand, flags, and args.
15
+ *
16
+ * @param {string[]} argv - process.argv.slice(2) style array
17
+ * @returns {{ subcommand: string|null, flags: Flags, args: object }}
18
+ */
19
+ function parseFlags(argv) {
20
+ const flags = {
21
+ yes: false,
22
+ json: false,
23
+ dryRun: false,
24
+ noInstall: false,
25
+ help: false,
26
+ };
27
+
28
+ const args = {};
29
+ let subcommand = null;
30
+
31
+ for (let i = 0; i < argv.length; i++) {
32
+ const arg = argv[i];
33
+
34
+ if (arg === "--yes") {
35
+ flags.yes = true;
36
+ } else if (arg === "--json") {
37
+ flags.json = true;
38
+ } else if (arg === "--dry-run") {
39
+ flags.dryRun = true;
40
+ } else if (arg === "--no-install") {
41
+ flags.noInstall = true;
42
+ } else if (arg === "--help") {
43
+ flags.help = true;
44
+ } else if (arg.startsWith("--")) {
45
+ // Key-value flag: --from schema.json → { from: "schema.json" }
46
+ const key = arg.slice(2);
47
+ const next = argv[i + 1];
48
+ if (next !== undefined && !next.startsWith("--")) {
49
+ args[key] = next;
50
+ i++; // skip the value
51
+ } else {
52
+ args[key] = true;
53
+ }
54
+ } else if (subcommand === null) {
55
+ subcommand = arg;
56
+ }
57
+ }
58
+
59
+ return { subcommand, flags, args };
60
+ }
61
+
62
+ /**
63
+ * OutputContext controls CLI output behavior based on flags.
64
+ *
65
+ * When --json is active:
66
+ * - log() is a no-op (suppresses human-readable output)
67
+ * - result() accumulates data
68
+ * - flush() prints the accumulated JSON to stdout
69
+ *
70
+ * When --json is NOT active:
71
+ * - log() prints to stdout
72
+ * - result() is a no-op
73
+ * - flush() is a no-op
74
+ */
75
+ class OutputContext {
76
+ constructor(flags) {
77
+ this._json = !!(flags && flags.json);
78
+ this._results = [];
79
+ }
80
+
81
+ /**
82
+ * Log a human-readable message. No-op when --json is active.
83
+ * @param {string} msg
84
+ */
85
+ log(msg) {
86
+ if (!this._json) {
87
+ console.log(msg);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Accumulate a result object for JSON output.
93
+ * @param {*} data
94
+ */
95
+ result(data) {
96
+ this._results.push(data);
97
+ }
98
+
99
+ /**
100
+ * Flush accumulated JSON results to stdout if --json is active.
101
+ * Prints a single JSON object (or the last result if only one was accumulated).
102
+ */
103
+ flush() {
104
+ if (this._json && this._results.length > 0) {
105
+ const output =
106
+ this._results.length === 1 ? this._results[0] : this._results;
107
+ console.log(JSON.stringify(output));
108
+ }
109
+ }
110
+ }
111
+
112
+ module.exports = { parseFlags, OutputContext };