const { parentPort } = require('worker_threads'); const path = require('path'); // ProjectInspector class will be imported in the message handler /** * Inspector Worker - Project Analysis Worker Thread * * Worker Thread สำหรับการวิเคราะห์โปรเจกต์แบบไม่ blocking UI * ทำงานแยกต่างหากจาก Main Process เพื่อป้องกันการค้างของ UI * * การทำงาน: * 1. รับ path จาก Main Process ผ่าน message * 2. ใช้ ProjectInspector instance ที่ถูก export มา * 3. เริ่มการวิเคราะห์แบบ asynchronous * 4. ส่งผลลัพธ์กลับไปให้ Main Process * 5. จัดการ error ทุกกรณี */ console.log(' [Inspector Worker] Worker thread started'); // เมื่อได้รับคำสั่งจาก Main Process parentPort.on('message', async (data) => { const { projectPath, scanTarget = 'โปรเจกต์' } = data; try { console.log(` [Inspector Worker] Received job to analyze ${scanTarget}: ${projectPath}`); // ส่งสถานะเริ่มต้นกลับไป parentPort.postMessage({ type: 'progress', message: `เริ่มการวิเคราะห์ ${scanTarget}...`, progress: 0 }); // สร้าง ProjectInspector instance พร้อม status callback const statusUpdateCallback = (message) => { // ส่งสถานะอัปเดตไปยัง Main Process ทันที parentPort.postMessage({ type: 'status-update', data: message }); }; // --- เพิ่มการตรวจสอบ Error ตรงนี้ --- let ProjectInspector; try { // ลอง require ไฟล์ ProjectInspector ProjectInspector = require('./project-inspector'); } catch (e) { throw new Error(`Failed to require ProjectInspector: ${e.message}`); } if (typeof ProjectInspector !== 'function') { throw new Error('ProjectInspector that was required is not a constructor. Check module.exports.'); } // สร้าง ProjectInspector instance โดยส่ง callback เข้าไป const inspector = new ProjectInspector(statusUpdateCallback); console.log(` [Inspector Worker] Created ProjectInspector with status callback`); // ส่งสถานะการเตรียมตัว parentPort.postMessage({ type: 'progress', message: 'กำลังเตรียมเครื่องมือวิเคราะห์...', progress: 10 }); // เริ่มการวิเคราะห์ (ต่อไปนี้เป็นงานหนัก) const startTime = Date.now(); console.log(` [Inspector Worker] Starting intensive analysis of: ${projectPath}`); // ส่งสถานะเริ่มสแกน parentPort.postMessage({ type: 'progress', message: 'กำลังสแกนไฟล์ทั้งหมด...', progress: 25 }); // ทำการวิเคราะห์หลัก (จุดที่ใช้เวลานาน) const analysisResult = await inspector.analyzeProject(projectPath); const endTime = Date.now(); const duration = (endTime - startTime) / 1000; console.log(` [Inspector Worker] Analysis completed in ${duration}s`); console.log(` [Inspector Worker] Found ${analysisResult.totalFiles} files, ${analysisResult.totalIssues} issues`); // ส่งสถานะเสร็จสิ้น parentPort.postMessage({ type: 'progress', message: 'การวิเคราะห์เสร็จสมบูรณ์!', progress: 100 }); // ส่งผลลัพธ์สุดท้ายกลับไปให้ Main Process parentPort.postMessage({ type: 'analysis-result', success: true, analysis: analysisResult, scanTarget, duration, timestamp: new Date().toISOString() }); // Force cleanup and graceful exit after successful completion console.log(' [Inspector Worker] Results sent, scheduling graceful exit...'); setTimeout(() => { console.log(' [Inspector Worker] Analysis complete, terminating gracefully'); process.exit(0); }, 100); } catch (error) { console.error(` [Inspector Worker] Analysis failed:`, error); // ส่ง Error ที่ชัดเจนกลับไป parentPort.postMessage({ type: 'analysis-result', success: false, error: { message: error.message, stack: error.stack, name: error.name, timestamp: new Date().toISOString() } }); // Force cleanup and exit after error setTimeout(() => { console.log(' [Inspector Worker] Error handled, terminating gracefully'); process.exit(0); }, 50); } }); // จัดการ error ที่ไม่คาดคิด process.on('unhandledRejection', (reason, promise) => { console.error(' [Inspector Worker] Unhandled Rejection at:', promise, 'reason:', reason); parentPort.postMessage({ type: 'error', error: { message: `Unhandled rejection: ${reason}`, stack: reason?.stack || 'No stack trace available', name: 'UnhandledRejection', timestamp: new Date().toISOString() } }); }); process.on('uncaughtException', (error) => { console.error(' [Inspector Worker] Uncaught Exception:', error); parentPort.postMessage({ type: 'error', error: { message: error.message, stack: error.stack, name: error.name, timestamp: new Date().toISOString() } }); // Don't exit immediately to allow for graceful cleanup setTimeout(() => { console.log(' [Inspector Worker] Graceful shutdown after uncaught exception'); process.exit(0); }, 100); }); console.log(' [Inspector Worker] Listening for messages from Main Process...');