File size: 12,239 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// ApiTraceDebugger.js

const fs = require('fs');
const path = require('path');
const { app } = require('electron');

// เก็บ reference ของฟังก์ชันดั้งเดิมไว้ก่อนที่จะ patch เพื่อป้องกัน circular dependency
const originalFs = {
    readFileSync: fs.readFileSync,
    writeFileSync: fs.writeFileSync,
    existsSync: fs.existsSync,
    mkdirSync: fs.mkdirSync,
    readdirSync: fs.readdirSync,
    unlinkSync: fs.unlinkSync,
    statSync: fs.statSync,
    createWriteStream: fs.createWriteStream
};

const originalPath = {
    join: path.join,
    resolve: path.resolve,
    dirname: path.dirname,
    extname: path.extname,
    basename: path.basename,
    relative: path.relative
};

/**
 * [ปรับปรุงใหม่] ระบบดีบั๊กสำหรับติดตามและบันทึก API Call ลงไฟล์แบบ Real-time
 * @class ApiTraceDebugger
 */
class ApiTraceDebugger {
    constructor() {
        this.isActive = false;
        this.logStream = null; // Stream สำหรับเขียนไฟล์
        this.logFilePath = null; // Path ของไฟล์ Log ปัจจุบัน
        this.originalFunctions = new Map();
        this.pluginsPath = this._getPluginsPath();
    }

    /**
     * [ปรับปรุงใหม่] เริ่มการทำงาน, สร้างไฟล์ และเปิด Stream
     */
    start() {
        if (this.isActive) { return; }

        try {
            // ตรวจสอบว่า app พร้อมใช้งาน
            if (!app || !app.getPath) {
                console.warn('[API TRACE] App ยังไม่พร้อม ข้าม API Trace initialization');
                return;
            }

            // สร้างโฟลเดอร์สำหรับเก็บ Log ถ้ายังไม่มี
            const logDir = originalPath.join(app.getPath('userData'), 'logs', 'api-traces');
            if (!originalFs.existsSync(logDir)) {
                originalFs.mkdirSync(logDir, { recursive: true });
            }

            // สร้างชื่อไฟล์ Log ที่ไม่ซ้ำกัน
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            this.logFilePath = originalPath.join(logDir, `trace-${timestamp}.log`);

            // สร้าง Write Stream ไปยังไฟล์ Log
            this.logStream = originalFs.createWriteStream(this.logFilePath, { flags: 'a' });

            this.isActive = true;
            this._writeHeader(); // เขียนข้อมูลเริ่มต้นลงไฟล์
            console.log(`[API TRACE]  REAL-TIME MODE: เริ่มบันทึก Log ไปที่ไฟล์: ${this.logFilePath}`);

            // เริ่มทำการ Patch ฟังก์ชันเป้าหมาย
            this._patchAllFunctions();

        } catch (error) {
            console.error('[API TRACE] ไม่สามารถเริ่มระบบ Real-time logger ได้:', error);
            this.isActive = false;
        }
    }

    /**
     * [ปรับปรุงใหม่] หยุดการทำงานและปิด Stream
     */
    stop() {
        if (!this.isActive) { return; }
        this.isActive = false;
        console.log('[API TRACE]  หยุดการทำงานและกำลังคืนค่าฟังก์ชันดั้งเดิม...');

        // คืนค่าฟังก์ชันดั้งเดิม
        this._unpatchAllFunctions();

        // ปิด Stream และไฟล์ Log
        if (this.logStream) {
            this.logStream.end('\n--- LOGGING STOPPED ---\n');
            this.logStream = null;
            console.log('[API TRACE]  ปิดไฟล์ Log เรียบร้อยแล้ว');
        }
    }

    /**
     * [เพิ่มใหม่] ฟังก์ชันสำหรับหา Path ของโฟลเดอร์ plugins
     * @private
     */
    _getPluginsPath() {
        try {
            // ตรวจสอบว่า app พร้อมใช้งานหรือไม่ก่อน
            if (!app || !app.getPath) {
                console.warn('[API TRACE] App ยังไม่พร้อม ข้าม plugins path detection');
                return null;
            }

            if (app.isPackaged) {
                // โหมด Production: โฟลเดอร์ plugins จะอยู่ข้างไฟล์ .exe
                // ใช้ originalPath เพื่อป้องกัน circular dependency
                return originalPath.join(originalPath.dirname(app.getPath('exe')), 'plugins');
            } else {
                // โหมด Development: อยู่ใน AppData
                // ใช้ originalPath เพื่อป้องกัน circular dependency
                return originalPath.join(app.getPath('userData'), 'plugins');
            }
        } catch (e) {
            console.warn('[API TRACE] ไม่สามารถหา Path ของโฟลเดอร์ plugins ได้:', e.message);
            return null;
        }
    }

    /**
     * [แก้ไข] เพิ่มการกรองโฟลเดอร์ plugins เข้าไป
     * ฟังก์ชันค้นหาไฟล์และบรรทัดที่เรียกใช้ (Call Site)
     * @private
     */
    _getCallSite() {
        const originalPrepareStackTrace = Error.prepareStackTrace;
        try {
            Error.prepareStackTrace = (_, stack) => stack;
            const err = new Error();
            const stack = err.stack;
            Error.prepareStackTrace = originalPrepareStackTrace;

            for (let i = 2; i < stack.length; i++) {
                const frame = stack[i];
                const fileName = frame.getFileName();

                if (fileName) {
                    const isNodeModule = fileName.includes('node_modules');
                    const isInternal = fileName.startsWith('node:internal');
                    const isSelf = fileName.endsWith('ApiTraceDebugger.js');
                    // [แก้ไข] ตรวจสอบว่าเป็นไฟล์ในโฟลเดอร์ plugins หรือไม่ และใช้ originalPath
                    const isPlugin = this.pluginsPath ? fileName.startsWith(this.pluginsPath) : false;

                    if (!isNodeModule && !isInternal && !isSelf && !isPlugin) {
                        // ใช้ originalPath เพื่อป้องกัน circular dependency
                        const relativePath = originalPath.relative(process.cwd(), fileName);
                        return `${relativePath}:${frame.getLineNumber()}`;
                    }
                }
            }
        } catch (e) {
            Error.prepareStackTrace = originalPrepareStackTrace;
        }
        return 'unknown';
    }

    /**
     * [ปรับปรุงใหม่] ฟังก์ชันภายในสำหรับบันทึก Log โดยจะเขียนลงไฟล์ทันที
     */
    _logTrace(moduleName, functionName, args, result, error, callSite) {
        // ถ้า stream ไม่พร้อมทำงาน ให้ข้ามไป
        if (!this.logStream) { return; }

        const logType = error ? '[API-ERR ]' : '[API-CALL]';
        const timestamp = new Date().toISOString();

        // จัดรูปแบบ Arguments และ ผลลัพธ์
        const formatArg = (arg) => {
            if (typeof arg === 'string') {
                if (arg.length > 150) return `'${arg.substring(0, 147)}...'`;
                return `'${arg}'`;
            }
            if (typeof arg === 'object' && arg !== null) return JSON.stringify(arg);
            return String(arg);
        };
        const argsString = args.map(formatArg).join(', ');

        let outcomeString = '';
        if (error) {
            outcomeString = `=> ERROR: ${error.message}`;
        } else {
            let resultStr = JSON.stringify(result);
            if (resultStr && resultStr.length > 200) {
                resultStr = resultStr.substring(0, 197) + '...';
            }
            outcomeString = `=> RESULT: ${resultStr}`;
        }

        // สร้าง Log 1 บรรทัดและเขียนลง Stream
        const line = `${timestamp} ${logType} ${moduleName}.${functionName}(${argsString}) ${outcomeString} (from ${callSite})\n`;
        this.logStream.write(line);
    }

    /**
     * ฟังก์ชันภายในสำหรับทำการ Patch (แทนที่) ฟังก์ชันเป้าหมาย
     * @private
     */
    _patchFunction(module, moduleName, functionName) {
        const originalFunction = module[functionName];

        if (typeof originalFunction !== 'function' || this.originalFunctions.has(`${moduleName}.${functionName}`)) {
            return;
        }

        this.originalFunctions.set(`${moduleName}.${functionName}`, originalFunction);

        const self = this;
        const patchFunction = function (...args) {
            const callSite = self._getCallSite();

            // [แก้ไข] เพิ่มการกรอง `plugins` เข้าไปในเงื่อนไข และใช้ originalPath
            const isNodeModule = callSite.includes('node_modules');
            const isPlugin = self.pluginsPath ? callSite.startsWith(originalPath.relative(process.cwd(), self.pluginsPath)) : false;

            // ถ้ามาจาก node_modules หรือ plugins ให้ข้ามการบันทึก Log
            if (isNodeModule || isPlugin) {
                return originalFunction.apply(this, args);
            }

            let result, error = null;
            try {
                result = originalFunction.apply(this, args);
            } catch (e) {
                error = e;
            }

            self._logTrace(moduleName, functionName, args, result, error, callSite);

            if (error) { throw error; }
            return result;
        };

        module[functionName] = patchFunction;
    }

    // ฟังก์ชันสำหรับวนลูป Patch (แยกออกมาเพื่อความสะอาด)
    _patchAllFunctions() {
        const modulesToTrace = {
            fs: ['readFileSync', 'writeFileSync', 'existsSync', 'mkdirSync', 'readdirSync', 'unlinkSync', 'statSync'],
            path: ['join', 'resolve', 'dirname', 'extname', 'basename']
        };
        for (const moduleName in modulesToTrace) {
            const functions = modulesToTrace[moduleName];
            const module = require(moduleName);
            for (const functionName of functions) {
                this._patchFunction(module, moduleName, functionName);
            }
        }
    }

    // ฟังก์ชันสำหรับวนลูป Unpatch
    _unpatchAllFunctions() {
        for (const [key, originalFunction] of this.originalFunctions.entries()) {
            const [module, functionName] = key.split('.');
            require(module)[functionName] = originalFunction;
        }
        this.originalFunctions.clear();
    }

    // เขียน Header ลงไฟล์ Log
    _writeHeader() {
        if (!this.logStream) return;
        const header = `
===========================================
  Chahuadev API Trace Log (Real-time)
===========================================
Start Time  : ${new Date().toISOString()}
Platform    : ${process.platform}
Version     : ${app.getVersion ? app.getVersion() : 'Unknown'}
Log File    : ${this.logFilePath}
-------------------------------------------

`;
        this.logStream.write(header);
    }
}

module.exports = new ApiTraceDebugger();