' + esc(uiText('emptyTitle')) + ' ' + esc(uiText('emptySources')) + '
' + esc(uiText('emptyTry')) + ' site:youtube.com author:name updated:90d';
}
function emptyNoResultHtml() {
return '' + esc(uiText('noResults')) + ' ' + esc(uiText('noResultsHelp')) + '';
}
var EMPTY_HOME = emptyHomeHtml();
var EMPTY_NORESULT = emptyNoResultHtml();
/* -- Utilities -- */
function esc(s) { if (!s) return ''; var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
function attr(s) { return esc(s).replace(/"/g, '"').replace(/'/g, '''); }
function safeUrl(url) {
if (!url || typeof url !== 'string') return '';
if (/^https?:\/\//i.test(url)) return url;
if (url.charAt(0) === '#' || url.charAt(0) === '/') return url;
return '';
}
function safeHref(url) { return attr(safeUrl(url)); }
function safeOpen(url) { var safe = safeUrl(url); if (safe) window.open(safe, '_blank', 'noopener'); }
function fmtNum(n) { if (n >= 1e6) return (n/1e6).toFixed(1)+'M'; if (n >= 1e3) return (n/1e3).toFixed(1)+'K'; return String(n); }
function timeAgo(d) { if (!d) return ''; var days = Math.floor((Date.now() - new Date(d)) / 864e5); if (days < 1) return 'today'; if (days === 1) return 'yesterday'; if (days < 30) return days+'d ago'; if (days < 365) return Math.floor(days/30)+'mo ago'; return Math.floor(days/365)+'y ago'; }
function showToast(msg, type, dur, undoFn, actionLabel) {
type = type || 'info'; dur = dur || 3000;
var c = document.getElementById('toastContainer'), t = document.createElement('div');
t.className = 'toast' + (type === 'error' ? ' error' : '');
t.textContent = msg;
if (undoFn) {
var btn = document.createElement('button');
btn.textContent = actionLabel || 'Undo'; btn.style.cssText = 'background:none;border:none;color:var(--accent);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;padding:0;text-decoration:underline;text-underline-offset:2px';
btn.addEventListener('click', function() { undoFn(); t.remove(); });
t.appendChild(btn);
}
c.appendChild(t); setTimeout(function() { t.classList.add('out'); setTimeout(function() { t.remove(); }, 300); }, dur);
}
/* ===== Event Bindings ===== */
var searchInput = document.getElementById('searchInput');
var clearBtn = document.getElementById('clearBtn');
var sortSelect = document.getElementById('sortSelect');
var siteFilter = document.getElementById('siteFilter');
var licenseFilter = document.getElementById('licenseFilter');
var minInstallsFilter = document.getElementById('minInstallsFilter');
var updatedFilter = document.getElementById('updatedFilter');
var languageFilter = document.getElementById('languageFilter');
var uiLocaleSelect = document.getElementById('uiLocale');
var grantFilterInput = document.getElementById('grantFilterInput');
var riskFilter = document.getElementById('riskFilter');
var historyEl = document.getElementById('searchHistory');
uiLocaleSelect.addEventListener('change', function() {
applyUiLocale(uiLocaleSelect.value, true);
EMPTY_HOME = emptyHomeHtml();
EMPTY_NORESULT = emptyNoResultHtml();
state.results.forEach(function(item) { if (item._meta) applyMetaUrls(item, item._meta); });
if (state.results.length) sortAndRender();
else grid.innerHTML = state.rawQuery ? EMPTY_NORESULT : EMPTY_HOME;
renderDiagnostics();
});
var debounceTimer = null;
searchInput.addEventListener('input', function() {
clearBtn.classList.toggle('visible', searchInput.value.length > 0);
historyEl.classList.remove('visible');
clearTimeout(debounceTimer);
debounceTimer = setTimeout(function() { var q = searchInput.value.trim(); if (q.length >= 2) executeSearch(q); }, 450);
});
searchInput.addEventListener('keydown', function(e) { if (e.key === 'Enter') { clearTimeout(debounceTimer); historyEl.classList.remove('visible'); var q = searchInput.value.trim(); if (q) executeSearch(q); } });
searchInput.addEventListener('focus', function() { if (!searchInput.value && _hGet().length) { renderHistory(); historyEl.classList.add('visible'); } });
document.addEventListener('click', function(e) { if (!e.target.closest('.search-wrap')) historyEl.classList.remove('visible'); });
clearBtn.addEventListener('click', function() {
searchInput.value = ''; clearBtn.classList.remove('visible'); siteFilter.value = '';
state.results = []; state.rawQuery = ''; state.query = ''; state.sourceCounts = {}; state.sourceErrors = {}; state.compareIds = []; state.showFavs = false; state.offlineCache = null;
updateCompareBar();
grid.innerHTML = EMPTY_HOME;
statsBar.style.display = 'none'; document.getElementById('sourceStatusBar').innerHTML = '';
document.title = 'ScriptHunt | Userscript search with trust context';
syncUrlState();
renderSourceToggles(); renderOfflineCachePanel(); searchInput.focus();
});
sortSelect.addEventListener('change', function() { state.sortBy = sortSelect.value; _prefSet('sort', state.sortBy); syncUrlState(); if (state.results.length) sortAndRender(); });
var filterDebounce = null;
document.getElementById('filterResults').addEventListener('input', function() {
clearTimeout(filterDebounce);
filterDebounce = setTimeout(function() { if (state.results.length) sortAndRender(); }, 200);
});
var siteDebounce = null;
siteFilter.addEventListener('input', function() { clearTimeout(siteDebounce); siteDebounce = setTimeout(function() { if (state.rawQuery) executeSearch(state.rawQuery); }, 600); });
var advancedFilterDebounce = null;
[licenseFilter, minInstallsFilter, grantFilterInput].forEach(function(ctrl) {
ctrl.addEventListener('input', function() {
clearTimeout(advancedFilterDebounce);
advancedFilterDebounce = setTimeout(function() { if (state.rawQuery) executeSearch(state.rawQuery); }, 450);
});
});
[updatedFilter, languageFilter, riskFilter].forEach(function(ctrl) {
ctrl.addEventListener('change', function() { if (state.rawQuery) executeSearch(state.rawQuery); });
});
// Comparison
document.getElementById('compareGo').addEventListener('click', openCompareModal);
document.getElementById('compareClear').addEventListener('click', function() { state.compareIds = []; updateCompareBar(); sortAndRender(); });
document.getElementById('modalOverlay').addEventListener('click', function(e) { if (e.target === this) closeCompareModal(); });
document.addEventListener('keydown', function(e) {
trapCompareFocus(e);
if (e.key === 'Escape') {
var modal = document.getElementById('modalOverlay');
if (modal.classList.contains('visible')) { closeCompareModal(); return; }
var hist = document.getElementById('searchHistory');
if (hist.classList.contains('visible')) { hist.classList.remove('visible'); return; }
}
if (e.target.closest('.result-card') && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
e.preventDefault();
var cards = Array.from(grid.querySelectorAll('.result-card'));
var idx = cards.indexOf(e.target.closest('.result-card'));
var next = e.key === 'ArrowDown' ? idx + 1 : idx - 1;
if (cards[next]) cards[next].focus();
}
if (e.target.closest('.result-card') && e.key === 'Enter' && !e.target.closest('a, button')) {
var c = e.target.closest('.result-card');
var title = c.querySelector('.card-title');
if (title && title.dataset.url) safeOpen(title.dataset.url);
}
});
// Bookmarklet
function bindPopoverFallback(btn, section, onOpen) {
if (_supportsNativePopover || !btn || !section) return;
btn.addEventListener('click', function(e) {
e.preventDefault();
var willOpen = !section.classList.contains('fallback-open');
document.querySelectorAll('.bookmarklet-section.fallback-open').forEach(function(openSection) {
if (openSection === section) return;
openSection.classList.remove('fallback-open');
var openBtn = document.querySelector('[popovertarget="' + openSection.id + '"]');
if (openBtn) openBtn.classList.remove('active');
});
section.classList.toggle('fallback-open', willOpen);
btn.classList.toggle('active', willOpen);
if (willOpen && typeof onOpen === 'function') onOpen();
});
}
var bmBase = location.origin !== 'null' ? location.origin + location.pathname.replace(/[^/]*$/, '') : 'https://sysadmindoc.github.io/UserScriptHunt/';
var bmCode = "javascript:void(window.open('" + bmBase + "?q=site:'+encodeURIComponent(location.hostname),'_blank'))";
document.getElementById('bookmarkletLink').href = bmCode;
var bmBtn = document.getElementById('btnBookmarklet');
var bmSection = document.getElementById('bookmarkletSection');
bindPopoverFallback(bmBtn, bmSection);
bmSection.addEventListener('toggle', function(e) {
bmBtn.classList.toggle('active', e.newState === 'open');
});
var savedBtn = document.getElementById('btnSavedSearches');
var savedSection = document.getElementById('savedSearchSection');
savedBtn.addEventListener('click', renderSavedSearches);
bindPopoverFallback(savedBtn, savedSection, renderSavedSearches);
savedSection.addEventListener('toggle', function(e) {
var open = e.newState === 'open';
savedBtn.classList.toggle('active', open);
if (open) renderSavedSearches();
});
document.getElementById('btnSaveCurrentSearch').addEventListener('click', saveCurrentSearch);
var diagBtn = document.getElementById('btnDiagnostics');
var diagSection = document.getElementById('diagnosticsSection');
diagBtn.addEventListener('click', renderGitHubSettings);
bindPopoverFallback(diagBtn, diagSection, function() { renderGitHubSettings(); refreshCacheDiagnostics(); });
diagSection.addEventListener('toggle', function(e) {
var open = e.newState === 'open';
diagBtn.classList.toggle('active', open);
if (open) { renderGitHubSettings(); refreshCacheDiagnostics(); }
});
var proxyInput = document.getElementById('customProxyInput');
var proxyStatus = document.getElementById('proxySettingsStatus');
var proxySaveBtn = document.getElementById('btnSaveProxy');
var proxyTestBtn = document.getElementById('btnTestProxy');
var proxyRemoveBtn = document.getElementById('btnRemoveProxy');
var publicProxyToggle = document.getElementById('allowPublicProxy');
if (proxyInput) proxyInput.value = _customProxy;
if (publicProxyToggle) publicProxyToggle.checked = _allowPublicProxy;
function setProxyStatus(msg, type) {
proxyStatus.textContent = msg;
proxyStatus.classList.toggle('ok', type === 'ok');
proxyStatus.classList.toggle('error', type === 'error');
}
proxySaveBtn.addEventListener('click', function() {
var raw = proxyInput.value.trim();
if (!raw) {
_customProxy = '';
_prefRemove('proxy');
setProxyStatus('Custom proxy removed. Public fallback proxies will be used.', 'ok');
renderDiagnostics();
return;
}
var norm = normalizeProxyUrl(raw);
if (!norm.ok) {
_prefRemove('proxy');
_customProxy = '';
setProxyStatus(norm.error, 'error');
renderDiagnostics();
return;
}
_customProxy = norm.url;
proxyInput.value = norm.url;
_prefSet('proxy', norm.url);
try { sessionStorage.setItem('sh_reopen_diagnostics', 'proxy-saved'); } catch(e) {}
location.reload();
});
proxyRemoveBtn.addEventListener('click', function() {
proxyInput.value = '';
_customProxy = '';
_prefRemove('proxy');
setProxyStatus(_allowPublicProxy ? 'Custom proxy removed. Public fallback proxies will be used.' : 'Custom proxy removed. Proxy-dependent sources are unavailable while public fallback is disabled.', _allowPublicProxy ? 'ok' : 'error');
renderDiagnostics();
});
publicProxyToggle.addEventListener('change', function() {
_allowPublicProxy = publicProxyToggle.checked;
_prefSet('allowPublicProxy', _allowPublicProxy);
var msg = _allowPublicProxy ? 'Public fallback enabled. Proxy services receive each target URL.' : (_customProxy ? 'Public fallback disabled. Only the configured custom proxy will be used.' : 'Public fallback disabled. Proxy-dependent sources will fail until a custom proxy is configured.');
setProxyStatus(msg, _allowPublicProxy || _customProxy ? 'ok' : 'error');
renderDiagnostics();
});
proxyTestBtn.addEventListener('click', async function() {
var norm = normalizeProxyUrl(proxyInput.value || _customProxy);
if (!norm.ok) { setProxyStatus(norm.error, 'error'); return; }
proxyTestBtn.disabled = true;
setProxyStatus('Testing custom proxy allowlist...', '');
try {
await selfTestCustomProxy(norm.url);
_customProxy = norm.url;
proxyInput.value = norm.url;
_prefSet('proxy', norm.url);
setProxyStatus('Proxy self-test passed: allowed userscript target returned content and unrelated target was blocked.', 'ok');
} catch(err) {
setProxyStatus('Proxy self-test failed: ' + ((err && err.message) || 'unknown error'), 'error');
} finally {
proxyTestBtn.disabled = false;
renderDiagnostics();
}
});
var githubTokenInput = document.getElementById('githubTokenInput');
var githubSaveBtn = document.getElementById('btnSaveGitHubToken');
var githubCheckBtn = document.getElementById('btnCheckGitHubRate');
var githubRemoveBtn = document.getElementById('btnRemoveGitHubToken');
githubSaveBtn.addEventListener('click', async function() {
var token = githubTokenInput.value.trim();
if (!token) { setGitHubStatus('Enter a GitHub token before saving.', 'error'); return; }
_ghToken = token;
saveGitHubToken(token);
githubTokenInput.value = '';
setGitHubStatus('GitHub token saved for this tab. Checking rate limit...', 'ok');
try { await refreshGitHubRate(); }
catch(err) { setGitHubStatus('GitHub token saved for this tab, but rate check failed: ' + ((err && err.message) || 'unknown error'), 'error'); }
renderDiagnostics();
});
githubCheckBtn.addEventListener('click', async function() {
githubCheckBtn.disabled = true;
try { await refreshGitHubRate(); }
catch(err) { setGitHubStatus('GitHub rate check failed: ' + ((err && err.message) || 'unknown error'), 'error'); }
finally { githubCheckBtn.disabled = false; renderDiagnostics(); }
});
githubRemoveBtn.addEventListener('click', function() {
_ghToken = '';
_ghRate = { limit: 0, remaining: 0, reset: 0, resource: 'search', authenticated: false, checkedAt: 0 };
clearGitHubToken();
_prefRemove('ghrate');
githubTokenInput.value = '';
setGitHubStatus('GitHub token removed. Unauthenticated search limits apply.', 'ok');
renderDiagnostics();
});
renderGitHubSettings();
renderCacheDiagnosticsSummary(_cacheDiagnostics);
var clearScanCacheBtn = document.getElementById('btnClearScanCache');
var clearOfflineCacheBtn = document.getElementById('btnClearOfflineCache');
clearScanCacheBtn.addEventListener('click', async function() {
clearScanCacheBtn.disabled = true;
setCacheStatus('Clearing scan cache...', '');
try {
await clearScanCache();
setCacheStatus('Scan cache cleared. Favorites, installed scripts, saved searches, and tokens were left untouched.', 'ok');
await refreshCacheDiagnostics();
} catch(err) {
setCacheStatus('Could not clear scan cache: ' + ((err && err.message) || 'unknown error'), 'error');
} finally {
clearScanCacheBtn.disabled = false;
}
});
clearOfflineCacheBtn.addEventListener('click', async function() {
clearOfflineCacheBtn.disabled = true;
setCacheStatus('Clearing offline search cache...', '');
try {
await clearOfflineCache();
setCacheStatus('Offline search cache cleared. Favorites, installed scripts, saved searches, and tokens were left untouched.', 'ok');
await refreshCacheDiagnostics();
} catch(err) {
setCacheStatus('Could not clear offline cache: ' + ((err && err.message) || 'unknown error'), 'error');
} finally {
clearOfflineCacheBtn.disabled = false;
}
});
document.getElementById('btnResetPrefs').addEventListener('click', function() {
resetPreferences();
_ghToken = '';
_ghRate = { limit: 0, remaining: 0, reset: 0, resource: 'search', authenticated: false, checkedAt: 0 };
setCacheStatus('Preferences reset. Favorites and installed lists preserved. Reload to apply.', 'ok');
renderDiagnostics();
});
function renderCustomSourceList() {
var el = document.getElementById('customSourceList');
if (!el) return;
var sources = _prefGet('customSources', []).map(migrateCustomSource);
if (!sources.length) { el.textContent = 'No custom sources configured.'; return; }
el.innerHTML = sources.map(function(src, index) {
var error = validateCustomSource(src);
var label = error ? 'Invalid custom source: ' + error : src.label + ' · manifest v' + src.schemaVersion + ' · ' + src.request.route;
return '
' + esc(label) + 'Remove';
}).join('');
el.querySelectorAll('[data-remove-source-index]').forEach(function(btn) {
btn.addEventListener('click', function() {
var current = _prefGet('customSources', []).map(migrateCustomSource);
var index = parseInt(btn.getAttribute('data-remove-source-index'), 10);
var removed = current[index];
var updated = current.filter(function(s, i) { return i !== index; });
_prefSet('customSources', updated);
if (removed && removed.id) delete SOURCES[removed.id];
renderCustomSourceList(); renderSourceToggles(); renderDiagnostics();
document.getElementById('customSourceStatus').textContent = 'Removed "' + (removed && (removed.label || removed.name) || 'invalid entry') + '".';
});
});
}
renderCustomSourceList();
document.getElementById('btnAddCustomSource').addEventListener('click', function() {
var nameInput = document.getElementById('customSourceName');
var urlInput = document.getElementById('customSourceUrl');
var manifestInput = document.getElementById('customSourceManifest');
var status = document.getElementById('customSourceStatus');
var src;
try {
src = manifestInput.value.trim() ? JSON.parse(manifestInput.value) : defaultCustomSourceManifest(nameInput.value.trim(), urlInput.value.trim());
} catch(e) {
status.textContent = 'Manifest JSON is invalid.';
return;
}
var err = validateCustomSource(src);
if (err) { status.textContent = err; return; }
var existing = _prefGet('customSources', []).map(migrateCustomSource);
if (existing.some(function(s) { return s.id === src.id || s.label.toLowerCase() === src.label.toLowerCase(); })) {
status.textContent = 'A custom source with that id or label already exists.'; return;
}
existing.push(src);
_prefSet('customSources', existing);
registerCustomSource(src);
nameInput.value = ''; urlInput.value = ''; manifestInput.value = '';
renderCustomSourceList(); renderSourceToggles(); renderDiagnostics();
status.textContent = 'Added "' + src.label + '" from manifest v' + src.schemaVersion + '. Toggle it in the source bar to use it.';
});
document.getElementById('btnCopyDiagnostics').addEventListener('click', function() {
renderDiagnostics();
var out = document.getElementById('diagnosticsOutput');
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(out.value).then(function() { showToast('Diagnostics copied', 'info', 2000); }).catch(function() { out.select(); showToast('Select and copy diagnostics manually', 'error', 3000); });
} else {
out.select(); showToast('Select and copy diagnostics manually', 'info', 3000);
}
});
// Favorites button
var btnExport = document.getElementById('btnExportFavs'), btnImport = document.getElementById('btnImportFavs'), btnImportInstalled = document.getElementById('btnImportInstalled'), btnExportInstalled = document.getElementById('btnExportInstalled');
document.getElementById('btnFavorites').addEventListener('click', function() {
this.classList.toggle('active');
var active = this.classList.contains('active');
btnExport.style.display = active ? '' : 'none'; btnImport.style.display = active ? '' : 'none';
if (active) { showFavorites(); } else { if (state.rawQuery) { state.showFavs = false; sortAndRender(); } else { clearBtn.click(); } }
});
function downloadJson(payload, filename) {
var blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
var a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = filename; a.click();
URL.revokeObjectURL(a.href);
}
// Export favorites
btnExport.addEventListener('click', function() {
var favs = getFavs(); if (!favs.length) { showToast('No favorites to export', 'error', 2000); return; }
downloadJson(buildFavoritesExport(), 'scripthunt-favorites.json'); showToast('Exported ' + favs.length + ' favorites', 'info', 2000);
});
btnExportInstalled.addEventListener('click', function() {
var installed = getInstalledScripts(); if (!installed.length) { showToast('No installed scripts to export', 'error', 2000); return; }
downloadJson(buildInstalledExport(), 'scripthunt-installed.json'); showToast('Exported ' + installed.length + ' installed scripts', 'info', 2000);
});
// Import favorites
var importInput = document.getElementById('importFavsFile');
var importMode = 'favorites';
btnImport.addEventListener('click', function() { importMode = 'favorites'; importInput.click(); });
btnImportInstalled.addEventListener('click', function() { importMode = 'installed'; importInput.click(); });
importInput.addEventListener('change', function() {
var file = this.files[0]; if (!file) return;
var reader = new FileReader();
reader.onload = function(e) {
try {
var parsed = parseScriptImportPayload(JSON.parse(e.target.result), importMode);
openImportPreview(buildImportPreview(parsed));
} catch(err) { showToast('Invalid import file', 'error', 3000); }
};
reader.readAsText(file); this.value = '';
});
/* ===== Theme Toggle ===== */
var THEMES = ['auto', 'dark', 'light', 'oled'];
var THEME_LABELS = { auto: 'Auto', dark: 'Dark', light: 'Light', oled: 'OLED' };
var themeToggleBtn = document.getElementById('themeToggle');
function applyTheme(theme) {
var html = document.documentElement;
html.classList.remove('theme-light', 'theme-oled', 'theme-auto');
if (theme === 'light') html.classList.add('theme-light');
else if (theme === 'oled') html.classList.add('theme-oled');
else if (theme === 'auto') {
html.classList.add('theme-auto');
if (window.matchMedia('(prefers-color-scheme: light)').matches) html.classList.add('theme-light');
}
themeToggleBtn.textContent = THEME_LABELS[theme] || 'Auto';
_prefSet('theme', theme);
}
themeToggleBtn.addEventListener('click', function() {
var current = _prefGet('theme', 'auto');
var next = THEMES[(THEMES.indexOf(current) + 1) % THEMES.length];
applyTheme(next);
});
window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', function() {
if (_prefGet('theme', 'auto') === 'auto') applyTheme('auto');
});
applyTheme(_prefGet('theme', 'auto'));
function syncUrlState() {
var params = new URLSearchParams();
var q = searchInput.value.trim();
var site = siteFilter.value.trim();
var sources = Object.keys(SOURCES).filter(function(id) { return SOURCES[id].enabled; });
if (q) params.set('q', q);
if (sources.length) params.set('sources', sources.join(','));
if (site) params.set('site', site);
if (sortSelect.value && sortSelect.value !== 'relevance') params.set('sort', sortSelect.value);
if (licenseFilter.value.trim()) params.set('license', licenseFilter.value.trim());
if (minInstallsFilter.value.trim()) params.set('min_installs', minInstallsFilter.value.trim());
if (updatedFilter.value !== '0') params.set('updated', updatedFilter.value);
if (languageFilter.value && languageFilter.value !== 'en') params.set('lang', languageFilter.value);
if (grantFilterInput.value.trim()) params.set('grant', grantFilterInput.value.trim());
if (riskFilter.value) params.set('risk', riskFilter.value);
var next = location.pathname + (params.toString() ? '?' + params.toString() : '') + location.hash;
history.replaceState(null, '', next);
}
function hasOption(select, value) {
return Array.from(select.options).some(function(opt) { return opt.value === value; });
}
function restoreUrlState(params) {
var sourceParam = params.get('sources');
if (sourceParam) {
var enabled = new Set(sourceParam.split(',').map(function(s) { return s.trim(); }).filter(Boolean));
Object.keys(SOURCES).forEach(function(id) { SOURCES[id].enabled = enabled.has(id); });
}
var site = params.get('site');
if (site) siteFilter.value = site;
var sort = params.get('sort');
if (sort && hasOption(sortSelect, sort)) { sortSelect.value = sort; state.sortBy = sort; }
if (params.get('license')) licenseFilter.value = params.get('license');
if (params.get('min_installs')) minInstallsFilter.value = params.get('min_installs');
if (params.get('updated') && hasOption(updatedFilter, params.get('updated'))) updatedFilter.value = params.get('updated');
if (params.get('lang') && hasOption(languageFilter, params.get('lang'))) languageFilter.value = params.get('lang');
if (params.get('grant')) grantFilterInput.value = params.get('grant');
if (params.get('risk') && hasOption(riskFilter, params.get('risk'))) riskFilter.value = params.get('risk');
return params.get('q') || '';
}
function renderCacheDiagnosticsSummary(summary) {
var el = document.getElementById('cacheDiagnosticsSummary');
if (!el) return;
if (!summary) {
el.innerHTML = 'Cache statusChecking...
Inspecting IndexedDB, localStorage, and browser quota.';
return;
}
var idb = summary.indexedDB || {};
var ls = summary.localStorage || {};
var storage = summary.storage || {};
var limits = summary.limits || { offlineSearches: OFFLINE_LIMIT, scanCache: SCAN_CACHE_LIMIT };
var cacheEvent = summary.lastOfflineEvent || {};
var storageValue = storage.supported && storage.quota ? fmtBytes(storage.usage) + ' / ' + fmtBytes(storage.quota) : 'Unavailable';
var storageNote = storage.supported && storage.quota ? storage.percent + '% used by this origin' : 'StorageManager estimate not available';
el.innerHTML =
'
Offline searches' + esc(String((idb.offlineSearches || 0) + (ls.offlineSearches || 0))) + '
IndexedDB ' + esc(String(idb.offlineSearches || 0)) + ' / localStorage ' + esc(String(ls.offlineSearches || 0)) + '; limit ' + esc(String(limits.offlineSearches)) + '' +
'
Scan cache' + esc(String((idb.scanCache || 0) + (ls.scanCache || 0))) + '
IndexedDB ' + esc(String(idb.scanCache || 0)) + ' / localStorage ' + esc(String(ls.scanCache || 0)) + '; limit ' + esc(String(limits.scanCache)) + '' +
'
Quota' + esc(storageValue) + '
' + esc(storageNote) + '' +
'
Offline schemav' + esc(String(limits.offlineSchemaVersion || OFFLINE_SCHEMA_VERSION)) + '
' + esc(cacheEvent.detail || 'No cache write in this session') + '' +
'
Fallback bytes' + esc(fmtBytes((ls.offlineBytes || 0) + (ls.scanBytes || 0))) + '
Recoverable localStorage cache payload only';
}
function setCacheStatus(msg, cls) {
var el = document.getElementById('cacheSettingsStatus');
if (!el) return;
el.textContent = msg;
el.className = 'proxy-settings-status' + (cls ? ' ' + cls : '');
}
async function refreshCacheDiagnostics() {
renderCacheDiagnosticsSummary(null);
try {
_cacheDiagnostics = await buildCacheDiagnostics();
renderCacheDiagnosticsSummary(_cacheDiagnostics);
renderDiagnostics();
} catch(e) {
_cacheDiagnostics = { error: (e && e.message) || 'cache diagnostics failed' };
renderCacheDiagnosticsSummary(_cacheDiagnostics);
renderDiagnostics();
}
}
function buildDiagnosticsPayload() {
return {
schema: 'scripthunt-diagnostics',
schemaVersion: 1,
app: 'ScriptHunt',
version: document.querySelector('.version').textContent,
generatedAt: new Date().toISOString(),
online: navigator.onLine,
userAgent: navigator.userAgent,
customProxyConfigured: !!_customProxy,
publicProxyFallbackEnabled: _allowPublicProxy,
githubTokenConfigured: !!_ghToken,
githubRateLimit: _ghRate,
sources: Object.keys(SOURCES).map(function(id) {
var meta = state.sourceMeta[id] || {};
return {
id: id,
name: SOURCES[id].name,
declaredMethod: SOURCES[id].method || '',
declaredRoute: SOURCES[id].route || '',
capabilities: SOURCES[id].capabilities || '',
enabled: SOURCES[id].enabled,
status: state.sourceStatus[id] || 'idle',
count: state.sourceCounts[id] || 0,
error: state.sourceErrors[id] || '',
envelopeVersion: meta.schemaVersion || SOURCE_ENVELOPE_VERSION,
total: meta.total === undefined ? null : meta.total,
hasMore: meta.hasMore === undefined ? null : meta.hasMore,
partial: !!meta.partial,
partialReason: meta.partialReason || '',
latencyMs: meta.latencyMs || 0,
cacheHit: !!meta.cacheHit,
route: meta.route || '',
httpStatus: meta.httpStatus || 0,
errorClass: meta.errorClass || '',
mode: meta.mode || '',
query: meta.query || '',
};
}),
sourceHealth: _sourceHealth,
proxyHealth: {
lastUsedBySource: _proxyHealth.lastUsedBySource,
failures: _proxyHealth.failures,
errorsBySource: _proxyHealth.errorsBySource,
},
cacheDiagnostics: _cacheDiagnostics || { status: 'checking' },
preferences: prefDiagnostics(),
interfaceLocale: _uiLocale,
filters: {
q: searchInput.value.trim(),
site: siteFilter.value.trim(),
sort: sortSelect.value,
license: licenseFilter.value.trim(),
minInstalls: minInstallsFilter.value.trim(),
updated: updatedFilter.value,
language: languageFilter.value,
grant: grantFilterInput.value.trim(),
risk: riskFilter.value,
},
};
}
function renderDiagnostics() {
document.getElementById('diagnosticsOutput').value = JSON.stringify(buildDiagnosticsPayload(), null, 2);
}
function showPwaUpdateToast(registration) {
if (!registration) return;
if (window.__pwaUpdateToastShown) return;
window.__pwaUpdateToastShown = true;
showToast('ScriptHunt update available', 'info', 12000, function() {
if (registration.waiting && registration.waiting.postMessage) {
window.__pwaRefreshPending = true;
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
} else {
location.reload();
}
}, 'Refresh');
}
function setupServiceWorker() {
if (!('serviceWorker' in navigator)) return;
navigator.serviceWorker.register('sw.js').then(function(registration) {
function watchWorker(worker) {
if (!worker) return;
function maybeReady() {
if (worker.state === 'installed' && navigator.serviceWorker.controller) showPwaUpdateToast(registration);
}
worker.addEventListener('statechange', maybeReady);
maybeReady();
}
if (registration.waiting && navigator.serviceWorker.controller) showPwaUpdateToast(registration);
registration.addEventListener('updatefound', function() { watchWorker(registration.installing); });
if (!navigator.onLine && navigator.serviceWorker.controller) showToast('Offline shell loaded from cache', 'info', 4000);
}).catch(function() {});
navigator.serviceWorker.addEventListener('message', function(e) {
if (!e.data) return;
if (e.data.type === 'CACHE_FALLBACK') showToast('Cached shell served while offline', 'info', 4000);
if (e.data.type === 'ASSET_UPDATED' && !window.__assetUpdateToastShown) {
window.__assetUpdateToastShown = true;
showToast('Updated application assets are ready', 'info', 15000, function() { location.reload(); }, 'Reload');
}
});
navigator.serviceWorker.addEventListener('controllerchange', function() {
if (window.__pwaRefreshPending) location.reload();
});
}
/* ===== Init ===== */
var savedSort = _prefGet('sort', 'relevance');
if (savedSort) { sortSelect.value = savedSort; state.sortBy = savedSort; }
applyUiLocale(_uiLocale, false);
EMPTY_HOME = emptyHomeHtml();
EMPTY_NORESULT = emptyNoResultHtml();
var urlParams = new URLSearchParams(window.location.search);
var initQ = restoreUrlState(urlParams);
window.addEventListener('online', function() { renderOfflineCachePanel(); if (state.offlineCache) showToast('Back online. Refresh cached results when ready.', 'info', 2500); });
window.addEventListener('offline', renderOfflineCachePanel);
renderSourceToggles(); renderOfflineCachePanel(); searchInput.focus();
if (!initQ) grid.innerHTML = EMPTY_HOME;
if (initQ) { searchInput.value = initQ; clearBtn.classList.add('visible'); executeSearch(initQ); }
try {
if (sessionStorage.getItem('sh_reopen_diagnostics') === 'proxy-saved') {
sessionStorage.removeItem('sh_reopen_diagnostics');
setTimeout(function() {
try {
var section = document.getElementById('diagnosticsSection');
if (section && section.showPopover) section.showPopover();
} catch(e) {}
setProxyStatus('Custom proxy saved locally. Run Test to verify allowlist behavior.', 'ok');
renderDiagnostics();
}, 0);
}
} catch(e) {}
setupServiceWorker();