@hedhog/admin 0.48.2 → 0.48.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.
@@ -1 +1 @@
1
- {"version":3,"file":"admin.module.d.ts","sourceRoot":"","sources":["../src/admin.module.ts"],"names":[],"mappings":"AAaA,qBAyBa,WAAW;CAAG"}
1
+ {"version":3,"file":"admin.module.d.ts","sourceRoot":"","sources":["../src/admin.module.ts"],"names":[],"mappings":"AAcA,qBA0Ba,WAAW;CAAG"}
@@ -14,6 +14,7 @@ const prisma_1 = require("@hedhog/prisma");
14
14
  const common_1 = require("@nestjs/common");
15
15
  const config_1 = require("@nestjs/config");
16
16
  const auth_module_1 = require("./auth/auth.module");
17
+ const core_module_1 = require("./core/core.module");
17
18
  const menu_module_1 = require("./menu/menu.module");
18
19
  const role_module_1 = require("./role/role.module");
19
20
  const route_module_1 = require("./route/route.module");
@@ -36,6 +37,7 @@ exports.AdminModule = AdminModule = __decorate([
36
37
  (0, common_1.forwardRef)(() => screen_module_1.ScreenModule),
37
38
  (0, common_1.forwardRef)(() => locale_1.LocaleModule),
38
39
  (0, common_1.forwardRef)(() => user_module_1.UserModule),
40
+ (0, common_1.forwardRef)(() => core_module_1.CoreModule),
39
41
  ],
40
42
  exports: [
41
43
  user_module_1.UserModule,
@@ -1 +1 @@
1
- {"version":3,"file":"admin.module.js","sourceRoot":"","sources":["../src/admin.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAA8C;AAC9C,uCAA0C;AAC1C,mDAAsD;AACtD,2CAA8C;AAC9C,2CAAoD;AACpD,2CAA8C;AAC9C,oDAAgD;AAChD,oDAAgD;AAChD,oDAAgD;AAChD,uDAAmD;AACnD,0DAAsD;AACtD,oDAAgD;AA2BzC,IAAM,WAAW,GAAjB,MAAM,WAAW;CAAG,CAAA;AAAd,kCAAW;sBAAX,WAAW;IAzBvB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE;YACP,qBAAY,CAAC,OAA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,mBAAU,EAAC,GAAG,EAAE,CAAC,iBAAU,CAAC;YAC5B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,wBAAU,CAAC;YAC5B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,6BAAgB,CAAC;YAClC,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,wBAAU,CAAC;YAC5B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,0BAAW,CAAC;YAC7B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,qBAAY,CAAC;YAC9B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,4BAAY,CAAC;YAC9B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,qBAAY,CAAC;YAC9B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,wBAAU,CAAC;YAC5B,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,wBAAU,CAAC;SAC7B;QACD,OAAO,EAAE;YACP,wBAAU;YACV,wBAAU;YACV,iBAAU;YACV,0BAAW;YACX,wBAAU;YACV,wBAAU;YACV,4BAAY;YACZ,qBAAY;SACb;KACF,CAAC;GACW,WAAW,CAAG"}
@@ -0,0 +1,45 @@
1
+ import { CoreService } from './core.service';
2
+ export declare class CoreController {
3
+ private readonly service;
4
+ constructor(service: CoreService);
5
+ index(): Promise<{
6
+ os: {
7
+ name: string;
8
+ platform: NodeJS.Platform;
9
+ version: string;
10
+ architecture: string;
11
+ uptime: number;
12
+ cpu: {
13
+ model: string;
14
+ speed: number;
15
+ physicalCores: number;
16
+ virtualCores: number;
17
+ };
18
+ memory: {
19
+ total: number;
20
+ free: number;
21
+ };
22
+ disk: unknown;
23
+ };
24
+ modules: unknown;
25
+ users: {
26
+ total: number;
27
+ admin: number;
28
+ active: number;
29
+ activities: {
30
+ created_at: Date;
31
+ user: {
32
+ name: string;
33
+ id: number;
34
+ };
35
+ message: string;
36
+ }[];
37
+ };
38
+ database: {
39
+ connections: number;
40
+ size: number;
41
+ queriesPerSecond: number;
42
+ };
43
+ }>;
44
+ }
45
+ //# sourceMappingURL=core.controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.controller.d.ts","sourceRoot":"","sources":["../../src/core/core.controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,qBACa,cAAc;IAGvB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,WAAW;IAIjC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAGZ"}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.CoreController = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const core_service_1 = require("./core.service");
18
+ let CoreController = class CoreController {
19
+ constructor(service) {
20
+ this.service = service;
21
+ }
22
+ async index() {
23
+ return this.service.index();
24
+ }
25
+ };
26
+ exports.CoreController = CoreController;
27
+ __decorate([
28
+ (0, common_1.Get)(),
29
+ __metadata("design:type", Function),
30
+ __metadata("design:paramtypes", []),
31
+ __metadata("design:returntype", Promise)
32
+ ], CoreController.prototype, "index", null);
33
+ exports.CoreController = CoreController = __decorate([
34
+ (0, common_1.Controller)('core'),
35
+ __param(0, (0, common_1.Inject)((0, common_1.forwardRef)(() => core_service_1.CoreService))),
36
+ __metadata("design:paramtypes", [core_service_1.CoreService])
37
+ ], CoreController);
38
+ //# sourceMappingURL=core.controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.controller.js","sourceRoot":"","sources":["../../src/core/core.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAqE;AACrE,iDAA6C;AAGtC,IAAM,cAAc,GAApB,MAAM,cAAc;IACzB,YAEmB,OAAoB;QAApB,YAAO,GAAP,OAAO,CAAa;IACpC,CAAC;IAGE,AAAN,KAAK,CAAC,KAAK;QACT,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IAC9B,CAAC;CACF,CAAA;AAVY,wCAAc;AAOnB;IADL,IAAA,YAAG,GAAE;;;;2CAGL;yBATU,cAAc;IAD1B,IAAA,mBAAU,EAAC,MAAM,CAAC;IAGd,WAAA,IAAA,eAAM,EAAC,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,0BAAW,CAAC,CAAC,CAAA;qCACZ,0BAAW;GAH5B,cAAc,CAU1B"}
@@ -0,0 +1,3 @@
1
+ export declare class CoreModule {
2
+ }
3
+ //# sourceMappingURL=core.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.module.d.ts","sourceRoot":"","sources":["../../src/core/core.module.ts"],"names":[],"mappings":"AAMA,qBAqBa,UAAU;CAAG"}
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CoreModule = void 0;
10
+ const prisma_1 = require("@hedhog/prisma");
11
+ const common_1 = require("@nestjs/common");
12
+ const jwt_1 = require("@nestjs/jwt");
13
+ const core_controller_1 = require("./core.controller");
14
+ const core_service_1 = require("./core.service");
15
+ let CoreModule = class CoreModule {
16
+ };
17
+ exports.CoreModule = CoreModule;
18
+ exports.CoreModule = CoreModule = __decorate([
19
+ (0, common_1.Module)({
20
+ imports: [
21
+ (0, common_1.forwardRef)(() => jwt_1.JwtModule.registerAsync({
22
+ global: true,
23
+ useFactory: () => {
24
+ return {
25
+ secret: String(process.env.JWT_SECRET),
26
+ global: true,
27
+ signOptions: {
28
+ expiresIn: process.env.JWT_EXPIRES_IN || '30d',
29
+ },
30
+ };
31
+ },
32
+ })),
33
+ (0, common_1.forwardRef)(() => prisma_1.PrismaModule),
34
+ ],
35
+ controllers: [core_controller_1.CoreController],
36
+ providers: [core_service_1.CoreService],
37
+ })
38
+ ], CoreModule);
39
+ //# sourceMappingURL=core.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.module.js","sourceRoot":"","sources":["../../src/core/core.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAA8C;AAC9C,2CAAoD;AACpD,qCAAwC;AACxC,uDAAmD;AACnD,iDAA6C;AAuBtC,IAAM,UAAU,GAAhB,MAAM,UAAU;CAAG,CAAA;AAAb,gCAAU;qBAAV,UAAU;IArBtB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE;YACP,IAAA,mBAAU,EAAC,GAAG,EAAE,CACd,eAAS,CAAC,aAAa,CAAC;gBACtB,MAAM,EAAE,IAAI;gBACZ,UAAU,EAAE,GAAG,EAAE;oBACf,OAAO;wBACL,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;wBACtC,MAAM,EAAE,IAAI;wBACZ,WAAW,EAAE;4BACX,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,KAAK;yBAC/C;qBACF,CAAC;gBACJ,CAAC;aACF,CAAC,CACH;YACD,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,qBAAY,CAAC;SAC/B;QACD,WAAW,EAAE,CAAC,gCAAc,CAAC;QAC7B,SAAS,EAAE,CAAC,0BAAW,CAAC;KACzB,CAAC;GACW,UAAU,CAAG"}
@@ -0,0 +1,56 @@
1
+ import { PrismaService } from '@hedhog/prisma';
2
+ export declare class CoreService {
3
+ private prismaService;
4
+ constructor(prismaService: PrismaService);
5
+ index(): Promise<{
6
+ os: {
7
+ name: string;
8
+ platform: NodeJS.Platform;
9
+ version: string;
10
+ architecture: string;
11
+ uptime: number;
12
+ cpu: {
13
+ model: string;
14
+ speed: number;
15
+ physicalCores: number;
16
+ virtualCores: number;
17
+ };
18
+ memory: {
19
+ total: number;
20
+ free: number;
21
+ };
22
+ disk: unknown;
23
+ };
24
+ modules: unknown;
25
+ users: {
26
+ total: number;
27
+ admin: number;
28
+ active: number;
29
+ activities: {
30
+ created_at: Date;
31
+ user: {
32
+ name: string;
33
+ id: number;
34
+ };
35
+ message: string;
36
+ }[];
37
+ };
38
+ database: {
39
+ connections: number;
40
+ size: number;
41
+ queriesPerSecond: number;
42
+ };
43
+ }>;
44
+ private getFriendlyOSName;
45
+ private getDatabaseInfo;
46
+ private getUsersInfo;
47
+ private getModulesInfo;
48
+ private getLatestVersion;
49
+ private getCpuInfo;
50
+ private getMemoryInfo;
51
+ private getDiskInfo;
52
+ private getDiskCommand;
53
+ private parseWindowsDiskInfo;
54
+ private parseUnixDiskInfo;
55
+ }
56
+ //# sourceMappingURL=core.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.service.d.ts","sourceRoot":"","sources":["../../src/core/core.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAO/C,qBACa,WAAW;IACV,OAAO,CAAC,aAAa;gBAAb,aAAa,EAAE,aAAa;IAE1C,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsBX,OAAO,CAAC,iBAAiB;YAqBX,eAAe;YAgCf,YAAY;YA4CZ,cAAc;YAoCd,gBAAgB;IAkB9B,OAAO,CAAC,UAAU;IASlB,OAAO,CAAC,aAAa;YAOP,WAAW;IA2BzB,OAAO,CAAC,cAAc;IAYtB,OAAO,CAAC,oBAAoB;IAgB5B,OAAO,CAAC,iBAAiB;CAkB1B"}
@@ -0,0 +1,300 @@
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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.CoreService = void 0;
46
+ const prisma_1 = require("@hedhog/prisma");
47
+ const common_1 = require("@nestjs/common");
48
+ const child_process_1 = require("child_process");
49
+ const fs = __importStar(require("fs"));
50
+ const os = __importStar(require("os"));
51
+ const path = __importStar(require("path"));
52
+ let CoreService = class CoreService {
53
+ constructor(prismaService) {
54
+ this.prismaService = prismaService;
55
+ }
56
+ async index() {
57
+ const cpus = os.cpus();
58
+ const totalSpeed = cpus.reduce((acc, cpu) => acc + cpu.speed, 0);
59
+ const averageSpeed = totalSpeed / cpus.length;
60
+ return {
61
+ os: {
62
+ name: this.getFriendlyOSName(),
63
+ platform: os.platform(),
64
+ version: os.release(),
65
+ architecture: os.arch(),
66
+ uptime: os.uptime(),
67
+ cpu: this.getCpuInfo(cpus, averageSpeed),
68
+ memory: this.getMemoryInfo(),
69
+ disk: await this.getDiskInfo(),
70
+ },
71
+ modules: await this.getModulesInfo(),
72
+ users: await this.getUsersInfo(),
73
+ database: await this.getDatabaseInfo(),
74
+ };
75
+ }
76
+ getFriendlyOSName() {
77
+ switch (os.platform()) {
78
+ case 'aix':
79
+ return `AIX`;
80
+ case 'darwin':
81
+ return `macOS`;
82
+ case 'freebsd':
83
+ return `FreeBSD`;
84
+ case 'linux':
85
+ return `Linux`;
86
+ case 'openbsd':
87
+ return `OpenBSD`;
88
+ case 'sunos':
89
+ return `SunOS`;
90
+ case 'win32':
91
+ return `Windows`;
92
+ default:
93
+ return `Unknown`;
94
+ }
95
+ }
96
+ async getDatabaseInfo() {
97
+ let connections, size, queriesPerSecond;
98
+ if (process.env.DATABASE_URL.includes('postgres')) {
99
+ [connections, size, queriesPerSecond] = await Promise.all([
100
+ this.prismaService.$queryRaw `SELECT COUNT(*) FROM pg_stat_activity`, // For PostgreSQL
101
+ this.prismaService
102
+ .$queryRaw `SELECT pg_database_size(current_database())`, // For PostgreSQL
103
+ this.prismaService
104
+ .$queryRaw `SELECT sum(numbackends) FROM pg_stat_database`, // For PostgreSQL
105
+ ]);
106
+ }
107
+ else if (process.env.DATABASE_URL.includes('mysql')) {
108
+ [connections, size, queriesPerSecond] = await Promise.all([
109
+ this.prismaService
110
+ .$queryRaw `SHOW STATUS WHERE variable_name = 'Threads_connected'`, // For MySQL
111
+ this.prismaService
112
+ .$queryRaw `SELECT SUM(data_length + index_length) AS size FROM information_schema.tables WHERE table_schema = DATABASE()`, // For MySQL
113
+ this.prismaService
114
+ .$queryRaw `SHOW STATUS WHERE variable_name = 'Queries'`, // For MySQL
115
+ ]);
116
+ }
117
+ else {
118
+ throw new Error('Unsupported database type');
119
+ }
120
+ return {
121
+ connections: +String(connections[0].count || connections[0].Value) || 0,
122
+ size: +String(size[0].pg_database_size || size[0].size) || 0,
123
+ queriesPerSecond: +String(queriesPerSecond[0].sum || queriesPerSecond[0].Value) || 0,
124
+ };
125
+ }
126
+ async getUsersInfo() {
127
+ const users = await this.prismaService.user.findMany({
128
+ include: {
129
+ role_user: {
130
+ where: {
131
+ role_id: 1,
132
+ },
133
+ select: {
134
+ role_id: true,
135
+ },
136
+ },
137
+ },
138
+ });
139
+ const activities = await this.prismaService.user_activity.findMany({
140
+ where: {
141
+ created_at: {
142
+ gte: new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
143
+ },
144
+ },
145
+ take: 10,
146
+ orderBy: {
147
+ created_at: 'desc',
148
+ },
149
+ select: {
150
+ created_at: true,
151
+ message: true,
152
+ user: {
153
+ select: {
154
+ name: true,
155
+ id: true,
156
+ },
157
+ },
158
+ },
159
+ });
160
+ return {
161
+ total: users.length,
162
+ admin: users.filter((user) => user.role_user.length > 0).length,
163
+ active: 0,
164
+ activities,
165
+ };
166
+ }
167
+ async getModulesInfo() {
168
+ const packageJsonPath = path.resolve(process.cwd(), 'package.json');
169
+ return new Promise((resolve, reject) => {
170
+ fs.readFile(packageJsonPath, 'utf8', async (err, data) => {
171
+ if (err) {
172
+ reject(`Error reading package.json: ${err.message}`);
173
+ return;
174
+ }
175
+ try {
176
+ const packageJson = JSON.parse(data);
177
+ const dependencies = packageJson.dependencies || {};
178
+ const hedgehogModules = await Promise.all(Object.keys(dependencies)
179
+ .filter((key) => key.startsWith('@hedhog'))
180
+ .map(async (key) => {
181
+ const currentVersion = dependencies[key].replace(/^[\^~]/, '');
182
+ const latestVersion = await this.getLatestVersion(key);
183
+ return {
184
+ name: key,
185
+ version: dependencies[key],
186
+ latestVersion,
187
+ upToDate: currentVersion === latestVersion,
188
+ };
189
+ }));
190
+ resolve(hedgehogModules);
191
+ }
192
+ catch (parseError) {
193
+ reject(`Error parsing package.json: ${parseError === null || parseError === void 0 ? void 0 : parseError.message}`);
194
+ }
195
+ });
196
+ });
197
+ }
198
+ async getLatestVersion(moduleName) {
199
+ return new Promise((resolve, reject) => {
200
+ (0, child_process_1.exec)(`npm show ${moduleName} version`, (error, stdout, stderr) => {
201
+ if (error) {
202
+ reject(`Error fetching latest version for ${moduleName}: ${error.message}`);
203
+ return;
204
+ }
205
+ if (stderr) {
206
+ reject(`stderr: ${stderr}`);
207
+ return;
208
+ }
209
+ resolve(stdout.trim());
210
+ });
211
+ });
212
+ }
213
+ getCpuInfo(cpus, averageSpeed) {
214
+ return {
215
+ model: cpus[0].model,
216
+ speed: averageSpeed,
217
+ physicalCores: cpus.length / 2, // Assuming hyper-threading, this gives physical cores
218
+ virtualCores: cpus.length,
219
+ };
220
+ }
221
+ getMemoryInfo() {
222
+ return {
223
+ total: os.totalmem(),
224
+ free: os.freemem(),
225
+ };
226
+ }
227
+ async getDiskInfo() {
228
+ return new Promise((resolve, reject) => {
229
+ const command = this.getDiskCommand();
230
+ if (!command) {
231
+ reject('Unsupported OS');
232
+ return;
233
+ }
234
+ (0, child_process_1.exec)(command, (error, stdout, stderr) => {
235
+ if (error) {
236
+ reject(`error: ${error.message}`);
237
+ return;
238
+ }
239
+ if (stderr) {
240
+ reject(`stderr: ${stderr}`);
241
+ return;
242
+ }
243
+ const diskInfo = os.platform() === 'win32'
244
+ ? this.parseWindowsDiskInfo(stdout)
245
+ : this.parseUnixDiskInfo(stdout);
246
+ resolve(diskInfo);
247
+ });
248
+ });
249
+ }
250
+ getDiskCommand() {
251
+ switch (os.platform()) {
252
+ case 'win32':
253
+ return 'wmic logicaldisk get size,freespace,caption';
254
+ case 'darwin':
255
+ case 'linux':
256
+ return 'df -h';
257
+ default:
258
+ return null;
259
+ }
260
+ }
261
+ parseWindowsDiskInfo(output) {
262
+ const lines = output.trim().split('\n');
263
+ const result = [];
264
+ for (let i = 1; i < lines.length; i++) {
265
+ const parts = lines[i].trim().split(/\s+/);
266
+ if (parts.length === 3) {
267
+ result.push({
268
+ filesystem: parts[0].replace(':', ''),
269
+ size: parseInt(parts[1], 10),
270
+ free: parseInt(parts[2], 10),
271
+ });
272
+ }
273
+ }
274
+ return result;
275
+ }
276
+ parseUnixDiskInfo(output) {
277
+ const lines = output.trim().split('\n');
278
+ const result = [];
279
+ for (let i = 1; i < lines.length; i++) {
280
+ const parts = lines[i].split(/\s+/);
281
+ if (parts.length >= 6) {
282
+ result.push({
283
+ filesystem: parts[0],
284
+ size: parts[1],
285
+ used: parts[2],
286
+ available: parts[3],
287
+ capacity: parts[4],
288
+ mountpoint: parts[5],
289
+ });
290
+ }
291
+ }
292
+ return result;
293
+ }
294
+ };
295
+ exports.CoreService = CoreService;
296
+ exports.CoreService = CoreService = __decorate([
297
+ (0, common_1.Injectable)(),
298
+ __metadata("design:paramtypes", [prisma_1.PrismaService])
299
+ ], CoreService);
300
+ //# sourceMappingURL=core.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.service.js","sourceRoot":"","sources":["../../src/core/core.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA+C;AAC/C,2CAA4C;AAC5C,iDAAqC;AACrC,uCAAyB;AACzB,uCAAyB;AACzB,2CAA6B;AAGtB,IAAM,WAAW,GAAjB,MAAM,WAAW;IACtB,YAAoB,aAA4B;QAA5B,kBAAa,GAAb,aAAa,CAAe;IAAG,CAAC;IAEpD,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC;QACvB,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACjE,MAAM,YAAY,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;QAE9C,OAAO;YACL,EAAE,EAAE;gBACF,IAAI,EAAE,IAAI,CAAC,iBAAiB,EAAE;gBAC9B,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE;gBACvB,OAAO,EAAE,EAAE,CAAC,OAAO,EAAE;gBACrB,YAAY,EAAE,EAAE,CAAC,IAAI,EAAE;gBACvB,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE;gBACnB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,YAAY,CAAC;gBACxC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE;gBAC5B,IAAI,EAAE,MAAM,IAAI,CAAC,WAAW,EAAE;aAC/B;YACD,OAAO,EAA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C,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;gBACtB,MAAM,CAAC,IAAI,CAAC;oBACV,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC;oBACpB,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;oBACd,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;oBACd,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC;oBACnB,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC;oBAClB,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC;iBACrB,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAA;AAzQY,kCAAW;sBAAX,WAAW;IADvB,IAAA,mBAAU,GAAE;qCAEwB,sBAAa;GADrC,WAAW,CAyQvB"}
package/hedhog.yaml CHANGED
@@ -529,6 +529,21 @@ tables:
529
529
  - type: created_at
530
530
  - type: updated_at
531
531
  ifNotExists: true
532
+ user_activity:
533
+ columns:
534
+ - type: pk
535
+ - name: user_id
536
+ type: fk
537
+ references:
538
+ table: user
539
+ column: id
540
+ onDelete: CASCADE
541
+ - name: ip
542
+ - name: user_agent
543
+ - name: message
544
+ - type: created_at
545
+ - type: updated_at
546
+ ifNotExists: true
532
547
  user:
533
548
  columns:
534
549
  - type: pk
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hedhog/admin",
3
- "version": "0.48.2",
3
+ "version": "0.48.4",
4
4
  "private": false,
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -5,6 +5,7 @@ import { PrismaModule } from '@hedhog/prisma';
5
5
  import { forwardRef, Module } from '@nestjs/common';
6
6
  import { ConfigModule } from '@nestjs/config';
7
7
  import { AuthModule } from './auth/auth.module';
8
+ import { CoreModule } from './core/core.module';
8
9
  import { MenuModule } from './menu/menu.module';
9
10
  import { RoleModule } from './role/role.module';
10
11
  import { RouteModule } from './route/route.module';
@@ -24,6 +25,7 @@ import { UserModule } from './user/user.module';
24
25
  forwardRef(() => ScreenModule),
25
26
  forwardRef(() => LocaleModule),
26
27
  forwardRef(() => UserModule),
28
+ forwardRef(() => CoreModule),
27
29
  ],
28
30
  exports: [
29
31
  UserModule,
@@ -0,0 +1,15 @@
1
+ import { Controller, forwardRef, Get, Inject } from '@nestjs/common';
2
+ import { CoreService } from './core.service';
3
+
4
+ @Controller('core')
5
+ export class CoreController {
6
+ constructor(
7
+ @Inject(forwardRef(() => CoreService))
8
+ private readonly service: CoreService,
9
+ ) {}
10
+
11
+ @Get()
12
+ async index() {
13
+ return this.service.index();
14
+ }
15
+ }
@@ -0,0 +1,28 @@
1
+ import { PrismaModule } from '@hedhog/prisma';
2
+ import { forwardRef, Module } from '@nestjs/common';
3
+ import { JwtModule } from '@nestjs/jwt';
4
+ import { CoreController } from './core.controller';
5
+ import { CoreService } from './core.service';
6
+
7
+ @Module({
8
+ imports: [
9
+ forwardRef(() =>
10
+ JwtModule.registerAsync({
11
+ global: true,
12
+ useFactory: () => {
13
+ return {
14
+ secret: String(process.env.JWT_SECRET),
15
+ global: true,
16
+ signOptions: {
17
+ expiresIn: process.env.JWT_EXPIRES_IN || '30d',
18
+ },
19
+ };
20
+ },
21
+ }),
22
+ ),
23
+ forwardRef(() => PrismaModule),
24
+ ],
25
+ controllers: [CoreController],
26
+ providers: [CoreService],
27
+ })
28
+ export class CoreModule {}
@@ -0,0 +1,274 @@
1
+ import { PrismaService } from '@hedhog/prisma';
2
+ import { Injectable } from '@nestjs/common';
3
+ import { exec } from 'child_process';
4
+ import * as fs from 'fs';
5
+ import * as os from 'os';
6
+ import * as path from 'path';
7
+
8
+ @Injectable()
9
+ export class CoreService {
10
+ constructor(private prismaService: PrismaService) {}
11
+
12
+ async index() {
13
+ const cpus = os.cpus();
14
+ const totalSpeed = cpus.reduce((acc, cpu) => acc + cpu.speed, 0);
15
+ const averageSpeed = totalSpeed / cpus.length;
16
+
17
+ return {
18
+ os: {
19
+ name: this.getFriendlyOSName(),
20
+ platform: os.platform(),
21
+ version: os.release(),
22
+ architecture: os.arch(),
23
+ uptime: os.uptime(),
24
+ cpu: this.getCpuInfo(cpus, averageSpeed),
25
+ memory: this.getMemoryInfo(),
26
+ disk: await this.getDiskInfo(),
27
+ },
28
+ modules: await this.getModulesInfo(),
29
+ users: await this.getUsersInfo(),
30
+ database: await this.getDatabaseInfo(),
31
+ };
32
+ }
33
+
34
+ private getFriendlyOSName() {
35
+ switch (os.platform()) {
36
+ case 'aix':
37
+ return `AIX`;
38
+ case 'darwin':
39
+ return `macOS`;
40
+ case 'freebsd':
41
+ return `FreeBSD`;
42
+ case 'linux':
43
+ return `Linux`;
44
+ case 'openbsd':
45
+ return `OpenBSD`;
46
+ case 'sunos':
47
+ return `SunOS`;
48
+ case 'win32':
49
+ return `Windows`;
50
+ default:
51
+ return `Unknown`;
52
+ }
53
+ }
54
+
55
+ private async getDatabaseInfo() {
56
+ let connections, size, queriesPerSecond;
57
+
58
+ if (process.env.DATABASE_URL.includes('postgres')) {
59
+ [connections, size, queriesPerSecond] = await Promise.all([
60
+ this.prismaService.$queryRaw`SELECT COUNT(*) FROM pg_stat_activity`, // For PostgreSQL
61
+ this.prismaService
62
+ .$queryRaw`SELECT pg_database_size(current_database())`, // For PostgreSQL
63
+ this.prismaService
64
+ .$queryRaw`SELECT sum(numbackends) FROM pg_stat_database`, // For PostgreSQL
65
+ ]);
66
+ } else if (process.env.DATABASE_URL.includes('mysql')) {
67
+ [connections, size, queriesPerSecond] = await Promise.all([
68
+ this.prismaService
69
+ .$queryRaw`SHOW STATUS WHERE variable_name = 'Threads_connected'`, // For MySQL
70
+ this.prismaService
71
+ .$queryRaw`SELECT SUM(data_length + index_length) AS size FROM information_schema.tables WHERE table_schema = DATABASE()`, // For MySQL
72
+ this.prismaService
73
+ .$queryRaw`SHOW STATUS WHERE variable_name = 'Queries'`, // For MySQL
74
+ ]);
75
+ } else {
76
+ throw new Error('Unsupported database type');
77
+ }
78
+
79
+ return {
80
+ connections: +String(connections[0].count || connections[0].Value) || 0,
81
+ size: +String(size[0].pg_database_size || size[0].size) || 0,
82
+ queriesPerSecond:
83
+ +String(queriesPerSecond[0].sum || queriesPerSecond[0].Value) || 0,
84
+ };
85
+ }
86
+
87
+ private async getUsersInfo() {
88
+ const users = await this.prismaService.user.findMany({
89
+ include: {
90
+ role_user: {
91
+ where: {
92
+ role_id: 1,
93
+ },
94
+ select: {
95
+ role_id: true,
96
+ },
97
+ },
98
+ },
99
+ });
100
+
101
+ const activities = await this.prismaService.user_activity.findMany({
102
+ where: {
103
+ created_at: {
104
+ gte: new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
105
+ },
106
+ },
107
+ take: 10,
108
+ orderBy: {
109
+ created_at: 'desc',
110
+ },
111
+ select: {
112
+ created_at: true,
113
+ message: true,
114
+ user: {
115
+ select: {
116
+ name: true,
117
+ id: true,
118
+ },
119
+ },
120
+ },
121
+ });
122
+
123
+ return {
124
+ total: users.length,
125
+ admin: users.filter((user) => user.role_user.length > 0).length,
126
+ active: 0,
127
+ activities,
128
+ };
129
+ }
130
+
131
+ private async getModulesInfo() {
132
+ const packageJsonPath = path.resolve(process.cwd(), 'package.json');
133
+
134
+ return new Promise((resolve, reject) => {
135
+ fs.readFile(packageJsonPath, 'utf8', async (err, data) => {
136
+ if (err) {
137
+ reject(`Error reading package.json: ${err.message}`);
138
+ return;
139
+ }
140
+
141
+ try {
142
+ const packageJson = JSON.parse(data);
143
+ const dependencies = packageJson.dependencies || {};
144
+ const hedgehogModules = await Promise.all(
145
+ Object.keys(dependencies)
146
+ .filter((key) => key.startsWith('@hedhog'))
147
+ .map(async (key) => {
148
+ const currentVersion = dependencies[key].replace(/^[\^~]/, '');
149
+ const latestVersion = await this.getLatestVersion(key);
150
+ return {
151
+ name: key,
152
+ version: dependencies[key],
153
+ latestVersion,
154
+ upToDate: currentVersion === latestVersion,
155
+ };
156
+ }),
157
+ );
158
+
159
+ resolve(hedgehogModules);
160
+ } catch (parseError: any) {
161
+ reject(`Error parsing package.json: ${parseError?.message}`);
162
+ }
163
+ });
164
+ });
165
+ }
166
+
167
+ private async getLatestVersion(moduleName: string): Promise<string> {
168
+ return new Promise((resolve, reject) => {
169
+ exec(`npm show ${moduleName} version`, (error, stdout, stderr) => {
170
+ if (error) {
171
+ reject(
172
+ `Error fetching latest version for ${moduleName}: ${error.message}`,
173
+ );
174
+ return;
175
+ }
176
+ if (stderr) {
177
+ reject(`stderr: ${stderr}`);
178
+ return;
179
+ }
180
+ resolve(stdout.trim());
181
+ });
182
+ });
183
+ }
184
+
185
+ private getCpuInfo(cpus: os.CpuInfo[], averageSpeed: number) {
186
+ return {
187
+ model: cpus[0].model,
188
+ speed: averageSpeed,
189
+ physicalCores: cpus.length / 2, // Assuming hyper-threading, this gives physical cores
190
+ virtualCores: cpus.length,
191
+ };
192
+ }
193
+
194
+ private getMemoryInfo() {
195
+ return {
196
+ total: os.totalmem(),
197
+ free: os.freemem(),
198
+ };
199
+ }
200
+
201
+ private async getDiskInfo() {
202
+ return new Promise((resolve, reject) => {
203
+ const command = this.getDiskCommand();
204
+ if (!command) {
205
+ reject('Unsupported OS');
206
+ return;
207
+ }
208
+
209
+ exec(command, (error, stdout, stderr) => {
210
+ if (error) {
211
+ reject(`error: ${error.message}`);
212
+ return;
213
+ }
214
+ if (stderr) {
215
+ reject(`stderr: ${stderr}`);
216
+ return;
217
+ }
218
+
219
+ const diskInfo =
220
+ os.platform() === 'win32'
221
+ ? this.parseWindowsDiskInfo(stdout)
222
+ : this.parseUnixDiskInfo(stdout);
223
+ resolve(diskInfo);
224
+ });
225
+ });
226
+ }
227
+
228
+ private getDiskCommand() {
229
+ switch (os.platform()) {
230
+ case 'win32':
231
+ return 'wmic logicaldisk get size,freespace,caption';
232
+ case 'darwin':
233
+ case 'linux':
234
+ return 'df -h';
235
+ default:
236
+ return null;
237
+ }
238
+ }
239
+
240
+ private parseWindowsDiskInfo(output: string) {
241
+ const lines = output.trim().split('\n');
242
+ const result = [];
243
+ for (let i = 1; i < lines.length; i++) {
244
+ const parts = lines[i].trim().split(/\s+/);
245
+ if (parts.length === 3) {
246
+ result.push({
247
+ filesystem: parts[0].replace(':', ''),
248
+ size: parseInt(parts[1], 10),
249
+ free: parseInt(parts[2], 10),
250
+ });
251
+ }
252
+ }
253
+ return result;
254
+ }
255
+
256
+ private parseUnixDiskInfo(output: string) {
257
+ const lines = output.trim().split('\n');
258
+ const result = [];
259
+ for (let i = 1; i < lines.length; i++) {
260
+ const parts = lines[i].split(/\s+/);
261
+ if (parts.length >= 6) {
262
+ result.push({
263
+ filesystem: parts[0],
264
+ size: parts[1],
265
+ used: parts[2],
266
+ available: parts[3],
267
+ capacity: parts[4],
268
+ mountpoint: parts[5],
269
+ });
270
+ }
271
+ }
272
+ return result;
273
+ }
274
+ }