-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemp.js
More file actions
458 lines (408 loc) · 40.8 KB
/
Copy pathtemp.js
File metadata and controls
458 lines (408 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
> <script>
const $ = (id) => document.getElementById(id);
const authSel = $('authMethod');
let scanMode = 'remote';
// Toggle between Remote Scan & Local Scan modes
function setMode(mode) {
scanMode = mode;
if (mode === 'remote') {
$('btn-remote').classList.add('active');
$('btn-local').classList.remove('active');
document.querySelectorAll('.remote-only').forEach(el => el.style.display = 'block');
document.querySelectorAll('.local-only').forEach(el => el.style.display = 'none');
} else {
$('btn-remote').classList.remove('active');
$('btn-local').classList.add('active');
document.querySelectorAll('.remote-only').forEach(el => el.style.display = 'none');
document.querySelectorAll('.local-only').forEach(el => el.style.display = 'block');
}
}
// Request notifications permission
if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
document.addEventListener('click', () => {
if (Notification.permission === 'default') {
Notification.requestPermission();
}
}, { once: true });
}
function syncAuth() {
document.querySelectorAll('.auth-fields').forEach(el => {
if (el.dataset.for === authSel.value) {
el.classList.add('show');
} else {
el.classList.remove('show');
}
});
}
authSel.addEventListener('change', syncAuth); syncAuth();
function syncLlmKeys() {
const mode = $('llmMode').value;
$('claudeKeyGroup').style.display = (mode === 'claude' || mode === 'both') ? 'block' : 'none';
$('geminiKeyGroup').style.display = (mode === 'gemini' || mode === 'both') ? 'block' : 'none';
}
function syncWindow() {
const custom = $('windowSel').value === 'custom';
$('customRange').style.display = custom ? 'grid' : 'none';
}
let lastHtml = '';
function card(k, v, icon) {
return `<div class="card"><div class="k"><i data-lucide="${icon}"></i> ${k}</div><div
class="v">${v}</div></div>`;
}
$('form').addEventListener('submit', async (e) => {
e.preventDefault();
const repo = $('repo').value.trim();
const localPath = $('localPath').value.trim();
if (scanMode === 'remote' && !repo) { alert('Specify a Git repository URL to proceed.'); return; }
if (scanMode === 'local' && !localPath) { alert('Specify a local folder path to proceed.'); return; }
const llmMode = $('llmMode').value;
const claudeKey = $('claudeKey').value.trim();
const geminiKey = $('geminiKey').value.trim();
if ((llmMode === 'claude' || llmMode === 'both') && !claudeKey) {
alert('Please enter your Claude API Key to run Claude analysis.');
$('claudeKey').focus();
return;
}
if ((llmMode === 'gemini' || llmMode === 'both') && !geminiKey) {
alert('Please enter your Gemini API Key to run Gemini analysis.');
$('geminiKey').focus();
return;
}
const auth = {};
if (scanMode === 'remote') {
const m = authSel.value;
if (m === 'token') auth.token = $('token').value.trim();
else if (m === 'app') { auth.username = $('username').value.trim(); auth.appPassword =
$('appPassword').value.trim(); }
else if (m === 'api') { auth.email = $('email').value.trim(); auth.apiToken = $('apiToken').value.trim(); }
}
const winSel = $('windowSel') ? $('windowSel').value : '30';
const custom = winSel === 'custom';
const body = {
repo: scanMode === 'remote' ? repo : '',
localPath: scanMode === 'local' ? localPath : '',
branch: $('branch').value.trim(),
name: $('name').value.trim(),
auth,
llmMode,
claudeKey,
geminiKey,
windowDays: custom ? 30 : Number(winSel),
since: custom ? ($('sinceDate').value || undefined) : undefined,
until: custom ? ($('untilDate').value || undefined) : undefined
};
// Setup visual progress box
$('output').classList.remove('reveal-active');
$('placeholder').style.display = 'flex';
$('placeholder').innerHTML = `
<div class="progress-box">
<!-- SVG Detective Bot Character Searching AI Code -->
<svg class="detective-bot" viewBox="0 0 160 160" width="120" height="120" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="booster-grad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="var(--neon-violet)" stop-opacity="0.8"/>
<stop offset="100%" stop-color="transparent"/>
</linearGradient>
<linearGradient id="laser-beam" x1="0.5" y1="0" x2="0.5" y2="1">
<stop offset="0%" stop-color="rgba(0, 242, 254, 0.4)"/>
<stop offset="100%" stop-color="rgba(127, 0, 255, 0.0)"/>
</linearGradient>
</defs>
<!-- floating background code particles -->
<g class="float-code">
<text x="20" y="40" class="code-char char-1">{</text>
<text x="130" y="55" class="code-char char-2">AI</text>
<text x="10" y="110" class="code-char char-3">1</text>
<text x="140" y="120" class="code-char char-4">0</text>
<text x="35" y="140" class="code-char char-5">}</text>
</g>
<g class="bot-body">
<!-- Rocket Booster Fire -->
<path d="M 70 100 L 80 130 L 90 100 Z" fill="url(#booster-grad)" class="booster-flame"/>
<!-- Chassis / Torso -->
<rect x="62" y="85" width="36" height="20" rx="6" fill="#1e293b" stroke="var(--neon-cyan)"
stroke-width="1.5"/>
<circle cx="80" cy="95" r="4" fill="var(--neon-violet)"/>
<!-- Head / Helmet -->
<rect x="50" y="35" width="60" height="50" rx="18" fill="#161a2b" stroke="var(--neon-cyan)"
stroke-width="2.5"/>
<!-- Searching Eye Visor -->
<rect x="58" y="47" width="44" height="18" rx="9" fill="#040814" stroke="rgba(255,255,255,0.1)"/>
<!-- Visor scanning light -->
<ellipse cx="80" cy="56" rx="8" ry="4" fill="var(--neon-cyan)">
<animate attributeName="cx" values="68;92;68" dur="2s" repeatCount="indefinite"/>
</ellipse>
<!-- Scanning light beam cone -->
<polygon points="80,62 30,150 130,150" fill="url(#laser-beam)" class="scan-beam"/>
<!-- Antenna -->
<line x1="80" y1="35" x2="80" y2="20" stroke="var(--neon-cyan)" stroke-width="2"/>
<circle cx="80" cy="18" r="3.5" fill="var(--neon-violet)" style="filter: drop-shadow(0 0 4px
var(--neon-violet));">
<animate attributeName="opacity" values="1;0.3;1" dur="1s" repeatCount="indefinite"/>
</circle>
</g>
</svg>
<div style="font-weight: 600; color: #fff; font-size: 15px;" id="p-status">Contacting scan server...</div>
<div class="progress-bar-outer">
<div class="progress-bar-inner" id="p-bar" style="width: 0%;"></div>
</div>
<div class="progress-meta">
<span id="p-pct">0%</span>
<span id="p-time">Estimating time...</span>
</div>
<div class="progress-current-file" id="p-file" style="display: none;">Waiting...</div>
<!-- Live character/code scanning stream -->
<div class="terminal-stream" id="p-terminal">
<div class="terminal-line info">[INIT] Standby. Forensic attribution engine booting...</div>
</div>
</div>
`;
$('output').style.display = 'none';
$('go').disabled = true;
// Terminal Logging helper
const logToTerminal = (text, type = 'info') => {
const term = $('p-terminal');
if (!term) return;
const el = document.createElement('div');
el.className = `terminal-line ${type}`;
el.textContent = `[${new Date().toLocaleTimeString()}] ${text}`;
term.appendChild(el);
if (term.children.length > 20) {
term.removeChild(term.firstChild);
}
term.scrollTop = term.scrollHeight;
};
// Staggered mock log messages to simulate "character search" AST parsing activities
let logSeq = 0;
const logInterval = setInterval(() => {
const codes = [
"PARSING AST: Found function declaration on master branch...",
"ANALYZING: Claude pattern signature checked on regex Match...",
"BLAME CHECK: commit velocity line counts checked...",
"METRIC: Analyzing single-file line threshold anomalies...",
"FORENSICS: Comparing author git blame patterns...",
"AST PARSER: node.walk => detected 'ArrowFunctionExpression'",
"SIGNATURE: Google Antigravity/Gemini markers loaded...",
"CHECKING: Filtering locked packages & specification sheets...",
"MATCH: High similarity to assistant instruction style...",
"FORENSICS: Extracting email initials from commit metadata...",
"AST SCAN: Checking if docstring contains helper tags...",
"AI ATTRIBUTION: Scanning for copy-paste footprints..."
];
const randText = codes[logSeq % codes.length];
logSeq++;
logToTerminal(randText, Math.random() > 0.6 ? 'success' : 'info');
}, 450);
const startTime = Date.now();
try {
const response = await fetch('/api/scan', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!response.ok) {
const errText = await response.text();
let errMsg = 'scan failed';
try { errMsg = JSON.parse(errText).error || errMsg; } catch {}
throw new Error(errMsg);
}
// Stream the response body
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop(); // Hold onto the last incomplete chunk
for (const line of lines) {
if (!line.trim()) continue;
let msg;
try { msg = JSON.parse(line); } catch (e) { continue; }
if (msg.type === 'progress') {
if (msg.step === 'init' || msg.step === 'cloning' || msg.step === 'listing') {
$('p-status').textContent = msg.message;
$('p-bar').style.width = '5%';
$('p-pct').textContent = '5%';
$('p-file').style.display = 'none';
logToTerminal(msg.message, 'info');
}
else if (msg.step === 'blaming') {
const current = msg.current || 0;
const total = msg.total || 1;
const pctVal = Math.round((current / total) * 100);
$('p-status').textContent = `Running Git blame analysis...`;
$('p-bar').style.width = `${pctVal}%`;
$('p-pct').textContent = `${pctVal}% (${current}/${total})`;
// Estimating Time Remaining
const elapsedMs = Date.now() - startTime;
if (current > 5) {
const msPerFile = elapsedMs / current;
const remainingFiles = total - current;
const remainingSeconds = Math.round((remainingFiles * msPerFile) / 1000);
$('p-time').textContent = remainingSeconds > 0 ? `Est. remaining: ~${remainingSeconds}s` :
'Finishing blame...';
} else {
$('p-time').textContent = 'Estimating remaining time...';
}
if (msg.file) {
$('p-file').style.display = 'block';
$('p-file').textContent = `📄 blaming: ${msg.file}`;
logToTerminal(`Blaming target: ${msg.file.split('/').pop()}`, 'info');
}
}
else if (msg.step === 'commits') {
$('p-status').textContent = msg.message;
$('p-bar').style.width = '98%';
$('p-pct').textContent = '98%';
$('p-file').style.display = 'none';
logToTerminal(msg.message, 'success');
}
}
else if (msg.type === 'error') {
logToTerminal(`SCAN ERROR: ${msg.error || 'stream error occurred'}`, 'alert');
throw new Error(msg.error || 'stream error occurred');
}
else if (msg.type === 'complete') {
const s = msg.summary || {};
logToTerminal(`SCAN SUCCESS: Completed analysis for ${s.files} source files!`, 'success');
// Render KPI cards at top
$('cards').innerHTML =
card('AI-assisted code', (s.repoAiPct ?? 0) + '%', 'bot') +
card('Est. AI LOC Added', (s.totalAiLinesAdded || 0).toLocaleString(), 'code-2') +
card('Active LOC', (s.totalActiveLOC || 0).toLocaleString(), 'activity') +
card('Files Scanned', s.files || 0, 'files');
lucide.createIcons();
$('caption').innerHTML = `🔠scanned: <strong>${esc(msg.repo)}</strong> — ${(s.repoAiPct ?? 0)}% AI
ratio on master`;
window.__aiHtml = msg.html;
window.__teamHtml = msg.teamHtml || '';
lastHtml = msg.html;
function renderToShadow(html) {
const container = $('frame');
if (!container.shadowRoot) container.attachShadow({ mode: 'open' });
const shadow = container.shadowRoot;
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
shadow.innerHTML = '';
doc.querySelectorAll('style, link[rel="stylesheet"]').forEach(el =>
shadow.appendChild(el.cloneNode(true)));
Array.from(doc.body.childNodes).forEach(node => shadow.appendChild(node.cloneNode(true)));
doc.querySelectorAll('script').forEach(s => {
if (s.src) {
if (!document.querySelector(`script[src="${s.src}"]`)) {
const newS = document.createElement('script');
newS.src = s.src;
document.head.appendChild(newS);
}
} else {
try {
const fn = new Function(s.textContent);
fn();
} catch (err) {
console.error("Error evaluating report script:", err);
}
}
});
}
renderToShadow(lastHtml);
// Same scan, two views: wire AI ⇄ Team Pulse tabs to swap the view.
(function () {
const tabs = document.querySelectorAll('#viewTabs .vtab');
tabs.forEach((b) => {
b.onclick = () => {
tabs.forEach((x) => { x.classList.remove('active'); x.style.background = ''; x.style.color = '';
});
b.classList.add('active'); b.style.background = 'var(--primary-gradient)'; b.style.color = '#fff';
const team = b.dataset.view === 'team';
lastHtml = team
? (window.__teamHtml || '<p style="font-family:sans-serif;color:#888;padding:24px">No team data
for this scan.</p>')
: window.__aiHtml;
renderToShadow(lastHtml);
};
});
})();
$('placeholder').style.display = 'none';
$('output').style.display = 'grid';
$('output').classList.add('reveal-active');
// Fire native notification if permission granted
if (typeof Notification !== 'undefined' && Notification.permission === 'granted') {
new Notification(`🔬 Scan Complete: ${msg.repo}`, {
body: `Analyzed ${s.files} files successfully. Master branch is ${s.repoAiPct}% AI-assisted.`,
icon: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
viewBox="0 0 24 24" fill="none" stroke="%2300f2fe" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>'
});
}
}
}
}
} catch (err) {
logToTerminal(`CRITICAL ERROR: ${err.message}`, 'alert');
$('placeholder').innerHTML = '<div class="err"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18"
height="18" rx="2" ry="2"/><line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9"
y2="15"/></svg><div><strong>Scan Failed</strong><br>' + err.message + '</div></div>';
} finally {
clearInterval(logInterval);
$('go').disabled = false;
}
});
const escSrcDoc = (s) => String(s || '').replace(/&/g, '&').replace(/"/g, '"').replace(/'/g,
''').replace(/</g, '<').replace(/>/g, '>');
function getCombinedHtml() {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Combined AI Code Scanner Report</title>
<style>
body { margin: 0; background: #000; color: #fff; font-family: 'Inter', sans-serif; overflow: hidden; }
.tabs { display: flex; gap: 8px; padding: 14px 20px; background: #0a0a0a; border-bottom: 1px solid #333;
align-items: center; }
.tabs h3 { margin: 0; margin-right: 16px; font-size: 14px; font-weight: 600; color: #aaa; letter-spacing: 0.5px;
text-transform: uppercase; }
button { background: transparent; color: #888; border: 1px solid transparent; padding: 6px 14px; border-radius:
6px; cursor: pointer; font-weight: 600; transition: 0.2s; }
button:hover { background: #111; color: #fff; }
button.active { background: #222; color: #fff; border-color: #444; }
iframe { width: 100%; height: calc(100vh - 65px); border: none; display: none; background: #000; }
iframe.active { display: block; }
</style>
</head>
<body>
<div class="tabs">
<h3>Offline Report View</h3>
<button class="active" onclick="show('ai', this)">🤖 AI Code Scan</button>
<button onclick="show('team', this)">📊 Team Pulse</button>
</div>
<iframe id="ai" class="active" srcdoc="${escSrcDoc(window.__aiHtml)}"></iframe>
<iframe id="team" srcdoc="${escSrcDoc(window.__teamHtml || '<p
style="color:#888;padding:24px;font-family:sans-serif">No Team Pulse data generated for this scan.</p>')}"></iframe>
> <script>
function show(id, btn) {
document.querySelectorAll('iframe').forEach(f => f.classList.remove('active'));
document.getElementById(id).classList.add('active');
document.querySelectorAll('button').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
}
</script>
</body>
</html>`;
}
$('download').addEventListener('click', () => {
const combined = getCombinedHtml();
const blob = new Blob([combined], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = 'ai-code-report.html'; a.click();
URL.revokeObjectURL(url);
});
$('openTab').addEventListener('click', () => {
const w = window.open(); w.document.write(getCombinedHtml()); w.document.close();
});
</script>
</body>
</html>