File size: 2,313 Bytes
d02c2a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { NextResponse } from 'next/server';
import si from 'systeminformation';
import { createRequire } from 'module';
import os from 'os';
import { CpuInfo } from '@/types';

const isMac = os.platform() === 'darwin';

export async function GET() {
  try {
    const cpuInfoRaw = await si.cpu();
    let cpuInfo: CpuInfo;

    if (isMac) {
      try {
        const nativeRequire = createRequire(import.meta.url);
        const ms = nativeRequire('macstats') as any;
        const ramData = ms.getRAMUsageSync();
        const cpuData = ms.getCpuDataSync();

        cpuInfo = {
          name: `${cpuInfoRaw.manufacturer} ${cpuInfoRaw.brand}`,
          cores: cpuInfoRaw.cores,
          temperature: cpuData.temperature || 0,
          totalMemory: ramData.total / (1024 * 1024),
          availableMemory: ramData.free / (1024 * 1024),
          freeMemory: ramData.free / (1024 * 1024),
          currentLoad: (await si.currentLoad()).currentLoad || 0,
        };
      } catch {
        // Fallback to systeminformation if macstats fails
        const memoryData = await si.mem();
        cpuInfo = {
          name: `${cpuInfoRaw.manufacturer} ${cpuInfoRaw.brand}`,
          cores: cpuInfoRaw.cores,
          temperature: (await si.cpuTemperature()).main || 0,
          totalMemory: memoryData.total / (1024 * 1024),
          availableMemory: memoryData.available / (1024 * 1024),
          freeMemory: memoryData.free / (1024 * 1024),
          currentLoad: (await si.currentLoad()).currentLoad || 0,
        };
      }
    } else {
      const memoryData = await si.mem();
      cpuInfo = {
        name: `${cpuInfoRaw.manufacturer} ${cpuInfoRaw.brand}`,
        cores: cpuInfoRaw.cores,
        temperature: (await si.cpuTemperature()).main || 0,
        totalMemory: memoryData.total / (1024 * 1024),
        availableMemory: memoryData.available / (1024 * 1024),
        freeMemory: memoryData.free / (1024 * 1024),
        currentLoad: (await si.currentLoad()).currentLoad || 0,
      };
    }

    return NextResponse.json(cpuInfo);
  } catch (error) {
    console.error('Error fetching CPU stats:', error);
    return NextResponse.json(
      {
        error: `Failed to fetch CPU stats: ${error instanceof Error ? error.message : String(error)}`,
      },
      { status: 500 },
    );
  }
}