Datasets:
Download main.js from chahuadev/chahuadev-hub: direct link, hf CLI and curl.
- Browser
- Download file 47.2 kB
-
https://huggingface.co/datasets/chahuadev/chahuadev-hub/resolve/main/main.js
- Command line
-
hf download hf://datasets/chahuadev/chahuadev-hub/main.js
-
curl -L -o main.js https://huggingface.co/datasets/chahuadev/chahuadev-hub/resolve/main/main.js
47.2 kB
| /** | |
| * ╔══════════════════════════════════════════════════════════════════════╗ | |
| * ║ CHAHUADEV HUB — Electron Main Process ║ | |
| * ║ Official App Distribution Center (Desktop) ║ | |
| * ╚══════════════════════════════════════════════════════════════════════╝ | |
| * | |
| * @author Chahuadev | |
| * @license NON-COMMERCIAL & ACCEPTABLE USE ONLY. | |
| * Strictly prohibited for sale or malicious activities. | |
| * See LICENSE.md for full terms. | |
| */ | |
| ; | |
| const { app, BrowserWindow, ipcMain, shell, session, Menu } = require('electron'); | |
| const { autoUpdater } = require('electron-updater'); | |
| const path = require('path'); | |
| const fs = require('fs'); | |
| const os = require('os'); | |
| const https = require('https'); | |
| const http = require('http'); | |
| const { spawn, exec } = require('child_process'); | |
| const { URL } = require('url'); | |
| const SecurityCore = require('./security/security-core.js'); | |
| // Ignore dev flags in packaged builds so end users cannot force dev mode. | |
| if (app.isPackaged) { | |
| process.argv = process.argv.filter(arg => arg !== '--dev' && arg !== '--dev-mode'); | |
| } | |
| // ── Constants ──────────────────────────────────────────────────────────────── | |
| const HF_AUTHOR = 'chahuadev'; | |
| const HF_REPO = 'chahuadev/chahuadev-framework-binaries'; | |
| const HF_API_URL = `https://huggingface.co/api/datasets/${HF_REPO}/tree/main`; | |
| const HF_COMMITS_URL = `https://huggingface.co/api/datasets/${HF_REPO}/commits/main`; | |
| const R2_CDN_BASE = 'https://r2.chahuadev.com'; | |
| const R2_CATALOG_URL = 'https://r2.chahuadev.com/catalog.json'; | |
| const APP_CATALOG_ID = 'chahuadev-hub'; | |
| const GITHUB_CATALOG_URL = 'https://raw.githubusercontent.com/toyspata00/chahuadev-hub/main/catalog.json'; | |
| const HF_DATASETS_API = `https://huggingface.co/api/datasets?author=${HF_AUTHOR}&full=true`; | |
| const HF_MODELS_API = `https://huggingface.co/api/models?author=${HF_AUTHOR}&full=true`; | |
| const HF_SPACES_API = `https://huggingface.co/api/spaces?author=${HF_AUTHOR}&full=true`; | |
| const DOWNLOAD_DIR = path.join(os.homedir(), 'Downloads', 'ChahuadevHub'); | |
| const APP_BASE_DIR = app.isPackaged | |
| ? (process.env.PORTABLE_EXECUTABLE_DIR || path.dirname(process.execPath)) | |
| : __dirname; | |
| const HF_SANDBOX_DIR = path.join(APP_BASE_DIR, '.hf-sandbox-cache'); | |
| // ── npm Registry Constants ──────────────────────────────────────────────────── | |
| const NPM_ORG = 'chahuadev'; | |
| const NPM_ORG_PKG_URL = `https://registry.npmjs.org/-/org/${NPM_ORG}/package`; | |
| const NPM_REG_BASE = 'https://registry.npmjs.org'; | |
| const NPM_DL_BASE = 'https://api.npmjs.org/downloads/point/last-month'; | |
| // ── Cache System (ป้องกันคนรัวปุ่ม) ───────────────────────────────────────── | |
| let cachedChangelog = null; | |
| let lastChangelogFetch = 0; | |
| const CACHE_COOLDOWN = 5 * 60 * 1000; // 5 นาที | |
| const HF_TREE_STALE_MS = 5 * 60 * 1000; | |
| const HF_PREVIEW_MAX_BYTES = 256 * 1024; | |
| // npm cache | |
| let cachedNpmPackages = null; | |
| let lastNpmFetch = 0; | |
| // Hugging Face API cache (keyed by endpoint) with in-flight de-duplication | |
| const hfApiCache = new Map(); | |
| const hfPendingRequests = new Map(); | |
| const hfRepoTreeCache = new Map(); | |
| const hfRepoCommitHeadCache = new Map(); | |
| const hfRepoFileCacheMeta = new Map(); | |
| const SKIP_FILES = new Set([ | |
| '.gitattributes', 'README.md', | |
| 'chahuadev-framework-binaries.png', 'emoji-cleaner-app.png' | |
| ]); | |
| // Allowed npm packages for self-update / install (whitelist — renderer cannot override) | |
| const NPM_PKG_WHITELIST = new Set([ | |
| '@chahuadev/chahuadev-hub-app', | |
| '@chahuadev/dev-launcher', | |
| '@chahuadev/junk-sweeper-app', | |
| '@chahuadev/emoji-cleaner-app', | |
| '@chahuadev/framework' | |
| ]); | |
| const isDev = !app.isPackaged && process.argv.includes('--dev'); | |
| const UPDATE_CHANNEL = ((process.env.APP_UPDATE_CHANNEL || process.env.UPDATE_CHANNEL || 'stable').toLowerCase() === 'beta') ? 'beta' : 'stable'; | |
| const UPDATE_BASE_URL = 'https://r2.chahuadev.com'; | |
| let updaterInitialized = false; | |
| let updaterState = { | |
| lastCheckedAt: null, | |
| lastResult: 'idle', | |
| lastError: null | |
| }; | |
| const security = new SecurityCore(); | |
| function configureUpdaterFeed() { | |
| const feedUrl = `${UPDATE_BASE_URL}/`; | |
| autoUpdater.setFeedURL({ | |
| provider: 'generic', | |
| url: feedUrl | |
| }); | |
| autoUpdater.allowPrerelease = UPDATE_CHANNEL === 'beta'; | |
| autoUpdater.allowDowngrade = true; | |
| autoUpdater.channel = UPDATE_CHANNEL; | |
| console.log(`[Updater] Channel: ${UPDATE_CHANNEL} | Feed: ${feedUrl}`); | |
| } | |
| async function checkForUpdatesNow() { | |
| updaterState.lastCheckedAt = new Date().toISOString(); | |
| try { | |
| const result = await autoUpdater.checkForUpdates(); | |
| const version = result && result.updateInfo && result.updateInfo.version ? result.updateInfo.version : null; | |
| updaterState.lastResult = version ? 'update-available' : 'no-update'; | |
| updaterState.lastError = null; | |
| return { | |
| ok: true, | |
| channel: UPDATE_CHANNEL, | |
| updateAvailable: Boolean(version), | |
| version | |
| }; | |
| } catch (error) { | |
| updaterState.lastResult = 'error'; | |
| updaterState.lastError = error && error.message ? error.message : String(error); | |
| return { | |
| ok: false, | |
| channel: UPDATE_CHANNEL, | |
| error: updaterState.lastError | |
| }; | |
| } | |
| } | |
| function initAutoUpdater() { | |
| if (!app.isPackaged || isDev) return; | |
| configureUpdaterFeed(); | |
| autoUpdater.autoDownload = true; | |
| autoUpdater.autoInstallOnAppQuit = true; | |
| autoUpdater.logger = console; | |
| autoUpdater.on('error', (e) => { | |
| updaterState.lastResult = 'error'; | |
| updaterState.lastError = e && e.message ? e.message : String(e); | |
| console.warn('[Updater] Error:', updaterState.lastError); | |
| }); | |
| autoUpdater.on('update-available', () => { | |
| updaterState.lastResult = 'update-available'; | |
| updaterState.lastError = null; | |
| }); | |
| autoUpdater.on('update-not-available', () => { | |
| updaterState.lastResult = 'no-update'; | |
| updaterState.lastError = null; | |
| }); | |
| autoUpdater.on('update-downloaded', (info) => { | |
| updaterState.lastResult = 'downloaded'; | |
| const r = require('electron').dialog.showMessageBoxSync({ | |
| type: 'info', | |
| buttons: ['Restart now', 'Later'], | |
| defaultId: 0, | |
| cancelId: 1, | |
| title: 'Update ready', | |
| message: `Version ${info && info.version ? info.version : 'new'} is ready to install.` | |
| }); | |
| if (r === 0) autoUpdater.quitAndInstall(); | |
| }); | |
| setTimeout(() => autoUpdater.checkForUpdates().catch(() => {}), 12000); | |
| setInterval(() => autoUpdater.checkForUpdates().catch(() => {}), 6 * 60 * 60 * 1000); | |
| updaterInitialized = true; | |
| } | |
| function createDevMenuTemplate() { | |
| return [ | |
| { | |
| label: 'File', | |
| submenu: [ | |
| { role: 'close' }, | |
| { type: 'separator' }, | |
| { role: process.platform === 'darwin' ? 'hide' : 'quit' } | |
| ] | |
| }, | |
| { | |
| label: 'Edit', | |
| submenu: [ | |
| { role: 'undo' }, { role: 'redo' }, | |
| { type: 'separator' }, | |
| { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, | |
| { role: 'selectAll' } | |
| ] | |
| }, | |
| { | |
| label: 'View', | |
| submenu: [ | |
| { role: 'reload' }, | |
| { role: 'forceReload' }, | |
| { type: 'separator' }, | |
| { role: 'resetZoom' }, | |
| { role: 'zoomIn' }, | |
| { role: 'zoomOut' }, | |
| { type: 'separator' }, | |
| { role: 'togglefullscreen' } | |
| ] | |
| }, | |
| { | |
| label: 'Window', | |
| submenu: [ | |
| { role: 'minimize' }, | |
| { role: 'zoom' }, | |
| { role: 'close' } | |
| ] | |
| }, | |
| { | |
| label: 'Help', | |
| submenu: [ | |
| { | |
| label: 'Chahuadev Website', | |
| click: () => shell.openExternal('https://chahuadev.com/') | |
| } | |
| ] | |
| }, | |
| { | |
| label: 'Dev', | |
| submenu: [ | |
| { role: 'toggleDevTools' }, | |
| { role: 'reload' }, | |
| { role: 'forceReload' } | |
| ] | |
| } | |
| ]; | |
| } | |
| function applyProductionWindowHardening(win) { | |
| if (isDev || !win || win.isDestroyed()) return; | |
| win.webContents.on('before-input-event', (event, input) => { | |
| const key = (input.key || '').toLowerCase(); | |
| const blockedShortcut = | |
| key === 'f12' || | |
| ((input.control || input.meta) && input.shift && (key === 'i' || key === 'j' || key === 'c')); | |
| if (blockedShortcut) { | |
| event.preventDefault(); | |
| } | |
| }); | |
| win.webContents.on('devtools-opened', () => { | |
| if (!win.webContents.isDestroyed()) { | |
| win.webContents.closeDevTools(); | |
| } | |
| }); | |
| } | |
| // ── Security Init ──────────────────────────────────────────────────────────────────── | |
| function initSecurity() { | |
| security.applySecurityConfig(); // Layer 5b: enforce strict CSP from main process (survives HTML tampering) | |
| security.applyStrictCSP(session.defaultSession, isDev); if (!isDev) { | |
| const ok = security.validateChecksums(); | |
| if (!ok) { | |
| console.error('[Security] CRITICAL: Integrity check failed.'); | |
| // Don’t hard-exit on first run (checksums may not exist yet) | |
| } | |
| console.log('[Security] Production mode active.'); | |
| } else { | |
| console.log('[Security] Dev mode — security checks relaxed.'); | |
| } | |
| } | |
| // ── Windows ─────────────────────────────────────────────────────────────────── | |
| let mainWindow = null; | |
| let splashWindow = null; | |
| // ── HTTP Helper (follows redirects) ────────────────────────────────────────── | |
| function fetchJSON(urlStr, redirectCount = 0) { | |
| return new Promise((resolve, reject) => { | |
| if (redirectCount > 10) return reject(new Error('Too many redirects')); | |
| let parsed; | |
| try { parsed = new URL(urlStr); } catch (e) { return reject(e); } | |
| const mod = parsed.protocol === 'https:' ? https : http; | |
| const req = mod.get(urlStr, { | |
| headers: { 'User-Agent': 'ChahuadevHub/1.0.0 (Electron)' } | |
| }, (res) => { | |
| if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { | |
| res.resume(); | |
| const nextUrl = new URL(res.headers.location, urlStr).toString(); | |
| fetchJSON(nextUrl, redirectCount + 1).then(resolve).catch(reject); | |
| return; | |
| } | |
| if (res.statusCode !== 200) { | |
| res.resume(); | |
| return reject(new Error(`HTTP ${res.statusCode} — ${urlStr}`)); | |
| } | |
| let data = ''; | |
| res.on('data', chunk => { data += chunk; }); | |
| res.on('end', () => { | |
| try { resolve(JSON.parse(data)); } catch (e) { reject(e); } | |
| }); | |
| res.on('error', reject); | |
| }); | |
| req.on('error', reject); | |
| req.setTimeout(20000, () => { req.destroy(new Error('Request timeout')); }); | |
| }); | |
| } | |
| async function fetchWithCooldownCache(cacheKey, fetcher) { | |
| const now = Date.now(); | |
| const cached = hfApiCache.get(cacheKey); | |
| if (cached && (now - cached.ts < CACHE_COOLDOWN)) { | |
| return cached.data; | |
| } | |
| if (hfPendingRequests.has(cacheKey)) { | |
| return hfPendingRequests.get(cacheKey); | |
| } | |
| const pending = (async () => { | |
| const data = await fetcher(); | |
| hfApiCache.set(cacheKey, { ts: Date.now(), data }); | |
| return data; | |
| })(); | |
| hfPendingRequests.set(cacheKey, pending); | |
| try { | |
| return await pending; | |
| } finally { | |
| hfPendingRequests.delete(cacheKey); | |
| } | |
| } | |
| function normalizeRepoPath(input) { | |
| const raw = String(input || '').replace(/\\/g, '/').trim(); | |
| if (!raw) return ''; | |
| const cleaned = raw | |
| .split('/') | |
| .filter(Boolean) | |
| .filter(seg => seg !== '.' && seg !== '..') | |
| .join('/'); | |
| return cleaned; | |
| } | |
| function getRepoTypeSegment(repoType) { | |
| const t = String(repoType || '').toLowerCase(); | |
| if (t === 'dataset') return 'datasets'; | |
| if (t === 'space') return 'spaces'; | |
| return 'models'; | |
| } | |
| function buildRepoTreeApiUrl(repoId, repoType, repoPath = '', expand = false) { | |
| const typeSegment = getRepoTypeSegment(repoType); | |
| const normalizedPath = normalizeRepoPath(repoPath); | |
| const encodedPath = normalizedPath | |
| ? '/' + normalizedPath.split('/').map(encodeURIComponent).join('/') | |
| : ''; | |
| const suffix = expand ? '?expand=true' : ''; | |
| return `https://huggingface.co/api/${typeSegment}/${repoId}/tree/main${encodedPath}${suffix}`; | |
| } | |
| function buildRepoRawFileUrl(repoId, repoType, repoPath) { | |
| const normalizedPath = normalizeRepoPath(repoPath); | |
| const encodedPath = normalizedPath.split('/').map(encodeURIComponent).join('/'); | |
| const prefix = repoType === 'dataset' ? 'datasets/' : repoType === 'space' ? 'spaces/' : ''; | |
| return `https://huggingface.co/${prefix}${repoId}/resolve/main/${encodedPath}?download=true`; | |
| } | |
| function getRepoCacheRoot(repoId, repoType) { | |
| const safeRepo = String(repoId || '').replace(/[^a-zA-Z0-9._\/-]/g, '_'); | |
| const root = path.join(HF_SANDBOX_DIR, getRepoTypeSegment(repoType), safeRepo); | |
| fs.mkdirSync(root, { recursive: true }); | |
| return root; | |
| } | |
| function resolveSafeRepoLocalPath(repoId, repoType, repoPath) { | |
| const repoRoot = getRepoCacheRoot(repoId, repoType); | |
| const parts = normalizeRepoPath(repoPath).split('/').filter(Boolean); | |
| const target = path.resolve(repoRoot, ...parts); | |
| const safeRoot = path.resolve(repoRoot); | |
| if (!target.startsWith(safeRoot)) { | |
| throw new Error('Invalid file path'); | |
| } | |
| fs.mkdirSync(path.dirname(target), { recursive: true }); | |
| return target; | |
| } | |
| async function getLatestRepoCommitHead(repoId, repoType) { | |
| const key = `${repoType}:${repoId}`; | |
| const now = Date.now(); | |
| const cached = hfRepoCommitHeadCache.get(key); | |
| if (cached && (now - cached.checkedAt < HF_TREE_STALE_MS)) { | |
| return cached; | |
| } | |
| const url = `https://huggingface.co/api/${getRepoTypeSegment(repoType)}/${repoId}/commits/main`; | |
| const commits = await fetchJSON(url); | |
| const head = Array.isArray(commits) && commits[0] ? commits[0] : {}; | |
| const value = { | |
| id: String(head.id || head.sha || ''), | |
| date: String(head.date || head.createdAt || ''), | |
| checkedAt: now | |
| }; | |
| hfRepoCommitHeadCache.set(key, value); | |
| return value; | |
| } | |
| async function fetchRepoTreeSmart(repoId, repoType, options = {}) { | |
| const normalizedPath = normalizeRepoPath(options.path || ''); | |
| const expand = !!options.expand; | |
| const force = !!options.force; | |
| const cacheKey = `${repoType}:${repoId}:${normalizedPath}:${expand ? 'expand' : 'flat'}`; | |
| const now = Date.now(); | |
| const cached = hfRepoTreeCache.get(cacheKey); | |
| if (cached && !force && (now - cached.checkedAt < HF_TREE_STALE_MS)) { | |
| return cached.entries; | |
| } | |
| let head = null; | |
| try { | |
| head = await getLatestRepoCommitHead(repoId, repoType); | |
| } catch { | |
| // If commit endpoint fails but we have cached tree, serve cache. | |
| if (cached && !force) { | |
| cached.checkedAt = now; | |
| return cached.entries; | |
| } | |
| } | |
| if (cached && !force && head && head.id && cached.commitId && head.id === cached.commitId) { | |
| cached.checkedAt = now; | |
| return cached.entries; | |
| } | |
| const url = buildRepoTreeApiUrl(repoId, repoType, normalizedPath, expand); | |
| const entries = await fetchJSON(url); | |
| const normalizedEntries = Array.isArray(entries) ? entries : []; | |
| hfRepoTreeCache.set(cacheKey, { | |
| entries: normalizedEntries, | |
| checkedAt: now, | |
| commitId: head && head.id ? head.id : (cached && cached.commitId ? cached.commitId : ''), | |
| path: normalizedPath, | |
| expand | |
| }); | |
| return normalizedEntries; | |
| } | |
| function detectLanguageFromPath(filePath) { | |
| const ext = path.extname(String(filePath || '')).toLowerCase(); | |
| const map = { | |
| '.js': 'javascript', '.cjs': 'javascript', '.mjs': 'javascript', | |
| '.ts': 'typescript', '.tsx': 'typescript', '.jsx': 'javascript', | |
| '.json': 'json', '.md': 'markdown', '.txt': 'plaintext', | |
| '.html': 'html', '.css': 'css', '.scss': 'scss', | |
| '.py': 'python', '.java': 'java', '.go': 'go', | |
| '.yml': 'yaml', '.yaml': 'yaml', '.xml': 'xml', | |
| '.sh': 'shell', '.bat': 'bat', '.ps1': 'powershell', | |
| '.rs': 'rust', '.cpp': 'cpp', '.c': 'c' | |
| }; | |
| return map[ext] || 'plaintext'; | |
| } | |
| function isLikelyTextBuffer(buffer) { | |
| if (!buffer || buffer.length === 0) return true; | |
| const sample = buffer.subarray(0, Math.min(buffer.length, 4096)); | |
| for (let i = 0; i < sample.length; i++) { | |
| if (sample[i] === 0) return false; | |
| } | |
| return true; | |
| } | |
| async function cacheRepoFileLocally(repoId, repoType, repoPath) { | |
| const normalizedPath = normalizeRepoPath(repoPath); | |
| if (!normalizedPath) throw new Error('Missing repo file path'); | |
| const metaKey = `${repoType}:${repoId}:${normalizedPath}`; | |
| const head = await getLatestRepoCommitHead(repoId, repoType).catch(() => null); | |
| const localPath = resolveSafeRepoLocalPath(repoId, repoType, normalizedPath); | |
| const prevMeta = hfRepoFileCacheMeta.get(metaKey); | |
| if ( | |
| prevMeta && | |
| fs.existsSync(prevMeta.localPath) && | |
| head && | |
| head.id && | |
| prevMeta.commitId === head.id | |
| ) { | |
| return { localPath: prevMeta.localPath, commitId: prevMeta.commitId }; | |
| } | |
| const rawUrl = buildRepoRawFileUrl(repoId, repoType, normalizedPath); | |
| await downloadRaw(rawUrl, localPath); | |
| try { | |
| fs.chmodSync(localPath, 0o444); | |
| } catch { | |
| // Best effort only; some environments may not support chmod semantics. | |
| } | |
| const commitId = head && head.id ? head.id : (prevMeta && prevMeta.commitId ? prevMeta.commitId : ''); | |
| hfRepoFileCacheMeta.set(metaKey, { localPath, commitId, updatedAt: Date.now() }); | |
| return { localPath, commitId }; | |
| } | |
| function openFileInBestEditor(targetPath) { | |
| return new Promise((resolve) => { | |
| const safePath = String(targetPath || ''); | |
| if (!safePath) return resolve('not-found'); | |
| const quoted = safePath.replace(/"/g, '\\"'); | |
| exec(`code -g "${quoted}"`, { windowsHide: true }, (codeErr) => { | |
| if (!codeErr) return resolve('ok-vscode'); | |
| const npCandidates = [ | |
| process.env.NotepadPlusPlusPath || '', | |
| 'C:\\Program Files\\Notepad++\\notepad++.exe', | |
| 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe' | |
| ].filter(Boolean); | |
| const npPath = npCandidates.find(p => fs.existsSync(p)); | |
| if (npPath) { | |
| const child = spawn(npPath, [safePath], { detached: true, stdio: 'ignore', windowsHide: true }); | |
| child.unref(); | |
| return resolve('ok-notepadpp'); | |
| } | |
| shell.openPath(safePath).then(() => resolve('ok-default')).catch(() => resolve('error')); | |
| }); | |
| }); | |
| } | |
| // ── Semver comparison helper ────────────────────────────────────────────────── | |
| function semverGt(a, b) { | |
| const pa = String(a || '0').split('.').map(Number); | |
| const pb = String(b || '0').split('.').map(Number); | |
| for (let i = 0; i < 3; i++) { | |
| const na = pa[i] || 0, nb = pb[i] || 0; | |
| if (na > nb) return true; | |
| if (na < nb) return false; | |
| } | |
| return false; | |
| } | |
| function mapPlatformToCatalogOs(platform) { | |
| if (platform === 'win32') return 'Windows'; | |
| if (platform === 'linux') return 'Linux'; | |
| if (platform === 'darwin') return 'macOS'; | |
| return 'Unknown'; | |
| } | |
| function findCatalogEntry(catalog) { | |
| const files = catalog && Array.isArray(catalog.files) ? catalog.files : []; | |
| const platformOs = mapPlatformToCatalogOs(process.platform); | |
| const exact = files.find((f) => f && f.id === APP_CATALOG_ID && f.os === platformOs); | |
| if (exact) return exact; | |
| return files.find((f) => f && f.id === APP_CATALOG_ID) || null; | |
| } | |
| // ── Raw file downloader used by hot-patch ───────────────────────────────────── | |
| function downloadRaw(urlStr, destPath, redirectCount = 0) { | |
| return new Promise((resolve, reject) => { | |
| if (redirectCount > 10) return reject(new Error('Too many redirects')); | |
| let parsed; | |
| try { parsed = new URL(urlStr); } catch (e) { return reject(e); } | |
| const mod = parsed.protocol === 'https:' ? https : http; | |
| const req = mod.get(urlStr, { | |
| headers: { 'User-Agent': 'ChahuadevHub/1.0.0 (Electron)' } | |
| }, (res) => { | |
| if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { | |
| res.resume(); | |
| const nextUrl = new URL(res.headers.location, urlStr).toString(); | |
| downloadRaw(nextUrl, destPath, redirectCount + 1).then(resolve).catch(reject); | |
| return; | |
| } | |
| if (res.statusCode !== 200) { res.resume(); return reject(new Error(`HTTP ${res.statusCode}`)); } | |
| fs.mkdirSync(path.dirname(destPath), { recursive: true }); | |
| const ws = fs.createWriteStream(destPath); | |
| res.pipe(ws); | |
| ws.on('finish', () => ws.close(() => resolve(destPath))); | |
| ws.on('error', reject); | |
| }); | |
| req.on('error', reject); | |
| req.setTimeout(30000, () => req.destroy(new Error('Timeout'))); | |
| }); | |
| } | |
| // ── Splash Window ───────────────────────────────────────────────────────────── | |
| function createSplashWindow() { | |
| splashWindow = new BrowserWindow({ | |
| width: 520, | |
| height: 340, | |
| frame: false, | |
| resizable: false, | |
| alwaysOnTop: true, | |
| skipTaskbar: true, | |
| center: true, | |
| backgroundColor: '#09090f', | |
| webPreferences: { | |
| preload: path.join(__dirname, 'preload.js'), | |
| nodeIntegration: false, | |
| contextIsolation: true, | |
| sandbox: true | |
| } | |
| }); | |
| splashWindow.loadFile(path.join(__dirname, 'splash.html')); | |
| splashWindow.webContents.on('will-navigate', (e) => e.preventDefault()); | |
| } | |
| // ── Main Window ─────────────────────────────────────────────────────────────── | |
| function createMainWindow() { | |
| mainWindow = new BrowserWindow({ | |
| width: 1100, | |
| height: 740, | |
| minWidth: 900, | |
| minHeight: 580, | |
| show: false, | |
| backgroundColor: '#09090f', | |
| icon: path.join(__dirname, 'icons', 'icon.png'), | |
| autoHideMenuBar: !isDev, | |
| webPreferences: { | |
| preload: path.join(__dirname, 'preload.js'), | |
| nodeIntegration: false, | |
| contextIsolation: true, | |
| sandbox: true | |
| } | |
| }); | |
| mainWindow.loadFile(path.join(__dirname, 'index.html')); | |
| mainWindow.setMenuBarVisibility(isDev); | |
| // Block external navigation | |
| mainWindow.webContents.on('will-navigate', (e) => e.preventDefault()); | |
| mainWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); | |
| // Security: DevTools lockdown + navigation guard | |
| security.applyDevToolsLockdown(mainWindow, isDev); | |
| applyProductionWindowHardening(mainWindow); | |
| mainWindow.once('ready-to-show', () => { | |
| const delay = isDev ? 120 : 350; | |
| setTimeout(() => { | |
| if (splashWindow && !splashWindow.isDestroyed()) { | |
| splashWindow.close(); | |
| splashWindow = null; | |
| } | |
| if (mainWindow && !mainWindow.isDestroyed()) { | |
| mainWindow.show(); | |
| mainWindow.focus(); | |
| if (isDev) mainWindow.webContents.openDevTools(); | |
| } | |
| }, delay); | |
| }); | |
| mainWindow.on('closed', () => { mainWindow = null; }); | |
| } | |
| // ── App lifecycle ───────────────────────────────────────────────────────────── | |
| app.whenReady().then(() => { | |
| createSplashWindow(); | |
| initSecurity(); | |
| initAutoUpdater(); | |
| if (isDev) { | |
| Menu.setApplicationMenu(Menu.buildFromTemplate(createDevMenuTemplate())); | |
| } else { | |
| Menu.setApplicationMenu(null); | |
| } | |
| fs.mkdirSync(DOWNLOAD_DIR, { recursive: true }); | |
| createMainWindow(); | |
| app.on('activate', () => { | |
| if (BrowserWindow.getAllWindows().length === 0) createMainWindow(); | |
| }); | |
| }); | |
| app.on('window-all-closed', () => { | |
| if (process.platform !== 'darwin') app.quit(); | |
| }); | |
| // ════════════════════════════════════════════════════════════════════════════ | |
| // IPC Handlers | |
| // ════════════════════════════════════════════════════════════════════════════ | |
| // Return download directory path | |
| ipcMain.handle('get-download-dir', () => DOWNLOAD_DIR); | |
| // Expose isDev flag to renderer (for hiding dev-only features) | |
| ipcMain.handle('get-is-dev', () => isDev); | |
| // Fetch file list from catalog.json (GitHub primary, R2 + local fallback) | |
| ipcMain.handle('fetch-files', async () => { | |
| const parseFiles = (data) => { | |
| if (Array.isArray(data)) return data; | |
| if (data && Array.isArray(data.files)) return data.files; | |
| return []; | |
| }; | |
| const sources = [ | |
| GITHUB_CATALOG_URL, | |
| R2_CATALOG_URL, | |
| ]; | |
| for (const src of sources) { | |
| try { | |
| const data = await fetchWithCooldownCache(src, () => fetchJSON(src)); | |
| return { files: parseFiles(data) }; | |
| } catch (error) { | |
| console.warn('[catalog] Remote fetch failed:', src, error.message); | |
| } | |
| } | |
| try { | |
| const localPath = path.join(__dirname, 'catalog.json'); | |
| if (fs.existsSync(localPath)) { | |
| const raw = fs.readFileSync(localPath, 'utf8'); | |
| const data = JSON.parse(raw); | |
| return { files: parseFiles(data) }; | |
| } | |
| } catch (localErr) { | |
| console.error('[catalog] Local fallback failed:', localErr.message); | |
| } | |
| return { files: [] }; | |
| }); | |
| // Fetch commit changelog — with cache + cooldown to block API spam | |
| ipcMain.handle('fetch-changelog', async () => { | |
| const now = Date.now(); | |
| if (cachedChangelog && (now - lastChangelogFetch < CACHE_COOLDOWN)) { | |
| console.log('[Cache] Returning cached changelog'); | |
| return cachedChangelog; | |
| } | |
| try { | |
| const endpoints = [ | |
| [HF_DATASETS_API, 'dataset'], | |
| [HF_MODELS_API, 'model'], | |
| [HF_SPACES_API, 'space'] | |
| ]; | |
| let allRepos = []; | |
| for (const [url, rtype] of endpoints) { | |
| try { | |
| const data = await fetchJSON(url); | |
| for (const r of data) allRepos.push({ repoId: r.id || r.modelId, type: rtype }); | |
| } catch (_) { } | |
| } | |
| const commitPromises = allRepos.map(async ({ repoId, type }) => { | |
| const commitUrl = `https://huggingface.co/api/${type}s/${repoId}/commits/main`; | |
| try { | |
| const commits = await fetchJSON(commitUrl); | |
| return commits.map(c => { | |
| const shortRepo = repoId.split('/').pop(); | |
| c.title = `[${shortRepo}] ${c.title || c.message || '—'}`; | |
| return c; | |
| }); | |
| } catch (_) { return []; } | |
| }); | |
| const results = await Promise.all(commitPromises); | |
| let allCommits = []; | |
| results.forEach(repoCommits => { allCommits = allCommits.concat(repoCommits); }); | |
| allCommits.sort((a, b) => new Date(b.date) - new Date(a.date)); | |
| const finalData = allCommits.slice(0, 50); | |
| cachedChangelog = finalData; | |
| lastChangelogFetch = now; | |
| return finalData; | |
| } catch (err) { | |
| console.error('Changelog fetch error:', err); | |
| throw err; | |
| } | |
| }); | |
| // Fetch all repos (datasets + models + spaces) for Explorer panel | |
| ipcMain.handle('fetch-all-repos', async () => { | |
| const [datasetsRaw, modelsRaw, spacesRaw] = await Promise.all([ | |
| fetchWithCooldownCache(HF_DATASETS_API, () => fetchJSON(HF_DATASETS_API)).catch(() => []), | |
| fetchWithCooldownCache(HF_MODELS_API, () => fetchJSON(HF_MODELS_API)).catch(() => []), | |
| fetchWithCooldownCache(HF_SPACES_API, () => fetchJSON(HF_SPACES_API)).catch(() => []), | |
| ]); | |
| const sortByDate = arr => [...arr].sort((a, b) => { | |
| const da = a.lastModified || a.updatedAt || ''; | |
| const db = b.lastModified || b.updatedAt || ''; | |
| return db.localeCompare(da); | |
| }); | |
| return { | |
| datasets: sortByDate(Array.isArray(datasetsRaw) ? datasetsRaw : []), | |
| models: sortByDate(Array.isArray(modelsRaw) ? modelsRaw : []), | |
| spaces: sortByDate(Array.isArray(spacesRaw) ? spacesRaw : []), | |
| }; | |
| }); | |
| // Fetch commits for a specific repo | |
| ipcMain.handle('fetch-repo-commits', async (_, repoId, repoType) => { | |
| const url = `https://huggingface.co/api/${repoType}s/${repoId}/commits/main`; | |
| return await fetchWithCooldownCache(url, () => fetchJSON(url)); | |
| }); | |
| // Fetch file tree for a specific repo | |
| ipcMain.handle('fetch-repo-tree', async (_, repoId, repoType, options = {}) => { | |
| return fetchRepoTreeSmart(repoId, repoType, options); | |
| }); | |
| ipcMain.handle('fetch-repo-file', async (_, repoId, repoType, repoPath) => { | |
| try { | |
| const normalizedPath = normalizeRepoPath(repoPath); | |
| if (!normalizedPath) { | |
| return { ok: false, error: 'Missing file path' }; | |
| } | |
| const { localPath } = await cacheRepoFileLocally(repoId, repoType, normalizedPath); | |
| const stat = fs.statSync(localPath); | |
| const isTooLarge = stat.size > HF_PREVIEW_MAX_BYTES; | |
| const previewSize = Math.min(stat.size, HF_PREVIEW_MAX_BYTES); | |
| const buffer = Buffer.alloc(previewSize); | |
| const fd = fs.openSync(localPath, 'r'); | |
| try { | |
| fs.readSync(fd, buffer, 0, previewSize, 0); | |
| } finally { | |
| fs.closeSync(fd); | |
| } | |
| const isText = isLikelyTextBuffer(buffer); | |
| let content = ''; | |
| if (isText) { | |
| content = buffer.toString('utf8'); | |
| } | |
| return { | |
| ok: true, | |
| path: normalizedPath, | |
| localPath, | |
| isText, | |
| size: stat.size, | |
| truncated: isTooLarge, | |
| language: detectLanguageFromPath(normalizedPath), | |
| content | |
| }; | |
| } catch (error) { | |
| return { ok: false, error: error && error.message ? error.message : String(error) }; | |
| } | |
| }); | |
| ipcMain.handle('open-repo-file-editor', async (_, repoId, repoType, repoPath) => { | |
| try { | |
| const normalizedPath = normalizeRepoPath(repoPath); | |
| if (!normalizedPath) return { ok: false, error: 'Missing file path' }; | |
| const { localPath } = await cacheRepoFileLocally(repoId, repoType, normalizedPath); | |
| const result = await openFileInBestEditor(localPath); | |
| return { ok: result !== 'error', mode: result, localPath }; | |
| } catch (error) { | |
| return { ok: false, error: error && error.message ? error.message : String(error) }; | |
| } | |
| }); | |
| // Fetch dashboard stats: datasets + models + spaces counts, total downloads, recent activity | |
| ipcMain.handle('fetch-dashboard', async () => { | |
| const endpoints = [ | |
| [HF_DATASETS_API, 'dataset'], | |
| [HF_MODELS_API, 'model'], | |
| [HF_SPACES_API, 'space'] | |
| ]; | |
| const stats = { datasets: 0, models: 0, spaces: 0, totalDownloads: 0 }; | |
| const activity = []; | |
| for (const [url, rtype] of endpoints) { | |
| try { | |
| const data = await fetchWithCooldownCache(url, () => fetchJSON(url)); | |
| if (!Array.isArray(data)) continue; | |
| if (rtype === 'dataset') stats.datasets = data.length; | |
| if (rtype === 'model') stats.models = data.length; | |
| if (rtype === 'space') stats.spaces = data.length; | |
| for (const r of data) { | |
| const dl = r.downloads || r.downloadsAllTime || 0; | |
| stats.totalDownloads += Number(dl) || 0; | |
| const id = r.id || r.modelId || ''; | |
| const updated = r.lastModified || r.updatedAt || ''; | |
| if (id && updated) activity.push({ id, type: rtype, updated, private: !!r.private }); | |
| } | |
| } catch (_) { /* skip */ } | |
| } | |
| activity.sort((a, b) => b.updated.localeCompare(a.updated)); | |
| return { stats, activity: activity.slice(0, 20) }; | |
| }); | |
| // ── npm Packages ───────────────────────────────────────────────────────────── | |
| // Fetch all packages in the @chahuadev npm org with metadata + monthly downloads | |
| ipcMain.handle('fetch-npm-packages', async () => { | |
| const now = Date.now(); | |
| if (cachedNpmPackages && (now - lastNpmFetch < CACHE_COOLDOWN)) { | |
| return cachedNpmPackages; | |
| } | |
| try { | |
| // 1. Get list of packages in the org | |
| const pkgMap = await fetchJSON(NPM_ORG_PKG_URL); | |
| const names = Object.keys(pkgMap || {}); | |
| // 2. Fetch metadata + downloads for each package in parallel | |
| const results = await Promise.all( | |
| names.map(async (name) => { | |
| const [meta, dlData] = await Promise.all([ | |
| fetchJSON(`${NPM_REG_BASE}/${encodeURIComponent(name)}`).catch(() => null), | |
| fetchJSON(`${NPM_DL_BASE}/${encodeURIComponent(name)}`).catch(() => null), | |
| ]); | |
| const latest = meta?.['dist-tags']?.latest || ''; | |
| const verData = meta?.versions?.[latest] || {}; | |
| const timeMap = meta?.time || {}; | |
| const versionTimeRows = Object.entries(timeMap) | |
| .filter(([v]) => v !== 'created' && v !== 'modified') | |
| .sort((a, b) => String(b[1] || '').localeCompare(String(a[1] || ''))); | |
| const repositoryUrl = typeof verData.repository === 'string' | |
| ? verData.repository | |
| : (verData.repository && verData.repository.url ? verData.repository.url : ''); | |
| const readmeRaw = typeof meta?.readme === 'string' ? meta.readme : ''; | |
| const readmeExcerpt = readmeRaw.slice(0, 12000); | |
| return { | |
| name, | |
| version: latest, | |
| description: verData.description || meta?.description || '', | |
| keywords: verData.keywords || [], | |
| homepage: verData.homepage || `https://www.npmjs.com/package/${encodeURIComponent(name)}`, | |
| license: verData.license || '', | |
| updatedAt: meta?.time?.[latest] || '', | |
| downloads: dlData?.downloads || 0, | |
| versionsCount: Object.keys(meta?.versions || {}).length, | |
| recentVersions: versionTimeRows.slice(0, 12).map(([version, date]) => ({ version, date })), | |
| repositoryUrl, | |
| npmUrl: `https://www.npmjs.com/package/${encodeURIComponent(name)}`, | |
| readmeExcerpt, | |
| }; | |
| }) | |
| ); | |
| // Sort by downloads descending | |
| results.sort((a, b) => b.downloads - a.downloads); | |
| cachedNpmPackages = results; | |
| lastNpmFetch = now; | |
| return results; | |
| } catch (err) { | |
| console.error('[npm] fetch-npm-packages error:', err); | |
| throw err; | |
| } | |
| }); | |
| // Check if a downloaded file already exists on disk | |
| ipcMain.handle('check-file-exists', (_, filePath) => { | |
| const destPath = path.join(DOWNLOAD_DIR, filePath); | |
| return fs.existsSync(destPath); | |
| }); | |
| // ── Update detection: single downloads-meta.json inside app userData ───────── | |
| // Stored in %APPDATA%/Chahuadev-Hub/downloads-meta.json (never in user Downloads) | |
| // Schema: { "Junk-Sweeper.exe": { version, releaseDate }, ... } | |
| const DOWNLOADS_META_PATH = path.join(app.getPath('userData'), 'downloads-meta.json'); | |
| function readDownloadsMeta() { | |
| try { | |
| if (!fs.existsSync(DOWNLOADS_META_PATH)) return {}; | |
| return JSON.parse(fs.readFileSync(DOWNLOADS_META_PATH, 'utf8')); | |
| } catch { return {}; } | |
| } | |
| function writeDownloadsMeta(data) { | |
| fs.mkdirSync(path.dirname(DOWNLOADS_META_PATH), { recursive: true }); | |
| fs.writeFileSync(DOWNLOADS_META_PATH, JSON.stringify(data, null, 2), 'utf8'); | |
| } | |
| ipcMain.handle('save-file-meta', (_, filePath, meta) => { | |
| const all = readDownloadsMeta(); | |
| all[filePath] = meta; | |
| writeDownloadsMeta(all); | |
| return { success: true }; | |
| }); | |
| ipcMain.handle('get-file-meta', (_, filePath) => { | |
| const all = readDownloadsMeta(); | |
| return all[filePath] || null; | |
| }); | |
| // Open a locally downloaded file / launch it | |
| // Layer 6: verify hash from catalog before opening | |
| ipcMain.handle('open-file', async (_, filePath, expectedHash) => { | |
| const destPath = path.join(DOWNLOAD_DIR, filePath); | |
| if (!fs.existsSync(destPath)) return 'not-found'; | |
| if (expectedHash) { | |
| const { ok } = security.verifyDownloadedFile(destPath, expectedHash); | |
| if (!ok) return 'integrity-failed'; | |
| } | |
| return shell.openPath(destPath); | |
| }); | |
| // Open the folder containing a downloaded file in the system file explorer | |
| ipcMain.handle('open-file-folder', async (_, filePath) => { | |
| const destPath = path.join(DOWNLOAD_DIR, filePath); | |
| if (!fs.existsSync(destPath)) { | |
| // If file doesn't exist, open the parent download directory instead | |
| return shell.openPath(DOWNLOAD_DIR); | |
| } | |
| shell.showItemInFolder(destPath); | |
| return 'ok'; | |
| }); | |
| // Open downloads folder in system file explorer | |
| ipcMain.handle('open-downloads', async () => { | |
| fs.mkdirSync(DOWNLOAD_DIR, { recursive: true }); | |
| return shell.openPath(DOWNLOAD_DIR); | |
| }); | |
| // Open external URL — allow whitelisted hosts only | |
| const ALLOWED_EXTERNAL_HOSTS = new Set([ | |
| 'huggingface.co', | |
| 'github.com', | |
| 'raw.githubusercontent.com', | |
| 'www.tiktok.com', | |
| 'chahuadev.com', | |
| 'www.chahuadev.com', | |
| 'www.npmjs.com', | |
| 'r2.chahuadev.com', | |
| 'www.buymeacoffee.com', | |
| 'buymeacoffee.com', | |
| ]); | |
| ipcMain.handle('open-external-url', (_, url) => { | |
| if (typeof url !== 'string') return; | |
| try { | |
| const parsed = new URL(url); | |
| if (parsed.protocol !== 'https:') return; | |
| if (!ALLOWED_EXTERNAL_HOSTS.has(parsed.hostname)) return; | |
| shell.openExternal(parsed.toString()); | |
| } catch (_) { | |
| return; | |
| } | |
| }); | |
| // Download a file with streaming progress events | |
| ipcMain.handle('download-file', (event, filePath, fileSize) => { | |
| return new Promise((resolve, reject) => { | |
| // Build download URL — encode each path segment individually | |
| const encodedPath = filePath.split('/').map(encodeURIComponent).join('/'); | |
| const downloadUrl = `${R2_CDN_BASE}/${encodedPath}`; | |
| const destPath = path.join(DOWNLOAD_DIR, filePath); | |
| // Ensure destination directory exists | |
| fs.mkdirSync(path.dirname(destPath), { recursive: true }); | |
| function download(urlStr, redirectCount) { | |
| if (redirectCount > 15) return reject(new Error('Too many redirects')); | |
| let parsed; | |
| try { parsed = new URL(urlStr); } catch (e) { return reject(e); } | |
| const mod = parsed.protocol === 'https:' ? https : http; | |
| const req = mod.get(urlStr, { | |
| headers: { 'User-Agent': 'ChahuadevHub/1.0.0 (Electron)' } | |
| }, (res) => { | |
| // Follow redirect | |
| if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { | |
| res.resume(); | |
| const nextUrl = new URL(res.headers.location, urlStr).toString(); | |
| download(nextUrl, redirectCount + 1); | |
| return; | |
| } | |
| if (res.statusCode !== 200) { | |
| res.resume(); | |
| return reject(new Error(`HTTP ${res.statusCode}`)); | |
| } | |
| const total = parseInt(res.headers['content-length'] || fileSize || '0', 10); | |
| let downloaded = 0; | |
| const fileStream = fs.createWriteStream(destPath); | |
| res.on('data', (chunk) => { | |
| downloaded += chunk.length; | |
| fileStream.write(chunk); | |
| const pct = total > 0 ? downloaded / total : 0; | |
| if (!event.sender.isDestroyed()) { | |
| event.sender.send('download-progress', filePath, downloaded, total, pct); | |
| } | |
| }); | |
| res.on('end', () => { | |
| fileStream.end(() => { | |
| resolve({ success: true, dest: destPath, downloaded }); | |
| }); | |
| }); | |
| res.on('error', (err) => { | |
| fileStream.destroy(); | |
| fs.unlink(destPath, () => {}); | |
| reject(err); | |
| }); | |
| }); | |
| req.on('error', (err) => { | |
| fs.unlink(destPath, () => {}); | |
| reject(err); | |
| }); | |
| req.setTimeout(60000, () => { | |
| req.destroy(new Error('Download timeout')); | |
| }); | |
| } | |
| download(downloadUrl, 0); | |
| }); | |
| }); | |
| // ════════════════════════════════════════════════════════════════════════════ | |
| // App Self-Update (Approach 1 + 2) | |
| // ════════════════════════════════════════════════════════════════════════════ | |
| // Return current app version | |
| ipcMain.handle('get-app-version', () => app.getVersion()); | |
| ipcMain.handle('updater:get-channel', () => UPDATE_CHANNEL); | |
| ipcMain.handle('updater:get-status', () => ({ | |
| initialized: updaterInitialized, | |
| channel: UPDATE_CHANNEL, | |
| ...updaterState | |
| })); | |
| ipcMain.handle('updater:check-now', async () => { | |
| if (!app.isPackaged || isDev) { | |
| return { ok: false, channel: UPDATE_CHANNEL, error: 'Updater is disabled in development mode.' }; | |
| } | |
| if (!updaterInitialized) { | |
| return { ok: false, channel: UPDATE_CHANNEL, error: 'Updater is not initialized yet.' }; | |
| } | |
| return checkForUpdatesNow(); | |
| }); | |
| // Fetch catalog.json from R2, compare with running version | |
| ipcMain.handle('check-app-update', async () => { | |
| try { | |
| const catalog = await fetchJSON(R2_CATALOG_URL); | |
| const latestEntry = findCatalogEntry(catalog); | |
| if (!latestEntry || !latestEntry.version) { | |
| return { hasUpdate: false, error: `No catalog entry for ${APP_CATALOG_ID}` }; | |
| } | |
| const current = app.getVersion(); | |
| const latestVersion = String(latestEntry.version || ''); | |
| const hasUpdate = semverGt(latestVersion, current); | |
| return { | |
| hasUpdate, | |
| current, | |
| latest: latestVersion, | |
| releaseDate: String(latestEntry.releaseDate || ''), | |
| notes: String(latestEntry.notes || ''), | |
| path: String(latestEntry.path || ''), | |
| os: String(latestEntry.os || '') | |
| }; | |
| } catch (e) { | |
| return { hasUpdate: false, error: e.message }; | |
| } | |
| }); | |
| // ── npm self-update ─────────────────────────────────────────────────────────── | |
| // Runs: npm install -g @chahuadev/chahuadev-hub-app --foreground-scripts --force | |
| // Uses exec() so Node's built-in shell handles npm resolution on all platforms. | |
| // Security: command string is hardcoded — renderer passes no arguments. | |
| ipcMain.handle('npm-self-update', (event) => { | |
| return new Promise((resolve) => { | |
| const CMD = 'npm install -g @chahuadev/chahuadev-hub-app --foreground-scripts --force'; | |
| const send = (line) => { | |
| const trimmed = (line || '').toString().trim(); | |
| if (trimmed && !event.sender.isDestroyed()) | |
| event.sender.send('npm-update-log', trimmed); | |
| }; | |
| const child = exec(CMD, { windowsHide: true }); | |
| child.stdout.on('data', d => send(d)); | |
| child.stderr.on('data', d => send(d)); | |
| child.on('close', (code) => { | |
| resolve({ success: code === 0, code }); | |
| }); | |
| child.on('error', (err) => { | |
| send('ERROR: ' + err.message); | |
| resolve({ success: false, error: err.message }); | |
| }); | |
| }); | |
| }); | |
| // Relaunch app (kept for future use) | |
| ipcMain.handle('relaunch-app', () => { | |
| app.relaunch(); | |
| app.quit(); | |
| }); | |
| // Get npm global install path for a given package | |
| ipcMain.handle('npm-get-install-path', (_, pkgName) => { | |
| return new Promise((resolve) => { | |
| exec('npm root -g', { windowsHide: true }, (err, stdout) => { | |
| if (err) return resolve(null); | |
| const root = stdout.trim(); | |
| // Resolve scoped (@org/pkg) or unscoped (pkg) package path | |
| let pkgPath; | |
| if (pkgName && pkgName.startsWith('@')) { | |
| const parts = pkgName.slice(1).split('/'); | |
| pkgPath = path.join(root, '@' + parts[0], parts[1] || ''); | |
| } else if (pkgName) { | |
| pkgPath = path.join(root, pkgName); | |
| } else { | |
| pkgPath = path.join(root, '@chahuadev', 'chahuadev-hub-app'); | |
| } | |
| resolve(fs.existsSync(pkgPath) ? pkgPath : root); | |
| }); | |
| }); | |
| }); | |
| // Open the install folder for a given npm package (opens bin subdir if exists) | |
| ipcMain.handle('open-npm-folder', (_, pkgName) => { | |
| return new Promise((resolve) => { | |
| exec('npm root -g', { windowsHide: true }, (err, stdout) => { | |
| if (err) return resolve('error'); | |
| const root = stdout.trim(); | |
| let pkgPath; | |
| if (pkgName && pkgName.startsWith('@')) { | |
| const parts = pkgName.slice(1).split('/'); | |
| pkgPath = path.join(root, '@' + parts[0], parts[1] || ''); | |
| } else if (pkgName) { | |
| pkgPath = path.join(root, pkgName); | |
| } else { | |
| return resolve('not-found'); | |
| } | |
| if (!fs.existsSync(pkgPath)) return resolve('not-found'); | |
| const binPath = path.join(pkgPath, 'bin'); | |
| const openTarget = fs.existsSync(binPath) ? binPath : pkgPath; | |
| shell.openPath(openTarget); | |
| resolve('ok'); | |
| }); | |
| }); | |
| }); | |
| // Install any whitelisted npm package globally | |
| ipcMain.handle('npm-install-package', (event, pkgName) => { | |
| if (!NPM_PKG_WHITELIST.has(pkgName)) { | |
| return Promise.resolve({ success: false, error: 'Package not in whitelist' }); | |
| } | |
| return new Promise((resolve) => { | |
| const CMD = `npm install -g ${pkgName} --foreground-scripts --force`; | |
| const send = (line) => { | |
| const trimmed = (line || '').toString().trim(); | |
| if (trimmed && !event.sender.isDestroyed()) | |
| event.sender.send('npm-install-log', trimmed); | |
| }; | |
| const child = exec(CMD, { windowsHide: true }); | |
| child.stdout.on('data', d => send(d)); | |
| child.stderr.on('data', d => send(d)); | |
| child.on('close', (code) => resolve({ success: code === 0, code })); | |
| child.on('error', (err) => { | |
| send('ERROR: ' + err.message); | |
| resolve({ success: false, error: err.message }); | |
| }); | |
| }); | |
| }); | |