@monodog/backend 1.0.0

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 (36) hide show
  1. package/.eslintrc.cjs +15 -0
  2. package/dist/cli.js +98 -0
  3. package/dist/gitService.js +240 -0
  4. package/dist/index.js +1185 -0
  5. package/dist/utils/helpers.js +198 -0
  6. package/package.json +41 -0
  7. package/prisma/migrations/20251017041048_init/migration.sql +19 -0
  8. package/prisma/migrations/20251017083007_add_package/migration.sql +21 -0
  9. package/prisma/migrations/20251021083705_alter_package/migration.sql +37 -0
  10. package/prisma/migrations/20251022085155_test/migration.sql +2 -0
  11. package/prisma/migrations/20251022160841_/migration.sql +35 -0
  12. package/prisma/migrations/20251023130158_rename_column_name/migration.sql +34 -0
  13. package/prisma/migrations/20251023174837_/migration.sql +34 -0
  14. package/prisma/migrations/20251023175830_uodate_schema/migration.sql +32 -0
  15. package/prisma/migrations/20251024103700_add_dependency_info/migration.sql +13 -0
  16. package/prisma/migrations/20251025192150_add_dependency_info/migration.sql +19 -0
  17. package/prisma/migrations/20251025192342_add_dependency_info/migration.sql +40 -0
  18. package/prisma/migrations/20251025204613_add_dependency_info/migration.sql +8 -0
  19. package/prisma/migrations/20251026071336_add_dependency_info/migration.sql +25 -0
  20. package/prisma/migrations/20251027062626_add_commit/migration.sql +10 -0
  21. package/prisma/migrations/20251027062748_add_commit/migration.sql +23 -0
  22. package/prisma/migrations/20251027092741_add_commit/migration.sql +17 -0
  23. package/prisma/migrations/20251027112736_add_health_status/migration.sql +16 -0
  24. package/prisma/migrations/20251027140546_init_packages/migration.sql +16 -0
  25. package/prisma/migrations/20251029073436_added_package_heath_key/migration.sql +34 -0
  26. package/prisma/migrations/20251029073830_added_package_health_key/migration.sql +49 -0
  27. package/prisma/migrations/migration_lock.toml +3 -0
  28. package/prisma/schema.prisma +130 -0
  29. package/src/cli.ts +68 -0
  30. package/src/gitService.ts +274 -0
  31. package/src/index.ts +1366 -0
  32. package/src/utils/helpers.js +199 -0
  33. package/src/utils/helpers.js.map +1 -0
  34. package/src/utils/helpers.ts +223 -0
  35. package/tsconfig.json +15 -0
  36. package/tsconfig.o.json +29 -0
package/.eslintrc.cjs ADDED
@@ -0,0 +1,15 @@
1
+ module.exports = {
2
+ root: true,
3
+ parser: '@typescript-eslint/parser',
4
+ plugins: ['@typescript-eslint'],
5
+ extends: [
6
+ 'eslint:recommended',
7
+ 'plugin:@typescript-eslint/recommended',
8
+ ],
9
+ rules: {
10
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
11
+ '@typescript-eslint/no-explicit-any': 'off',
12
+ "@typescript-eslint/no-unused-vars": "off",
13
+ },
14
+ ignorePatterns: ['dist', 'node_modules', '**/*.js'],
15
+ };
package/dist/cli.js ADDED
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * CLI Entry Point for the Monorepo Analysis Engine.
5
+ * * This script is executed when a user runs the `monodog-cli` command
6
+ * in their project. It handles command-line arguments to determine
7
+ * whether to:
8
+ * 1. Start the API server for the dashboard.
9
+ * 2. Run a one-off analysis command. (Future functionality)
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ const path = __importStar(require("path"));
46
+ const index_1 = require("./index"); // Assume index.ts exports this function
47
+ // --- Argument Parsing ---
48
+ // 1. Get arguments excluding the node executable and script name
49
+ const args = process.argv.slice(2);
50
+ // Default settings
51
+ let serve = false;
52
+ let rootPath = process.cwd(); // Default to the current working directory
53
+ // Simple argument parsing loop
54
+ for (let i = 0; i < args.length; i++) {
55
+ const arg = args[i];
56
+ if (arg === '--serve') {
57
+ serve = true;
58
+ }
59
+ else if (arg === '--root') {
60
+ // Look at the next argument for the path
61
+ if (i + 1 < args.length) {
62
+ rootPath = path.resolve(args[i + 1]);
63
+ i++; // Skip the next argument since we've consumed it
64
+ }
65
+ else {
66
+ console.error('Error: --root requires a path argument.');
67
+ process.exit(1);
68
+ }
69
+ }
70
+ else if (arg === '-h' || arg === '--help') {
71
+ console.log(`
72
+ Monodog CLI - Monorepo Analysis Engine
73
+
74
+ Usage:
75
+ monodog-cli [options]
76
+
77
+ Options:
78
+ --serve Start the Monorepo Dashboard API server (default: off).
79
+ --root <path> Specify the root directory of the monorepo to analyze (default: current working directory).
80
+ -h, --help Show this help message.
81
+
82
+ Example:
83
+ monodog-cli --serve --root /path/to/my/monorepo
84
+ `);
85
+ process.exit(0);
86
+ }
87
+ }
88
+ // --- Execution Logic ---
89
+ if (serve) {
90
+ console.log(`Starting Monodog API server...`);
91
+ console.log(`Analyzing monorepo at root: ${rootPath}`);
92
+ // Start the Express server and begin analysis
93
+ (0, index_1.startServer)(rootPath);
94
+ }
95
+ else {
96
+ // Default mode: print usage or run a default report if no command is specified
97
+ console.log(`Monodog CLI: No operation specified. Use --serve to start the API or -h for help.`);
98
+ }
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ /**
3
+ * GitService.ts
4
+ *
5
+ * This service executes native 'git' commands using Node.js's child_process
6
+ * to retrieve the commit history of the local repository.
7
+ */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.GitService = void 0;
13
+ const child_process_1 = require("child_process");
14
+ const util_1 = require("util");
15
+ const path_1 = __importDefault(require("path"));
16
+ // Promisify the standard 'exec' function for easy async/await usage
17
+ const execPromise = (0, util_1.promisify)(child_process_1.exec);
18
+ /**
19
+ * List of standard Conventional Commit types for validation.
20
+ * Any extracted type not in this list will be set to 'other'.
21
+ */
22
+ const VALID_COMMIT_TYPES = [
23
+ 'feat', // New feature
24
+ 'fix', // Bug fix
25
+ 'docs', // Documentation changes
26
+ 'style', // Code style changes (formatting, etc)
27
+ 'refactor', // Code refactoring
28
+ 'perf', // Performance improvements
29
+ 'test', // Adding or updating tests
30
+ 'chore', // Maintenance tasks (e.g., build scripts, dependency updates)
31
+ 'ci', // CI/CD changes
32
+ 'build', // Build system changes (e.g., pnpm/npm scripts)
33
+ 'revert', // Reverting changes
34
+ ];
35
+ /**
36
+ * The delimiter used to separate individual commit records in the git log output.
37
+ * We use a unique string to ensure reliable splitting.
38
+ */
39
+ // const COMMIT_DELIMITER = '|---COMMIT-END---|';
40
+ /**
41
+ * The custom format string passed to 'git log'.
42
+ * It uses JSON structure and our unique delimiter to make parsing consistent.
43
+ * * %H: Commit hash
44
+ * %pn: packageName name
45
+ * %ae: Author email
46
+ * %ad: Author date (ISO 8601 format)
47
+ * %s: Subject (commit message's first line - used for 'message' and 'type' fields)
48
+ */
49
+ // const GIT_LOG_FORMAT = `{"hash": "%H", "author": "%ae", "packageName": "%pn", "date": "%ad", "message": "%s", "type": "%s"}${COMMIT_DELIMITER}`;
50
+ // export class GitService {
51
+ // private repoPath: string;
52
+ // constructor(repoPath: string = process.cwd()) {
53
+ // // Allows specifying a custom path to the monorepo root
54
+ // this.repoPath = repoPath;
55
+ // }
56
+ // /**
57
+ // * Retrieves commit history for the repository, optionally filtered by a package path.
58
+ // * @param pathFilter The path to a package directory (e.g., 'packages/server').
59
+ // * If provided, only commits affecting that path are returned.
60
+ // * @returns A Promise resolving to an array of GitCommit objects.
61
+ // */
62
+ // public async getAllCommits(pathFilter?: string): Promise<GitCommit[]> {
63
+ // const pathArgument = pathFilter ? ` -- ${pathFilter}` : '';
64
+ // const command = `git log --pretty=format:'${GIT_LOG_FORMAT}' --date=iso-strict${pathArgument}`;
65
+ // try {
66
+ // console.log(`Executing Git command: ${command}`);
67
+ // const { stdout } = await execPromise(command, {
68
+ // cwd: this.repoPath,
69
+ // maxBuffer: 1024 * 5000,
70
+ // }); // Increase buffer for large repos
71
+ // // console.log(stdout)
72
+ // console.log(stdout, '--', this.repoPath);
73
+ // const escapedDelimiter = COMMIT_DELIMITER.replace(
74
+ // /[.*+?^${}()|[\]\\]/g,
75
+ // '\\$&'
76
+ // );
77
+ // // 1. Remove the final trailing delimiter, as it creates an empty string at the end of the array
78
+ // const cleanedOutput = stdout
79
+ // .trim()
80
+ // .replace(new RegExp(`${escapedDelimiter}$`), '');
81
+ // console.log(cleanedOutput);
82
+ // if (!cleanedOutput) {
83
+ // return [];
84
+ // }
85
+ // // 2. Split the output by our custom delimiter to get an array of JSON strings
86
+ // const jsonStrings = cleanedOutput.split(COMMIT_DELIMITER);
87
+ // // 3. Parse each string into a GitCommit object
88
+ // const commits: GitCommit[] = jsonStrings
89
+ // .map(jsonString => {
90
+ // try {
91
+ // // JSON.parse is necessary because the output starts as a string
92
+ // const commit = JSON.parse(jsonString);
93
+ // console.log(commit.type, commit['hash']);
94
+ // try {
95
+ // // FIX: Updated Regex to handle optional scope (e.g., 'feat(scope):')
96
+ // // Matches:
97
+ // // 1. (^(\w+)) - The commit type (e.g., 'feat')
98
+ // // 2. (\([^)]+\))? - The optional scope (e.g., '(setup)')
99
+ // // 3. (:|!) - Ends with a colon or an exclamation point (for breaking changes)
100
+ // const typeMatch = commit.type.match(/^(\w+)(\([^)]+\))?([:!])/);
101
+ // let extractedType = 'other';
102
+ // if (typeMatch) {
103
+ // const rawType = typeMatch[1];
104
+ // // NEW: Validate the extracted type against the list of known types
105
+ // if (VALID_COMMIT_TYPES.includes(rawType)) {
106
+ // extractedType = rawType;
107
+ // }
108
+ // }
109
+ // commit.type = extractedType;
110
+ // } catch (e) {
111
+ // console.error('Failed to match commit type:', commit, e);
112
+ // // Skip malformed entries
113
+ // return null;
114
+ // }
115
+ // // // Set type to 'other' if the conventional format is not found
116
+ // // commit.type = typeMatch ? typeMatch[1] : 'other';
117
+ // return commit;
118
+ // } catch (e) {
119
+ // // console.log(jsonString)
120
+ // console.error('Failed to parse commit JSON:', jsonString, e);
121
+ // // Skip malformed entries
122
+ // return null;
123
+ // }
124
+ // })
125
+ // .filter((commit): commit is GitCommit => commit !== null);
126
+ // return commits;
127
+ // } catch (error) {
128
+ // console.error('Error fetching Git history:', error);
129
+ // // In a real application, you would handle this gracefully (e.g., throwing a custom error)
130
+ // throw new Error(
131
+ // 'Failed to retrieve Git commit history. Is Git installed and is the path correct?'
132
+ // );
133
+ // }
134
+ // }
135
+ // }
136
+ class GitService {
137
+ constructor(repoPath = process.cwd()) {
138
+ this.repoPath = repoPath;
139
+ }
140
+ /**
141
+ * Retrieves commit history for the repository, optionally filtered by a package path.
142
+ */
143
+ async getAllCommits(pathFilter) {
144
+ try {
145
+ // First, validate we're in a git repo
146
+ await this.validateGitRepository();
147
+ let pathArgument = '';
148
+ if (pathFilter) {
149
+ // Normalize the path and ensure it's relative to the repo root
150
+ const normalizedPath = this.normalizePath(pathFilter);
151
+ pathArgument = ` -- ${normalizedPath}`;
152
+ }
153
+ // Use a simpler git log format
154
+ const command = `git log --pretty=format:"%H|%an|%ad|%s" --date=iso-strict${pathArgument}`;
155
+ console.log(`🔧 Executing Git command in: ${this.repoPath}`);
156
+ console.log(`📝 Git command: ${command}`);
157
+ const { stdout, stderr } = await execPromise(command, {
158
+ cwd: this.repoPath,
159
+ maxBuffer: 1024 * 5000,
160
+ });
161
+ if (stderr) {
162
+ console.warn('Git stderr:', stderr);
163
+ }
164
+ if (!stdout.trim()) {
165
+ console.log('📭 No commits found for path:', pathFilter);
166
+ return [];
167
+ }
168
+ // Parse the output
169
+ const commits = [];
170
+ const lines = stdout.trim().split('\n');
171
+ for (const line of lines) {
172
+ try {
173
+ const [hash, author, date, message] = line.split('|');
174
+ const commit = {
175
+ hash: hash.trim(),
176
+ author: author.trim(),
177
+ packageName: pathFilter || 'root',
178
+ date: new Date(date.trim()),
179
+ message: message.trim(),
180
+ type: this.extractCommitType(message.trim()),
181
+ };
182
+ commits.push(commit);
183
+ }
184
+ catch (parseError) {
185
+ console.error('❌ Failed to parse commit line:', line, parseError);
186
+ }
187
+ }
188
+ console.log(`✅ Successfully parsed ${commits.length} commits`);
189
+ return commits;
190
+ }
191
+ catch (error) {
192
+ console.error('💥 Error in getAllCommits:', error);
193
+ throw error;
194
+ }
195
+ }
196
+ /**
197
+ * Normalize path to be relative to git repo root
198
+ */
199
+ normalizePath(inputPath) {
200
+ // If it's an absolute path, make it relative to repo root
201
+ if (path_1.default.isAbsolute(inputPath)) {
202
+ return path_1.default.relative(this.repoPath, inputPath);
203
+ }
204
+ // If it's already relative, return as-is
205
+ return inputPath;
206
+ }
207
+ /**
208
+ * Extract commit type from message
209
+ */
210
+ extractCommitType(message) {
211
+ try {
212
+ const typeMatch = message.match(/^(\w+)(\([^)]+\))?!?:/);
213
+ if (typeMatch) {
214
+ const rawType = typeMatch[1].toLowerCase();
215
+ if (VALID_COMMIT_TYPES.includes(rawType)) {
216
+ return rawType;
217
+ }
218
+ }
219
+ return 'other';
220
+ }
221
+ catch (error) {
222
+ return 'other';
223
+ }
224
+ }
225
+ /**
226
+ * Validate that we're in a git repository
227
+ */
228
+ async validateGitRepository() {
229
+ try {
230
+ await execPromise('git rev-parse --is-inside-work-tree', {
231
+ cwd: this.repoPath,
232
+ });
233
+ console.log('✅ Valid git repository');
234
+ }
235
+ catch (error) {
236
+ throw new Error('Not a git repository (or any of the parent directories)');
237
+ }
238
+ }
239
+ }
240
+ exports.GitService = GitService;