diff --git a/.gitattributes b/.gitattributes
index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..0628d740511e3ddfefa1e4731b7fe47106b3d26a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,60 +1,7 @@
-*.7z filter=lfs diff=lfs merge=lfs -text
-*.arrow filter=lfs diff=lfs merge=lfs -text
-*.avro filter=lfs diff=lfs merge=lfs -text
-*.bin filter=lfs diff=lfs merge=lfs -text
-*.bz2 filter=lfs diff=lfs merge=lfs -text
-*.ckpt filter=lfs diff=lfs merge=lfs -text
-*.ftz filter=lfs diff=lfs merge=lfs -text
-*.gz filter=lfs diff=lfs merge=lfs -text
-*.h5 filter=lfs diff=lfs merge=lfs -text
-*.joblib filter=lfs diff=lfs merge=lfs -text
-*.lfs.* filter=lfs diff=lfs merge=lfs -text
-*.lz4 filter=lfs diff=lfs merge=lfs -text
-*.mds filter=lfs diff=lfs merge=lfs -text
-*.mlmodel filter=lfs diff=lfs merge=lfs -text
-*.model filter=lfs diff=lfs merge=lfs -text
-*.msgpack filter=lfs diff=lfs merge=lfs -text
-*.npy filter=lfs diff=lfs merge=lfs -text
-*.npz filter=lfs diff=lfs merge=lfs -text
-*.onnx filter=lfs diff=lfs merge=lfs -text
-*.ot filter=lfs diff=lfs merge=lfs -text
-*.parquet filter=lfs diff=lfs merge=lfs -text
-*.pb filter=lfs diff=lfs merge=lfs -text
-*.pickle filter=lfs diff=lfs merge=lfs -text
-*.pkl filter=lfs diff=lfs merge=lfs -text
-*.pt filter=lfs diff=lfs merge=lfs -text
-*.pth filter=lfs diff=lfs merge=lfs -text
-*.rar filter=lfs diff=lfs merge=lfs -text
-*.safetensors filter=lfs diff=lfs merge=lfs -text
-saved_model/**/* filter=lfs diff=lfs merge=lfs -text
-*.tar.* filter=lfs diff=lfs merge=lfs -text
-*.tar filter=lfs diff=lfs merge=lfs -text
-*.tflite filter=lfs diff=lfs merge=lfs -text
-*.tgz filter=lfs diff=lfs merge=lfs -text
-*.wasm filter=lfs diff=lfs merge=lfs -text
-*.xz filter=lfs diff=lfs merge=lfs -text
-*.zip filter=lfs diff=lfs merge=lfs -text
-*.zst filter=lfs diff=lfs merge=lfs -text
-*tfevents* filter=lfs diff=lfs merge=lfs -text
-# Audio files - uncompressed
-*.pcm filter=lfs diff=lfs merge=lfs -text
-*.sam filter=lfs diff=lfs merge=lfs -text
-*.raw filter=lfs diff=lfs merge=lfs -text
-# Audio files - compressed
-*.aac filter=lfs diff=lfs merge=lfs -text
-*.flac filter=lfs diff=lfs merge=lfs -text
-*.mp3 filter=lfs diff=lfs merge=lfs -text
-*.ogg filter=lfs diff=lfs merge=lfs -text
-*.wav filter=lfs diff=lfs merge=lfs -text
-# Image files - uncompressed
-*.bmp filter=lfs diff=lfs merge=lfs -text
-*.gif filter=lfs diff=lfs merge=lfs -text
-*.png filter=lfs diff=lfs merge=lfs -text
-*.tiff filter=lfs diff=lfs merge=lfs -text
-# Image files - compressed
-*.jpg filter=lfs diff=lfs merge=lfs -text
-*.jpeg filter=lfs diff=lfs merge=lfs -text
-*.webp filter=lfs diff=lfs merge=lfs -text
-# Video files - compressed
-*.mp4 filter=lfs diff=lfs merge=lfs -text
-*.webm filter=lfs diff=lfs merge=lfs -text
+chahuadev-junk-sweeper1.png filter=lfs diff=lfs merge=lfs -text
+chahuadev-junk-sweeper.png filter=lfs diff=lfs merge=lfs -text
+icons/icon.png filter=lfs diff=lfs merge=lfs -text
+icons/logo.ico filter=lfs diff=lfs merge=lfs -text
+icons/logo.png filter=lfs diff=lfs merge=lfs -text
+icons/icon.ico filter=lfs diff=lfs merge=lfs -text
+icons/app-icon.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..01048de23ed8a6c51091589a710fe50dc860b4f4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,84 @@
+# Dependencies
+node_modules/
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+package-lock.json
+yarn.lock
+
+# Runtime
+*.log
+logs/
+pids/
+*.pid
+*.seed
+*.pid.lock
+
+# Coverage and testing
+coverage/
+.nyc_output/
+.jest/
+
+# Environment
+.env
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+# Editor files
+.vscode/
+.idea/
+*.swp
+*.swo
+*~
+
+# OS generated files
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+ehthumbs.db
+Thumbs.db
+
+# Backup directories (created by this tool)
+emoji-backup-*/
+backup-*/
+
+# Temporary test files
+test/temp/
+test/fixtures/temp/
+test
+
+# Distribution
+dist/
+build/
+
+# NPM
+.npm
+.npmrc
+
+# Ignore binary images
+icons/
+
+# Layout files (auto-generated per project)
+layouts/*.json
+
+# Python runtime — downloaded at build time, never committed
+# Run: npm run download-python-win (Windows only, ~12 MB)
+runtimes/
+
+# Python compiled cache
+__pycache__/
+*.pyc
+*.pyo
+
+# .NET build artifacts
+engines/cs_scanner/bin/
+engines/cs_scanner/obj/
+*.pyd
+logo.ico
+logo.png
+
+icon.png
diff --git a/.wslconfig b/.wslconfig
new file mode 100644
index 0000000000000000000000000000000000000000..dbfd65a4244c91a52aefd15ee46ce1f73f38d97d
--- /dev/null
+++ b/.wslconfig
@@ -0,0 +1,11 @@
+[interop]
+appendWindowsPath = true
+
+[automount]
+enabled = true
+root = /mnt
+options = "metadata,umask=0022,fmask=0011"
+mountFsTab = true
+
+[filesystem]
+umask = 0022
diff --git a/ApiTraceDebugger.js b/ApiTraceDebugger.js
new file mode 100644
index 0000000000000000000000000000000000000000..526f7766d66d9c9d97d93a247aa63e945239ac1e
--- /dev/null
+++ b/ApiTraceDebugger.js
@@ -0,0 +1,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();
\ No newline at end of file
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..395f44c763cc64a6c2c2916b2c9860c127ebbc68
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,54 @@
+# CHAHUADEV NON-COMMERCIAL & ACCEPTABLE USE LICENSE
+
+Copyright (c) 2026 Chahuadev. All rights reserved.
+
+This software and its source code are provided for educational, personal, and open-source community use. By downloading, accessing, or using this software, you agree to the following conditions:
+
+---
+
+## 1. FREE DISTRIBUTION ONLY (การแจกจ่ายต้องฟรีเท่านั้น)
+
+You are permitted to download, copy, modify, and distribute the software and its source code, provided that such distribution is **strictly free of charge**.
+
+---
+
+## 2. NO COMMERCIAL USE (ห้ามใช้หรือดัดแปลงเพื่อการค้า)
+
+You may **NOT** use, modify, distribute, or incorporate this software (or any of its parts) for any commercial purposes. This includes, but is not limited to:
+
+- Selling the software or derived versions.
+- Locking the software behind a paywall or subscription.
+- Using the software to provide commercial services.
+- Placing advertisements within the software.
+
+---
+
+## 3. ACCEPTABLE USE / NO MALICIOUS USE (ห้ามใช้ในทางที่ผิด)
+
+This software must not be used for any illegal, malicious, or harmful activities. You are strictly prohibited from using this codebase to:
+
+- Create malware, ransomware, or any destructive software.
+- Bypass security systems, steal data, or perform unauthorized access.
+- Violate any local, national, or international laws.
+
+If the software is found to be used in violation of these terms, your license to use it is immediately and permanently terminated without notice.
+
+---
+
+## 4. ATTRIBUTION (ต้องแสดงแหล่งที่มา)
+
+Any permitted distribution or modification must clearly credit the original author:
+
+> Original work by **Chahuadev** — https://chahuadev.com
+
+You may not remove, obscure, or alter any copyright notices or attribution present in the source code or documentation.
+
+---
+
+## 5. DISCLAIMER OF LIABILITY (ข้อสงวนสิทธิ์ความรับผิดชอบ)
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---
+
+For questions regarding licensing, contact: **Chahuadev** via https://chahuadev.com
diff --git a/README.md b/README.md
index 7be5fc7f47d5db027d120b8024982df93db95b74..be8abdefd7e9841641742b00ffd37afd8d3cd8fc 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,263 @@
----
-license: mit
----
+# Chahuadev Framework - Plugin Management System
+
+> Electron-based Desktop Application for Managing and Executing NPM Projects
+
+---
+
+## Documentation
+
+All documentation files have been organized in the `docs/` folder:
+
+### Core Documentation
+- **[docs/README.md](docs/README.md)** - Original project README
+- **[docs/IMPLEMENTATION_COMPLETE.txt](docs/IMPLEMENTATION_COMPLETE.txt)** - Project implementation status
+- **[docs/EMOJI_REMOVAL_COMPLETE.md](docs/EMOJI_REMOVAL_COMPLETE.md)** - Emoji removal system documentation
+
+### Authentication & Security
+- **[docs/OFFLINE_AUTH_GUIDE.md](docs/OFFLINE_AUTH_GUIDE.md)** - Offline authentication system guide
+- **[docs/OFFLINE_AUTH_CHANGES.md](docs/OFFLINE_AUTH_CHANGES.md)** - Offline authentication changes and implementation
+- **[docs/AUTH_SECURITY_GUIDE.md](docs/AUTH_SECURITY_GUIDE.md)** - Authentication security in ValidationGateway
+- **[docs/AUTH_SECURITY_IMPLEMENTATION.txt](docs/AUTH_SECURITY_IMPLEMENTATION.txt)** - Auth security implementation details
+- **[docs/SWITCH_TO_OAUTH_GUIDE.md](docs/SWITCH_TO_OAUTH_GUIDE.md)** - How to switch back to OAuth
+
+---
+
+## 🐧 Running the AppImage on Linux / WSL2 (Ubuntu)
+
+First install the required system libraries (one-time setup):
+
+```bash
+sudo apt-get update && sudo apt-get install -y \
+ libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 \
+ libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
+ libxrandr2 libgbm1 libasound2
+```
+
+Then run the AppImage:
+
+```bash
+chmod +x "Chahuadev-Framework.AppImage"
+DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 \
+ ./"Chahuadev-Framework.AppImage" \
+ --appimage-extract-and-run --no-sandbox --disable-gpu
+```
+
+> **WSL2 tip:** Copy the AppImage to the WSL native filesystem first for best performance:
+> ```bash
+> # Path after: npm install -g @chahuadev/framework
+> # (no sudo)
+> cp ~/.npm-global/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage
+> # (with sudo)
+> # cp /usr/lib/node_modules/@chahuadev/framework/bin/Chahuadev-Framework.AppImage /tmp/ChahuadevFramework.AppImage
+> chmod +x /tmp/ChahuadevFramework.AppImage
+> DISPLAY=:0 WAYLAND_DISPLAY=wayland-0 /tmp/ChahuadevFramework.AppImage \
+> --appimage-extract-and-run --no-sandbox --disable-gpu
+> ```
+
+---
+
+## Quick Start
+
+```bash
+# Install dependencies
+npm install
+
+# Start development server
+npm start
+
+# Start with dev mode
+npm run dev
+
+# Generate builds
+npm run build # All platforms
+npm run build-win # Windows only
+npm run build-msi # MSI installer
+npm run build-exe # Portable executable
+npm run build-nsis # NSIS installer
+```
+
+---
+
+## Key Features
+
+ **Offline Authentication** - No internet connection required
+ **SVG Icon System** - 40+ SVG icons for UI/logging
+ **Fort-Knox Security** - Anti-debugging, tamper detection, runtime integrity checks
+ **Gateway Pattern** - Centralized command processing and validation
+ **Multi-User Support** - Admin, Developer, User roles with permission levels
+ **Plugin Management** - Load and execute NPM projects as plugins
+
+---
+
+## Project Structure
+
+```
+chahuadev-framework/
+├── docs/ # Documentation (moved here)
+│ ├── README.md
+│ ├── IMPLEMENTATION_COMPLETE.txt
+│ ├── OFFLINE_AUTH_GUIDE.md
+│ ├── AUTH_SECURITY_GUIDE.md
+│ └── ...
+├── src/
+├── backend/ # Backend utilities
+├── modules/ # Core modules
+│ ├── svg-icons.js # SVG icon system (40+ icons)
+│ ├── tamper-detector.js
+│ └── ...
+├── scripts/ # Build and utility scripts
+├── main.js # Electron main process
+├── preload.js # Preload script for IPC
+├── index.html # Main UI
+├── validation_gateway.js # Command gateway with auth
+└── package.json
+```
+
+---
+
+## Authentication System
+
+### Demo Users (Offline Mode)
+```
+Username: admin | Password: demo123 | Role: Administrator | Permissions: read, write, admin
+Username: developer | Password: demo123 | Role: Developer | Permissions: read, write
+Username: user | Password: demo123 | Role: User | Permissions: read
+```
+
+### Token Storage
+- Location: `~/.chahuadev/auth.json`
+- Expiration: 24 hours
+
+### Permission Levels
+- `read` - View data, list plugins
+- `write` - Run commands, execute npm
+- `admin` - System configuration, auth checks
+
+---
+
+## Security Features
+
+### Fort-Knox Level Security
+- Anti-debugging protection
+- Tamper detection system
+- Runtime integrity checks
+- DevTools protection
+- Supply chain security verification
+
+### Authentication Security
+- Account lockout (5 attempts, 5-minute timeout)
+- Token expiration checking
+- Permission-based access control
+- Command-level authentication checks
+
+### Command Security
+- IPC command sanitization
+- Dangerous pattern detection
+- Whitelist-based execution
+- Plugin signature verification
+
+---
+
+## Logging System
+
+### Text-based Logging Tags
+Instead of emoji, the system now uses text-based tags:
+
+```
+[SUCCESS] - Operation successful
+[ERROR] - Error occurred
+[FAILED] - Operation failed
+[DENIED] - Access denied
+[LOCKED] - Account/resource locked
+[UNLOCKED] - Account/resource unlocked
+[EXPIRED] - Token expired
+[AUTH] - Authentication operation
+[PERMISSION] - Permission check
+[GATEWAY] - Gateway operation
+[ADMIN] - Administrator action
+[DEV] - Developer action
+[USER] - User action
+```
+
+---
+
+## SVG Icons System
+
+40+ SVG icons available in `modules/svg-icons.js`:
+
+### Security & Auth Icons
+- lock, unlock, shield, checkCircle, alertCircle, xCircle
+- userCheck, userX, user, users
+
+### System Icons
+- zap, settings, loader, refresh, eye, eyeOff
+- check, x, alertTriangle, info, bell, clock
+
+### Usage
+```javascript
+const SVGIcons = require('./modules/svg-icons.js');
+
+// Get SVG string
+const svg = SVGIcons.getSVG('lock', 'icon-small');
+
+// Create DOM element
+const elem = SVGIcons.createSVGElement('user', 'user-icon');
+```
+
+---
+
+## Development Commands
+
+```bash
+# Start development
+npm start # Normal start
+npm run dev # Development mode
+npm run dev-mode # Development mode with flags
+
+# Security
+npm run generate-checksums # Generate file checksums
+npm run security:check # Run security checks
+npm run security:audit # Audit dependencies
+npm run security:report # Generate security report
+
+# Building
+npm run build # Build all platforms
+npm run build-win # Windows build
+npm run build-msi # MSI installer
+npm run build-exe # Portable executable
+npm run build-nsis # NSIS installer
+
+# Testing
+npm test # Run tests
+npm run test:logo # Test logo system
+```
+
+---
+
+## For More Information
+
+- See **[docs/](docs/)** folder for detailed documentation
+- Check specific guides for authentication, security, and emoji removal
+- Review `AUTH_SECURITY_GUIDE.md` for authentication implementation details
+
+---
+
+## License
+
+Non-Commercial & Acceptable Use — See [LICENSE.md](LICENSE.md)
+
+---
+
+## Contributing
+
+For contributing guidelines, see the main documentation files in `docs/` folder
+
+---
+
+**Status**: Production Ready
+**Version**: 1.0.0
+**Last Updated**: February 17, 2026
+
+---
+
+*Chahuadev Framework - Making Project Management Simple & Secure*
diff --git a/app.html b/app.html
new file mode 100644
index 0000000000000000000000000000000000000000..94321f2868f014819c203744c8441c416cc66741
--- /dev/null
+++ b/app.html
@@ -0,0 +1,6596 @@
+
+
+
+
+
+ Chahua Plugin Management System
+
+
+
+
+
+
+
+ CHAHUADEV FRAMEWORK
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Plugin ต้องการอนุญาตการเข้าถึงข้อมูลต่อไปนี้:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/auth-dialog.js b/auth-dialog.js
new file mode 100644
index 0000000000000000000000000000000000000000..604175a5d079bb1b462f6b286346f714b44f28de
--- /dev/null
+++ b/auth-dialog.js
@@ -0,0 +1,171 @@
+/**
+ * Auth Dialog System - ระบบกล่องแจ้งเตือนล็อกอิน
+ * สำหรับแจ้งเตือนเมื่อผู้ใช้ยังไม่ได้ล็อกอิน
+ */
+
+class AuthDialog {
+ constructor() {
+ this.createStyles();
+ }
+
+ createStyles() {
+ const styles = `
+ .auth-dialog-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.8);
+ backdrop-filter: blur(5px);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 15000;
+ animation: auth-dialog-fade-in 0.3s ease-out;
+ }
+
+ .auth-dialog-box {
+ background: linear-gradient(135deg, #1a1a1a 0%, #0a0a0a 100%);
+ border: 2px solid #333;
+ border-radius: 12px;
+ padding: 30px;
+ max-width: 400px;
+ width: 90%;
+ box-shadow:
+ 0 20px 40px rgba(0, 0, 0, 0.5),
+ 0 0 0 1px rgba(255, 255, 255, 0.1),
+ inset 0 1px 0 rgba(255, 255, 255, 0.1);
+ animation: auth-dialog-slide-up 0.3s ease-out;
+ text-align: center;
+ }
+
+ .auth-dialog-header {
+ color: #e0e0e0;
+ font-size: 18px;
+ font-weight: 600;
+ margin-bottom: 8px;
+ padding-bottom: 15px;
+ border-bottom: 1px solid #333;
+ }
+
+ .auth-dialog-message {
+ color: #b0b0b0;
+ font-size: 16px;
+ line-height: 1.5;
+ margin-bottom: 25px;
+ margin-top: 15px;
+ }
+
+ .auth-dialog-button {
+ background: linear-gradient(135deg, #0ea5e9, #0284c7);
+ border: none;
+ color: white;
+ padding: 12px 24px;
+ border-radius: 8px;
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3);
+ min-width: 100px;
+ }
+
+ .auth-dialog-button:hover {
+ background: linear-gradient(135deg, #0284c7, #0369a1);
+ transform: translateY(-2px);
+ box-shadow: 0 6px 20px rgba(14, 165, 233, 0.4);
+ }
+
+ .auth-dialog-button:active {
+ transform: translateY(0);
+ }
+
+ @keyframes auth-dialog-fade-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+
+ @keyframes auth-dialog-slide-up {
+ from {
+ opacity: 0;
+ transform: translateY(30px) scale(0.9);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0) scale(1);
+ }
+ }
+ `;
+
+ // เพิ่ม CSS styles
+ if (!document.getElementById('auth-dialog-styles')) {
+ const styleElement = document.createElement('style');
+ styleElement.id = 'auth-dialog-styles';
+ styleElement.textContent = styles;
+ document.head.appendChild(styleElement);
+ }
+ }
+
+ show(options = {}) {
+ const {
+ title = 'ข้อความจาก chahuadev.com',
+ message = 'กรุณาล็อกอินก่อนใช้งาน',
+ buttonText = 'ตกลง'
+ } = options;
+
+ // ลบ dialog เก่าถ้ามี
+ this.hide();
+
+ // สร้าง dialog overlay
+ const overlay = document.createElement('div');
+ overlay.className = 'auth-dialog-overlay';
+ overlay.id = 'auth-dialog-overlay';
+
+ // สร้าง dialog box
+ const dialog = document.createElement('div');
+ dialog.className = 'auth-dialog-box';
+
+ dialog.innerHTML = `
+
+ ${message}
+
+ `;
+
+ overlay.appendChild(dialog);
+ document.body.appendChild(overlay);
+
+ // ปิด dialog เมื่อคลิกข้างนอก
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) {
+ this.hide();
+ }
+ });
+
+ // ปิด dialog ด้วย ESC key
+ const escapeHandler = (e) => {
+ if (e.key === 'Escape') {
+ this.hide();
+ document.removeEventListener('keydown', escapeHandler);
+ }
+ };
+ document.addEventListener('keydown', escapeHandler);
+ }
+
+ hide() {
+ const overlay = document.getElementById('auth-dialog-overlay');
+ if (overlay) {
+ overlay.style.animation = 'auth-dialog-fade-in 0.2s ease-out reverse';
+ setTimeout(() => {
+ overlay.remove();
+ }, 200);
+ }
+ }
+}
+
+// สร้าง instance ของ AuthDialog
+window.authDialog = new AuthDialog();
\ No newline at end of file
diff --git a/backend/utils/inspector-worker.js b/backend/utils/inspector-worker.js
new file mode 100644
index 0000000000000000000000000000000000000000..5ab104015779e5c3f62427e02d0bb42bdac663ff
--- /dev/null
+++ b/backend/utils/inspector-worker.js
@@ -0,0 +1,169 @@
+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...');
\ No newline at end of file
diff --git a/backend/utils/project-inspector-ipc.js b/backend/utils/project-inspector-ipc.js
new file mode 100644
index 0000000000000000000000000000000000000000..31777e0a48cdd2034f72486f5968fae2bac150c2
--- /dev/null
+++ b/backend/utils/project-inspector-ipc.js
@@ -0,0 +1,247 @@
+const { ipcMain, app } = require('electron');
+const { Worker } = require('worker_threads');
+const path = require('path');
+const fs = require('fs');
+// Note: projectInspector is now handled by Worker Thread
+
+// Track if handlers are already registered
+let handlersRegistered = false;
+
+/**
+ * IPC Handlers สำหรับ Project Inspector
+ * @param {Object} logger - Logger object
+ * @param {Object} debugManager - Debug manager instance
+ * @param {Object} cmdLogger - CMD logger for real-time display
+ */
+function setupProjectInspectorIPC(logger, debugManager, cmdLogger) {
+ // ป้องกันการลงทะเบียนซ้ำ
+ if (handlersRegistered) {
+ console.log(' Project Inspector IPC handlers already registered, skipping...');
+ return;
+ }
+
+ try {
+ // Project Inspector IPC Handlers (ใช้ Worker Threads เพื่อป้องกัน UI ค้าง)
+ ipcMain.handle('project:analyze', async (event, projectPath) => {
+ return new Promise((resolve, reject) => {
+ try {
+ let pathToScan;
+ let scanTarget;
+
+ // ถ้าไม่ได้ระบุ path มา, ให้สแกนโฟลเดอร์ plugins เป็น default
+ if (!projectPath) {
+ console.log('No path provided, defaulting to plugins directory.');
+ scanTarget = 'ปลั๊กอินทั้งหมด';
+
+ // หา Path ของโฟลเดอร์ plugins ที่ถูกต้อง
+ if (app.isPackaged) {
+ pathToScan = path.join(path.dirname(app.getPath('exe')), 'plugins');
+ } else {
+ pathToScan = path.join(app.getPath('userData'), 'plugins');
+ }
+ } else {
+ pathToScan = projectPath;
+ scanTarget = 'โปรเจกต์เฉพาะ';
+ }
+
+ console.log(`[IPC] Starting project analysis for ${scanTarget}: ${pathToScan}`);
+
+ // ตรวจสอบว่าโฟลเดอร์มีอยู่จริง
+ if (!fs.existsSync(pathToScan)) {
+ fs.mkdirSync(pathToScan, { recursive: true });
+ console.log(`Created missing directory: ${pathToScan}`);
+ }
+
+ logger.info('Starting project analysis with Worker Thread', { pathToScan, scanTarget });
+
+ // ส่งข้อความเริ่มต้นไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.info(`[Inspector] Starting project analysis...`);
+ cmdLogger.info(`[Inspector] Scan target: ${scanTarget}`);
+ cmdLogger.info(`[Inspector] Path to scan: ${pathToScan}`);
+ }
+
+ // สร้าง Worker Thread สำหรับการวิเคราะห์
+ const worker = new Worker(path.join(__dirname, 'inspector-worker.js'));
+
+ console.log(`[IPC] Created Worker Thread for analysis`);
+ if (cmdLogger) {
+ cmdLogger.debug(`[Inspector] Worker Thread created successfully`);
+ }
+
+ // รอรับผลลัพธ์และสถานะจาก Worker
+ worker.on('message', (result) => {
+ if (result.type === 'progress') {
+ // ส่ง progress update ไปให้ Frontend (ถ้าต้องการ)
+ const progressMessage = `Progress: ${result.message} (${result.progress}%)`;
+ console.log(`[IPC] ${progressMessage}`);
+ // ส่ง progress ไปยัง CMD แบบ real-time
+ if (cmdLogger) {
+ cmdLogger.info(`[Inspector] ${progressMessage}`);
+ }
+ // event.sender.send('project:analysis-progress', result);
+
+ } else if (result.type === 'status-update') {
+ // ส่งสถานะ real-time ไปให้ UI และ CMD ทันที
+ console.log(`[IPC] Status: ${result.data}`);
+
+ // ส่งไปยัง CMD แบบ real-time
+ if (cmdLogger) {
+ cmdLogger.info(`[Inspector] ${result.data}`);
+ }
+
+ try {
+ // ส่งสถานะไปยัง debug window หรือ main window
+ event.sender.send('inspector:status-update', result.data);
+
+ // ส่งสถานะไปยัง debug manager ถ้ามี (สำหรับ Real-time Terminal Display)
+ if (debugManager) {
+ // ตรวจสอบว่า debug window เปิดอยู่หรือไม่
+ if (debugManager.isDebugWindowOpen && debugManager.isDebugWindowOpen()) {
+ // ส่งข้อความไปยัง terminal ใน debug window
+ debugManager.sendTerminalMessage && debugManager.sendTerminalMessage(result.data, 'info');
+ console.log(`[IPC] Status sent to debug terminal: ${result.data}`);
+ } else {
+ console.log(`[IPC] Debug window is closed, skipping terminal message`);
+ }
+ } else {
+ console.log(`[IPC] Debug manager not available`);
+ }
+ } catch (error) {
+ console.warn('[IPC] Failed to send status update to renderer:', error.message);
+ }
+
+ } else if (result.type === 'analysis-result') {
+ // จัดการผลลัพธ์สุดท้าย
+ if (result.success) {
+ logger.info('Project analysis completed successfully', {
+ totalFiles: result.analysis.totalFiles,
+ totalIssues: result.analysis.totalIssues,
+ scanTarget: result.scanTarget,
+ duration: result.duration
+ });
+
+ const successMessage = `Worker completed successfully in ${result.duration}s - Files: ${result.analysis.totalFiles}, Issues: ${result.analysis.totalIssues}`;
+ console.log(`[IPC] ${successMessage}`);
+
+ // ส่งผลลัพธ์สุดท้ายไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.info(`[Inspector] ${successMessage}`);
+ cmdLogger.info(`[Inspector] Analysis completed for: ${result.scanTarget}`);
+ }
+
+ resolve({
+ success: true,
+ analysis: result.analysis,
+ scanTarget: result.scanTarget,
+ duration: result.duration
+ });
+ // Let worker terminate gracefully on its own
+
+ } else {
+ // จัดการ error case
+ logger.error('Project analysis failed in Worker', result.error);
+ const errorMessage = `Worker failed: ${result.error.message || result.error}`;
+ console.error(`[IPC] ${errorMessage}`);
+
+ // ส่ง error ไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.error(`[Inspector] ${errorMessage}`);
+ }
+
+ resolve({ success: false, error: result.error.message });
+ // Let worker terminate gracefully on its own
+ }
+ }
+ });
+
+ // รอรับ Error ที่ไม่คาดคิดจาก Worker
+ worker.on('error', (err) => {
+ logger.error('Worker encountered unrecoverable error', err);
+ const errorMessage = `Worker unrecoverable error: ${err.message}`;
+ console.error(`[IPC] ${errorMessage}`);
+
+ // ส่ง error ไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.error(`[Inspector] ${errorMessage}`);
+ }
+
+ resolve({ success: false, error: err.message });
+ worker.terminate();
+ });
+
+ // ตรวจสอบการปิด Worker
+ worker.on('exit', (code) => {
+ if (code !== 0) {
+ const exitMessage = `Worker stopped with exit code ${code}`;
+ console.error(`[IPC] ${exitMessage}`);
+
+ // ส่ง exit message ไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.warn(`[Inspector] ${exitMessage}`);
+ }
+ }
+ });
+
+ // สั่งให้ Worker เริ่มทำงานโดยส่ง data เข้าไป
+ worker.postMessage({
+ projectPath: pathToScan,
+ scanTarget
+ });
+
+ // ส่งข้อความที่เริ่มงานไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.info(`[Inspector] Sending analysis request to Worker Thread...`);
+ }
+
+ } catch (error) {
+ logger.error('Failed to create Worker for project analysis', error);
+ const errorMessage = `Failed to create Worker: ${error.message}`;
+
+ // ส่ง error ไปยัง CMD
+ if (cmdLogger) {
+ cmdLogger.error(`[Inspector] ${errorMessage}`);
+ }
+
+ resolve({ success: false, error: error.message });
+ }
+ });
+ });
+
+ ipcMain.handle('project:get-stats', async (event, analysis) => {
+ try {
+ // สำหรับ get-stats เราสามารถคำนวณใน Main Process ได้ เพราะไม่ใช่งานหนัก
+ const ProjectInspector = require('./project-inspector');
+ const tempInspector = new ProjectInspector();
+ const stats = tempInspector.getAnalysisStats(analysis);
+ return { success: true, stats };
+ } catch (error) {
+ logger.error('Failed to get project stats', error);
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle('project:set-rules', async (event, rules) => {
+ try {
+ // สำหรับ set-rules เราจัดเก็บใน memory หรือ file เพื่อให้ Worker ใช้ได้
+ // ตอนนี้จะ implement แบบง่ายๆ ก่อน
+ console.log('[IPC] Analysis rules updated:', rules);
+ // TODO: Implement rules storage for Worker Threads
+ return { success: true, message: 'Rules will be applied to next analysis' };
+ } catch (error) {
+ logger.error('Failed to set analysis rules', error);
+ return { success: false, error: error.message };
+ }
+ });
+
+ // ทำเครื่องหมายว่าลงทะเบียนแล้ว
+ handlersRegistered = true;
+ console.log(' Project Inspector IPC handlers registered');
+
+ } catch (error) {
+ console.error(' Failed to register Project Inspector IPC handlers:', error);
+ throw error;
+ }
+}
+
+module.exports = setupProjectInspectorIPC;
\ No newline at end of file
diff --git a/backend/utils/project-inspector.js b/backend/utils/project-inspector.js
new file mode 100644
index 0000000000000000000000000000000000000000..d7fe97d6b2ddc5596aa1987630930eeb55a364f2
--- /dev/null
+++ b/backend/utils/project-inspector.js
@@ -0,0 +1,1813 @@
+const fs = require('fs');
+const path = require('path');
+
+// ตรวจสอบและใช้ Dependencies ที่จำเป็นสำหรับการวิเคราะห์ขั้นสูง
+let acorn, cheerio;
+let dependencyWarning = null;
+try {
+ acorn = require('acorn');
+ cheerio = require('cheerio');
+ console.log(' Advanced analysis packages loaded successfully');
+} catch (error) {
+ console.warn(' Some analysis packages not found. Advanced checking will be disabled.');
+ dependencyWarning = 'Advanced analysis (HTML/JS/IPC) is disabled because required packages (acorn, cheerio) are missing.';
+ acorn = null;
+ cheerio = null;
+}
+
+/**
+ * Project Inspector V.2 - Full-Stack Application Integrity Analysis System
+ *
+ * ระบบวิเคราะห์ความสมบูรณ์ของแอปพลิเคชันแบบ Full-Stack
+ * ตรวจสอบ "ไวยากรณ์ของสถาปัตยกรรม" ตั้งแต่ Frontend ไปจนถึง Backend
+ *
+ * ความสามารถใหม่:
+ * 1. HTML-JS Link Analysis - ตรวจสอบการเชื่อมต่อระหว่าง HTML กับ JavaScript
+ * 2. IPC Communication Analysis - ตรวจสอบการสื่อสาร Renderer Main Process
+ * 3. Visual Regression Detection - ตรวจสอบ Layout และ UI Integrity
+ * 4. Architecture Grammar Validation - ตรวจสอบไวยากรณ์ของสถาปัตยกรรม
+ *
+ * พร้อมระบบคัดกรองไฟล์ของระบบแบบ Professional
+ *
+ * การปรับแต่งสำหรับการดีบัก:
+ * - index.html ได้รับการปลดล็อกจาก exclusion rules เพื่อให้สามารถตรวจเจอปัญหาได้
+ * - ระบบจะสแกนและวิเคราะห์ index.html อย่างละเอียดเหมือนไฟล์อื่นๆ
+ *
+ * การปรับปรุงครั้งใหญ่:
+ * - ปรับปรุงกฎการคัดกรองให้ฉลาดขึ้น (Smart Exclusion Rules)
+ * - เพิ่มการรองรับไฟล์สมัยใหม่ (Modern File Extensions)
+ * - ปรับปรุงการจัดการ Dependencies
+ */
+class ProjectInspector {
+ // แก้ไข constructor ให้รับ status callback
+ constructor(statusUpdateCallback = () => {}) {
+ this.statusUpdate = statusUpdateCallback;
+ this.fileContentCache = new Map();
+ this.dependencyWarning = dependencyWarning; // เก็บ warning message
+
+ // อัปเกรดกฎการวิเคราะห์ให้ครอบคลุม Full-Stack
+ this.analysisRules = {
+ // การวิเคราะห์พื้นฐาน
+ checkSyntax: acorn !== null,
+ checkMissingFiles: true,
+ checkUnusedFiles: false,
+ checkMissingDependencies: true,
+ checkCircularDependencies: true,
+ checkDuplicateExports: true,
+ checkImportExportMismatch: acorn !== null,
+
+ // การวิเคราะห์ขั้นสูง (ใหม่)
+ checkHtmlJsLinks: cheerio !== null && acorn !== null, // วิเคราะห์ HTML-JS connections
+ checkIpcIntegrity: acorn !== null, // วิเคราะห์ IPC communication
+ checkVisualRegression: true, // เตรียมพร้อมสำหรับ Visual Testing
+ checkArchitectureGrammar: true // วิเคราะห์ไวยากรณ์สถาปัตยกรรม
+ };
+
+ // ข้อมูลสำหรับการวิเคราะห์ขั้นสูง
+ this.htmlElements = new Map(); // เก็บ HTML elements และ IDs
+ this.jsHandlers = new Map(); // เก็บ JavaScript event handlers
+ this.ipcChannels = new Map(); // เก็บ IPC channels
+ this.cssClasses = new Set(); // เก็บ CSS classes
+
+ // [ปรับปรุงครั้งใหญ่] กฎการคัดกรองที่ฉลาดขึ้น - แก้ปัญหาการสแกนไม่ครอบคลุม
+ this.isExcluded = (filePath, projectRootPath) => {
+ // กฎข้อที่ 0: เด็ดขาดที่สุด - ห้ามทุกอย่างที่อยู่ใน node_modules
+ // กฎนี้จะทำงานก่อนเสมอและมีประสิทธิภาพสูงสุด
+ if (filePath.includes(path.sep + 'node_modules' + path.sep)) {
+ return true;
+ }
+
+ const relativePath = path.relative(projectRootPath, filePath);
+ const baseName = path.basename(filePath).toLowerCase();
+
+ // --- กฎข้อที่ 1: โฟลเดอร์ระดับรูทที่ต้องข้ามเสมอ (Root-level exclusions only) ---
+ // ตรวจสอบกับ relativePath เพื่อให้แน่ใจว่าเป็นโฟลเดอร์ที่อยู่ระดับบนสุดจริงๆ
+ const rootLevelExclusions = ['dist', 'build', '.git', 'test-results'];
+ if (rootLevelExclusions.some(dir => relativePath.startsWith(dir + path.sep) || relativePath === dir)) {
+ return true;
+ }
+
+ // --- กฎข้อที่ 2: โฟลเดอร์ระบบ Chahuadev Framework (เฉพาะของ Framework เท่านั้น) ---
+ const frameworkSystemDirs = new Set(['vendor', 'resources', 'bridge', 'logs', 'temp_extract']);
+ const pathParts = relativePath.split(path.sep);
+ if (pathParts.some(part => frameworkSystemDirs.has(part))) {
+ return true;
+ }
+
+ // --- กฎข้อที่ 3: ชื่อไฟล์ระบบที่ต้องข้ามเสมอ ---
+ const definitiveFileExclusions = new Set([
+ 'splash.html', 'loading.html', 'debugger.html',
+ 'main.js', 'preload.js', 'validation_gateway.js', 'debug-manager.js',
+ 'project-inspector.js', 'project-inspector-ipc.js',
+ 'generate-checksums.js', 'generate-keys.js', 'generate-manifests.js'
+ ]);
+ if (definitiveFileExclusions.has(baseName)) return true;
+
+ // --- กฎข้อที่ 4: รูปแบบชื่อไฟล์ที่ต้องข้าม ---
+ if (baseName.endsWith('.min.js') || baseName.endsWith('.bundle.js')) {
+ return true;
+ }
+
+ // --- กฎข้อที่ 5: ไฟล์ประเภทที่ไม่ควรสแกน (Binary files) ---
+ const binaryExtensions = ['.exe', '.dll', '.so', '.dylib', '.asar'];
+ if (binaryExtensions.some(ext => baseName.endsWith(ext))) {
+ return true;
+ }
+
+ // ถ้าไม่เข้าเงื่อนไขใดๆ เลย แสดงว่าไฟล์นี้ควรถูกสแกน
+ return false;
+ };
+
+ // Multi-Language Project Type Detection Rules
+ this.projectTypeRules = {
+ 'node': {
+ identifierFiles: ['package.json'],
+ extensions: ['.js', '.mjs', '.ts', '.jsx', '.json'],
+ checks: ['syntax', 'dependencies', 'imports']
+ },
+ 'python': {
+ identifierFiles: ['requirements.txt', 'setup.py', 'pyproject.toml'],
+ extensions: ['.py'],
+ checks: ['syntax', 'imports']
+ },
+ 'php': {
+ identifierFiles: ['composer.json', 'composer.lock'],
+ extensions: ['.php'],
+ checks: ['syntax', 'dependencies']
+ },
+ 'static_html': {
+ identifierFiles: ['index.html', 'main.html'],
+ extensions: ['.html', '.css', '.js', '.scss', '.less'],
+ checks: ['links', 'assets']
+ }
+ };
+ }
+
+
+
+ /**
+ * ฟังก์ชัน detectProjectType ที่ใช้ isExcluded เป็นด่านแรก
+ * @param {string} projectPath - เส้นทางของโปรเจกต์
+ * @returns {object} - { type: string, identifierFile: string | null }
+ */
+ detectProjectType(projectPath) {
+ console.log(` Detecting project type for: ${projectPath}`);
+
+ // ตรวจสอบไฟล์ identifier สำหรับแต่ละประเภท
+ for (const [type, rules] of Object.entries(this.projectTypeRules)) {
+ for (const identifierFile of rules.identifierFiles) {
+ const filePath = path.join(projectPath, identifierFile);
+
+ // ตรวจสอบก่อนว่าไฟล์ identifier ถูกสั่งให้ข้ามหรือไม่
+ if (this.isExcluded(filePath, projectPath)) {
+ console.log(` Skipping ${identifierFile} for ${type} detection (excluded by system rules)`);
+ continue;
+ }
+
+ if (fs.existsSync(filePath)) {
+ console.log(` Detected ${type} project (found ${identifierFile})`);
+ return { type, identifierFile };
+ }
+ }
+ }
+
+ // Fallback: ตรวจสอบจากนามสกุลไฟล์ที่มีอยู่
+ try {
+ const files = fs.readdirSync(projectPath);
+
+ // ตรวจหา .py files
+ if (files.some(file => file.endsWith('.py'))) {
+ console.log(' Detected python project (found .py files)');
+ return { type: 'python', identifierFile: null };
+ }
+
+ // ตรวจหา .php files
+ if (files.some(file => file.endsWith('.php'))) {
+ console.log(' Detected php project (found .php files)');
+ return { type: 'php', identifierFile: null };
+ }
+
+ // ตรวจหา HTML files (ต้องไม่ถูก exclude)
+ const htmlFiles = files.filter(file => {
+ const filePath = path.join(projectPath, file);
+ return file.endsWith('.html') && !this.isExcluded(filePath, projectPath);
+ });
+
+ if (htmlFiles.length > 0) {
+ console.log(' Detected static_html project (found .html files)');
+ return { type: 'static_html', identifierFile: null };
+ }
+
+ // ตรวจหา .js files (default Node.js)
+ if (files.some(file => file.endsWith('.js'))) {
+ console.log(' Detected node project (found .js files)');
+ return { type: 'node', identifierFile: null };
+ }
+
+ } catch (error) {
+ console.warn(` Error reading directory ${projectPath}:`, error.message);
+ }
+
+ console.log(' Unknown project type');
+ return { type: 'unknown', identifierFile: null };
+ }
+
+ /**
+ * อ่านเนื้อหาไฟล์พร้อม Cache (สำหรับ Metadata Flag Detection)
+ */
+ readFileContent(filePath) {
+ if (this.fileContentCache.has(filePath)) {
+ return this.fileContentCache.get(filePath);
+ }
+ const content = fs.readFileSync(filePath, 'utf-8');
+ this.fileContentCache.set(filePath, content);
+ return content;
+ }
+
+ /**
+ * อัปเดตฟังก์ชัน walkDirectory ให้ส่งสถานะ Real-time
+ */
+ walkDirectory(dir, projectPath, filelist = []) {
+ if (!projectPath) projectPath = dir; // กำหนด root path ครั้งแรก
+
+ // ส่งสถานะว่ากำลังจะสแกนโฟลเดอร์นี้
+ this.statusUpdate(` Scanning directory: ${path.relative(projectPath, dir) || '.'}`);
+
+ try {
+ const items = fs.readdirSync(dir, { withFileTypes: true });
+
+ for (const item of items) {
+ const fullPath = path.join(dir, item.name);
+
+ // ตรวจสอบกับกฎคัดกรองก่อนทำอะไรทั้งสิ้น!
+ if (this.isExcluded(fullPath, projectPath)) {
+ // ส่งสถานะว่ากำลังข้ามไฟล์/โฟลเดอร์นี้
+ this.statusUpdate(` Skipping: ${item.name}`);
+ continue; // ข้ามทันที - ไม่เข้าไปใน node_modules, .asar, หรือไฟล์ระบบ
+ }
+
+ if (item.isDirectory()) {
+ // ข้าม hidden folders เพิ่มเติม
+ if (!item.name.startsWith('.')) {
+ this.walkDirectory(fullPath, projectPath, filelist);
+ }
+ } else if (this.isPluginFile(item.name)) {
+ // ส่งสถานะว่าพบไฟล์ที่จะนำไปวิเคราะห์
+ this.statusUpdate(` Found file: ${item.name}`);
+ filelist.push(fullPath);
+ }
+ }
+ } catch (error) {
+ console.warn(`Cannot read directory ${dir}:`, error.message);
+ }
+ return filelist;
+ }
+
+ /**
+ * [ปรับปรุงครั้งใหญ่] ตรวจสอบไฟล์ปลั๊กอินด้วยการรองรับไฟล์สมัยใหม่
+ * เปลี่ยนจาก Whitelist เป็น Comprehensive Coverage
+ */
+ isPluginFile(filename) {
+ // รายการนามสกุลไฟล์ที่ครอบคลุมการพัฒนาสมัยใหม่
+ const pluginExtensions = [
+ // JavaScript & Frameworks
+ '.js', '.mjs', '.ts', '.jsx', '.tsx',
+ // Web Frontend
+ '.html', '.htm', '.css', '.scss', '.sass', '.less', '.vue',
+ // Backend Languages
+ '.py', '.php', '.rb', '.go', '.rs', '.java',
+ // Config & Data
+ '.json', '.yaml', '.yml', '.xml', '.toml', '.ini',
+ // Documentation & Text
+ '.txt', '.md', '.markdown', '.rst',
+ // Template Engines
+ '.ejs', '.pug', '.handlebars', '.hbs',
+ // Other useful formats
+ '.sql', '.graphql', '.env'
+ ];
+
+ const systemFiles = ['package.json', 'requirements.txt', 'composer.json', 'Cargo.toml', 'go.mod'];
+
+ // อนุญาตไฟล์การกำหนดค่าที่สำคัญ
+ if (systemFiles.includes(filename)) return true;
+
+ // อนุญาตไฟล์ที่มีนามสกุลที่เกี่ยวข้องกับปลั๊กอิน
+ return pluginExtensions.some(ext => filename.endsWith(ext));
+ }
+
+ /**
+ * ฟังก์ชันหลักในการเริ่มวิเคราะห์โปรเจกต์ (เวอร์ชันปรับปรุงขั้นสุดท้าย)
+ */
+ async analyzeProject(projectPath = process.cwd()) {
+ const analysis = {
+ timestamp: new Date().toISOString(),
+ projectPath,
+ totalFiles: 0,
+ totalIssues: 0,
+ issues: [],
+ dependencies: new Map(),
+ fileGraph: new Map(),
+ unusedFiles: [],
+ circularDeps: [],
+ stats: {
+ syntaxErrors: 0,
+ missingFiles: 0,
+ unusedFiles: 0,
+ missingDependencies: 0,
+ circularDependencies: 0,
+ duplicateExports: 0,
+ importExportMismatch: 0,
+ typeSpecificIssues: 0
+ }
+ };
+
+ try {
+ console.log(' Starting Project Inspector analysis...');
+
+ // ส่งสถานะเริ่มต้นการวิเคราะห์
+ this.statusUpdate(' Starting Project Inspector analysis...');
+
+ // Multi-Language Project Type Detection
+ this.statusUpdate(' Detecting project type...');
+ const detectionResult = this.detectProjectType(projectPath);
+ const projectType = detectionResult.type;
+ analysis.projectType = projectType;
+
+ this.statusUpdate(` Project type detected: ${projectType}`);
+
+ // --- การตรวจสอบ System File Exclusion ที่เด็ดขาดขึ้น ---
+ if (detectionResult.identifierFile) {
+ const identifierFilePath = path.join(projectPath, detectionResult.identifierFile);
+ if (this.isExcluded(identifierFilePath, projectPath)) {
+ console.log(` Skipping type-specific analysis for '${projectType}' because its identifier file '${detectionResult.identifierFile}' is excluded by System File Exclusion rules.`);
+ analysis.typeAnalysis = {
+ projectType,
+ typeSpecificIssues: [],
+ recommendations: ['ข้ามการวิเคราะห์เฉพาะประเภทเพราะไฟล์หลักอยู่ใน System File Exclusion rules']
+ };
+ } else {
+ // Type-specific Analysis (จะทำงานก็ต่อเมื่อไม่ถูกข้าม)
+ const typeAnalysis = this.analyzeByProjectType(projectPath, projectType);
+ analysis.typeAnalysis = typeAnalysis;
+
+ // เพิ่ม type-specific issues เข้าไปใน main issues
+ analysis.issues.push(...typeAnalysis.typeSpecificIssues);
+ analysis.totalIssues += typeAnalysis.typeSpecificIssues.length;
+ analysis.stats.typeSpecificIssues = typeAnalysis.typeSpecificIssues.length;
+
+ console.log(` Project type detected: ${projectType}`);
+ if (typeAnalysis.recommendations.length > 0) {
+ console.log(` Recommendations: ${typeAnalysis.recommendations.length} items`);
+ }
+ }
+ } else {
+ // กรณีไม่มี identifierFile ให้ทำ type analysis ปกติ
+ const typeAnalysis = this.analyzeByProjectType(projectPath, projectType);
+ analysis.typeAnalysis = typeAnalysis;
+
+ analysis.issues.push(...typeAnalysis.typeSpecificIssues);
+ analysis.totalIssues += typeAnalysis.typeSpecificIssues.length;
+ analysis.stats.typeSpecificIssues = typeAnalysis.typeSpecificIssues.length;
+
+ console.log(` Project type detected: ${projectType}`);
+ if (typeAnalysis.recommendations.length > 0) {
+ console.log(` Recommendations: ${typeAnalysis.recommendations.length} items`);
+ }
+ }
+
+ // 1. รวบรวมไฟล์ทั้งหมด (walkDirectory จะคัดกรองเบื้องต้นแล้ว)
+ this.statusUpdate(' Collecting files to analyze...');
+ const filesToAnalyze = this.walkDirectory(projectPath, projectPath);
+ const finalFileList = [];
+
+ // --- เพิ่มการคัดกรองชั้นที่สองโดยการอ่านเนื้อหาไฟล์ (Metadata Flag) ---
+ this.statusUpdate(' Performing secondary file filtering...');
+ for (const filePath of filesToAnalyze) {
+ try {
+ const content = this.readFileContent(filePath);
+ // ถ้าเจอ "ป้ายกำกับ" ของไฟล์ระบบ ให้ข้ามไป
+ if (content.includes('CHAHUADEV_SYSTEM_FILE')) {
+ console.log(` Skipping file with system flag: ${path.basename(filePath)}`);
+ continue;
+ }
+ finalFileList.push(filePath);
+ } catch (e) {
+ // ถ้าอ่านไฟล์ไม่ได้ ก็ข้ามไป
+ continue;
+ }
+ }
+
+ analysis.totalFiles = finalFileList.length;
+ this.statusUpdate(` Found ${analysis.totalFiles} files to analyze`);
+
+ // เพิ่มการแจ้งเตือนเกี่ยวกับ Dependencies ที่ขาดหายไป
+ if (this.dependencyWarning) {
+ analysis.issues.push({
+ type: 'ConfigurationWarning',
+ severity: 'warning',
+ file: 'Project Inspector',
+ message: this.dependencyWarning,
+ suggestion: 'Run "npm install acorn cheerio" in your project directory to enable advanced analysis features.',
+ line: 1,
+ column: 1
+ });
+ analysis.totalIssues += 1;
+ console.log(` ${this.dependencyWarning}`);
+ }
+
+ if (analysis.totalFiles === 0) {
+ console.log(' No plugin files found in project');
+ // สำหรับโปรเจกต์ที่ไม่ใช่ Node.js/JavaScript ให้ส่งผล type analysis กลับ
+ if (projectType !== 'node' && projectType !== 'unknown') {
+ console.log(` Analysis completed for ${projectType} project (no plugin files needed)`);
+ return analysis;
+ }
+ return analysis;
+ }
+
+ const allProjectFiles = new Set();
+ finalFileList.forEach(file => {
+ const relativePath = path.relative(projectPath, file);
+ allProjectFiles.add(relativePath);
+ });
+
+ // 2. วิเคราะห์แต่ละไฟล์
+ this.statusUpdate(' Starting file analysis...');
+ for (const filePath of finalFileList) {
+ try {
+ const code = fs.readFileSync(filePath, 'utf-8');
+ const relativePath = path.relative(projectPath, filePath);
+
+ // ส่งสถานะว่ากำลังวิเคราะห์ไฟล์นี้
+ this.statusUpdate(` Analyzing: ${relativePath}`);
+
+ // 2.1 ตรวจสอบ Syntax
+ if (this.analysisRules.checkSyntax && acorn) {
+ const syntaxIssues = this.checkSyntax(code, relativePath, projectPath);
+ analysis.issues.push(...syntaxIssues);
+ analysis.stats.syntaxErrors += syntaxIssues.length;
+ }
+
+ // 2.2 วิเคราะห์ Dependencies
+ if (this.analysisRules.checkMissingFiles) {
+ const depIssues = this.analyzeDependencies(code, filePath, projectPath, analysis);
+ analysis.issues.push(...depIssues);
+ analysis.stats.missingFiles += depIssues.length;
+ }
+
+ // 2.3 ตรวจสอบ Duplicate Exports
+ if (this.analysisRules.checkDuplicateExports && acorn) {
+ const exportIssues = this.checkDuplicateExports(code, relativePath, projectPath);
+ analysis.issues.push(...exportIssues);
+ analysis.stats.duplicateExports += exportIssues.length;
+ }
+
+ // 2.4 ตรวจสอบ Import/Export Mismatch
+ if (this.analysisRules.checkImportExportMismatch && acorn) {
+ const mismatchIssues = this.checkImportExportMismatch(code, filePath, projectPath);
+ analysis.issues.push(...mismatchIssues);
+ analysis.stats.importExportMismatch += mismatchIssues.length;
+ }
+
+ } catch (error) {
+ // ไม่สามารถวิเคราะห์ไฟล์นี้ได้
+ analysis.issues.push({
+ type: 'AnalysisError',
+ severity: 'warning',
+ file: path.relative(projectPath, filePath),
+ message: `ไม่สามารถวิเคราะห์ไฟล์ได้: ${error.message}`,
+ line: 1,
+ column: 1
+ });
+ }
+ }
+
+ // 3. หาไฟล์ที่ไม่ได้ใช้งาน
+ if (this.analysisRules.checkUnusedFiles) {
+ const unusedIssues = this.findUnusedFiles(analysis.dependencies, allProjectFiles, projectPath);
+ analysis.issues.push(...unusedIssues);
+ analysis.stats.unusedFiles += unusedIssues.length;
+ }
+
+ // 4. ตรวจสอบ Circular Dependencies
+ if (this.analysisRules.checkCircularDependencies) {
+ const circularIssues = this.findCircularDependencies(analysis.fileGraph, projectPath);
+ analysis.issues.push(...circularIssues);
+ analysis.stats.circularDependencies += circularIssues.length;
+ }
+
+ // 5. ตรวจสอบ Missing Dependencies ใน package.json
+ if (this.analysisRules.checkMissingDependencies) {
+ const missingDepIssues = this.checkMissingDependencies(analysis.dependencies, projectPath);
+ analysis.issues.push(...missingDepIssues);
+ analysis.stats.missingDependencies += missingDepIssues.length;
+ }
+
+ // ========== ADVANCED ANALYSIS (NEW) ==========
+
+ // 6. วิเคราะห์การเชื่อมต่อ HTML-JavaScript
+ if (this.analysisRules.checkHtmlJsLinks) {
+ const htmlFiles = finalFileList.filter(f => f.endsWith('.html'));
+ const jsFiles = finalFileList.filter(f => f.endsWith('.js') && !f.includes('.min.js'));
+
+ if (htmlFiles.length > 0 && jsFiles.length > 0) {
+ this.statusUpdate(' [Advanced] Running HTML-JavaScript link analysis...');
+ console.log(' [Advanced] Running HTML-JavaScript link analysis...');
+ const htmlJsIssues = this.analyzeHtmlJsLinks(htmlFiles, jsFiles, projectPath);
+ analysis.issues.push(...htmlJsIssues);
+ analysis.stats.htmlJsLinkIssues = htmlJsIssues.length;
+ }
+ }
+
+ // 7. วิเคราะห์การสื่อสาร IPC
+ if (this.analysisRules.checkIpcIntegrity) {
+ const rendererFiles = finalFileList.filter(f =>
+ (f.endsWith('.js') && !f.includes('main.js')) || f.includes('preload.js') || f.includes('renderer')
+ );
+ const mainFiles = finalFileList.filter(f =>
+ f.includes('main.js') || f.includes('debug-manager.js')
+ );
+
+ this.statusUpdate(' [Advanced] Running IPC communication analysis...');
+
+ if (rendererFiles.length > 0 && mainFiles.length > 0) {
+ console.log(' [Advanced] Running IPC communication analysis...');
+ const ipcIssues = this.analyzeIpcIntegrity(rendererFiles, mainFiles, projectPath);
+ analysis.issues.push(...ipcIssues);
+ analysis.stats.ipcIntegrityIssues = ipcIssues.length;
+ }
+ }
+
+ // 8. ตรวจสอบไวยากรณ์ของสถาปัตยกรรม
+ if (this.analysisRules.checkArchitectureGrammar) {
+ this.statusUpdate(' [Advanced] Running architecture grammar validation...');
+ console.log(' [Advanced] Running architecture grammar validation...');
+ const architectureIssues = this.validateArchitectureGrammar(projectPath, finalFileList);
+ analysis.issues.push(...architectureIssues);
+ analysis.stats.architectureGrammarIssues = architectureIssues.length;
+ }
+
+ analysis.totalIssues = analysis.issues.length;
+
+ // ล้าง cache หลังจากวิเคราะห์เสร็จ
+ this.fileContentCache.clear();
+
+ this.statusUpdate(` Analysis completed: ${analysis.totalIssues} issues found in ${analysis.totalFiles} files`);
+ console.log(` Project Inspector completed: ${analysis.totalIssues} issues found in ${analysis.totalFiles} files`);
+ return analysis;
+
+ } catch (error) {
+ console.error(' Project Inspector failed:', error);
+ throw error;
+ }
+ }
+
+ /**
+ * วิเคราะห์ปลั๊กอินตามประเภท
+ * @param {string} projectPath - เส้นทางของโปรเจกต์
+ * @param {string} projectType - ประเภทของโปรเจกต์
+ * @returns {Object} - ผลการวิเคราะห์เฉพาะประเภท
+ */
+ analyzeByProjectType(projectPath, projectType) {
+ const typeAnalysis = {
+ projectType,
+ typeSpecificIssues: [],
+ recommendations: []
+ };
+
+ try {
+ switch (projectType) {
+ case 'node':
+ return this.analyzeNodeProject(projectPath, typeAnalysis);
+ case 'python':
+ return this.analyzePythonProject(projectPath, typeAnalysis);
+ case 'php':
+ return this.analyzePhpProject(projectPath, typeAnalysis);
+ case 'static_html':
+ return this.analyzeHtmlProject(projectPath, typeAnalysis);
+ default:
+ typeAnalysis.recommendations.push('ไม่สามารถระบุประเภทโปรเจกต์ได้ - แนะนำให้เพิ่มไฟล์ manifest');
+ return typeAnalysis;
+ }
+ } catch (error) {
+ console.error(` Error analyzing ${projectType} project:`, error);
+ typeAnalysis.typeSpecificIssues.push({
+ type: 'analysis_error',
+ severity: 'high',
+ message: `ไม่สามารถวิเคราะห์โปรเจกต์ประเภท ${projectType} ได้: ${error.message}`
+ });
+ return typeAnalysis;
+ }
+ }
+
+ /**
+ * วิเคราะห์โปรเจกต์ Node.js
+ */
+ analyzeNodeProject(projectPath, typeAnalysis) {
+ const packageJsonPath = path.join(projectPath, 'package.json');
+
+ if (fs.existsSync(packageJsonPath)) {
+ try {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
+
+ // ตรวจสอบ main entry point
+ if (!packageJson.main && !packageJson.scripts?.start) {
+ typeAnalysis.typeSpecificIssues.push({
+ type: 'missing_entry_point',
+ severity: 'medium',
+ message: 'ไม่พบ main entry point หรือ start script ใน package.json'
+ });
+ typeAnalysis.recommendations.push('เพิ่ม "main": "index.js" หรือ "scripts": {"start": "node index.js"} ใน package.json');
+ }
+
+ // ตรวจสอบ dependencies
+ if (!packageJson.dependencies && !packageJson.devDependencies) {
+ typeAnalysis.recommendations.push('โปรเจกต์ไม่มี dependencies - ตรวจสอบว่าต้องการ package เพิ่มเติมหรือไม่');
+ }
+
+ } catch (error) {
+ typeAnalysis.typeSpecificIssues.push({
+ type: 'invalid_package_json',
+ severity: 'high',
+ message: 'ไฟล์ package.json ไม่ถูกต้อง: ' + error.message
+ });
+ }
+ }
+
+ return typeAnalysis;
+ }
+
+ /**
+ * วิเคราะห์โปรเจกต์ Python
+ */
+ analyzePythonProject(projectPath, typeAnalysis) {
+ const requirementsPath = path.join(projectPath, 'requirements.txt');
+
+ // ตรวจสอบ requirements.txt
+ if (fs.existsSync(requirementsPath)) {
+ try {
+ const requirements = fs.readFileSync(requirementsPath, 'utf8');
+ if (requirements.trim().length === 0) {
+ typeAnalysis.recommendations.push('ไฟล์ requirements.txt ว่างเปล่า - พิจารณาเพิ่ม dependencies ที่จำเป็น');
+ }
+ } catch (error) {
+ typeAnalysis.typeSpecificIssues.push({
+ type: 'invalid_requirements',
+ severity: 'medium',
+ message: 'ไม่สามารถอ่านไฟล์ requirements.txt ได้: ' + error.message
+ });
+ }
+ } else {
+ typeAnalysis.recommendations.push('แนะนำให้สร้างไฟล์ requirements.txt สำหรับจัดการ Python dependencies');
+ }
+
+ // ตรวจหาไฟล์ main
+ const mainFiles = ['main.py', 'app.py', '__main__.py'];
+ const hasMainFile = mainFiles.some(file => fs.existsSync(path.join(projectPath, file)));
+
+ if (!hasMainFile) {
+ typeAnalysis.recommendations.push('แนะนำให้มีไฟล์ main entry point เช่น main.py หรือ app.py');
+ }
+
+ return typeAnalysis;
+ }
+
+ /**
+ * วิเคราะห์โปรเจกต์ PHP
+ */
+ analyzePhpProject(projectPath, typeAnalysis) {
+ const composerJsonPath = path.join(projectPath, 'composer.json');
+
+ if (fs.existsSync(composerJsonPath)) {
+ try {
+ const composerJson = JSON.parse(fs.readFileSync(composerJsonPath, 'utf8'));
+
+ // ตรวจสอบ autoload
+ if (!composerJson.autoload) {
+ typeAnalysis.recommendations.push('แนะนำให้เพิ่ม autoload configuration ใน composer.json');
+ }
+
+ } catch (error) {
+ typeAnalysis.typeSpecificIssues.push({
+ type: 'invalid_composer_json',
+ severity: 'high',
+ message: 'ไฟล์ composer.json ไม่ถูกต้อง: ' + error.message
+ });
+ }
+ } else {
+ typeAnalysis.recommendations.push('แนะนำให้สร้างไฟล์ composer.json สำหรับจัดการ PHP dependencies');
+ }
+
+ // ตรวจหาไฟล์ main
+ const mainFiles = ['index.php', 'main.php', 'app.php'];
+ const hasMainFile = mainFiles.some(file => fs.existsSync(path.join(projectPath, file)));
+
+ if (!hasMainFile) {
+ typeAnalysis.recommendations.push('แนะนำให้มีไฟล์ entry point เช่น index.php');
+ }
+
+ return typeAnalysis;
+ }
+
+ /**
+ * วิเคราะห์โปรเจกต์ HTML
+ */
+ analyzeHtmlProject(projectPath, typeAnalysis) {
+ const indexHtmlPath = path.join(projectPath, 'index.html');
+
+ if (fs.existsSync(indexHtmlPath)) {
+ try {
+ const htmlContent = fs.readFileSync(indexHtmlPath, 'utf8');
+
+ // ตรวจสอบ external resources
+ const cssLinks = (htmlContent.match(/]*\.css/g) || []).length;
+ const jsScripts = (htmlContent.match(/
+
+
+