impeccable 2.0.1 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,8 @@
2
2
 
3
3
  /**
4
4
  * Anti-Pattern Detector for Impeccable
5
+ * Copyright (c) 2026 Paul Bakaus
6
+ * SPDX-License-Identifier: BSL-1.1
5
7
  *
6
8
  * Universal file — auto-detects environment (browser vs Node) and adapts.
7
9
  *
@@ -1208,11 +1210,20 @@ if (IS_BROWSER) {
1208
1210
  // Inject hover styles via CSS (more reliable than JS event listeners)
1209
1211
  const styleEl = document.createElement('style');
1210
1212
  styleEl.textContent = `
1213
+ @keyframes impeccable-reveal {
1214
+ from { opacity: 0; outline-color: transparent; }
1215
+ to { opacity: 1; outline-color: ${OUTLINE_COLOR}; }
1216
+ }
1211
1217
  .impeccable-overlay:not(.impeccable-banner) {
1212
1218
  pointer-events: none;
1213
1219
  outline: 2px solid ${OUTLINE_COLOR};
1214
1220
  border-radius: 4px;
1215
1221
  transition: outline-color 0.3s ease;
1222
+ animation: impeccable-reveal 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
1223
+ animation-play-state: paused;
1224
+ }
1225
+ .impeccable-overlay.impeccable-visible {
1226
+ animation-play-state: running;
1216
1227
  }
1217
1228
  .impeccable-overlay.impeccable-hover {
1218
1229
  outline-color: rgba(0,0,0,0.85);
@@ -1285,6 +1296,7 @@ if (IS_BROWSER) {
1285
1296
  // Uses a huge rootMargin so all *rendered* elements count as intersecting,
1286
1297
  // while display:none / closed <details> / hidden modals etc. do not.
1287
1298
  // This is event-driven -- no polling needed.
1299
+ let overlayIndex = 0;
1288
1300
  const visibilityObserver = new IntersectionObserver((entries) => {
1289
1301
  for (const entry of entries) {
1290
1302
  const overlay = entry.target._impeccableOverlay;
@@ -1292,6 +1304,11 @@ if (IS_BROWSER) {
1292
1304
  if (entry.isIntersecting) {
1293
1305
  overlay.style.display = '';
1294
1306
  positionOverlay(overlay);
1307
+ if (!overlay._revealed) {
1308
+ overlay._revealed = true;
1309
+ overlay.style.animationDelay = `${(overlay._staggerIndex || 0) * 80}ms`;
1310
+ requestAnimationFrame(() => overlay.classList.add('impeccable-visible'));
1311
+ }
1295
1312
  } else {
1296
1313
  overlay.style.display = 'none';
1297
1314
  }
@@ -1358,6 +1375,7 @@ if (IS_BROWSER) {
1358
1375
 
1359
1376
  // Start hidden; the IntersectionObserver will show it once the target is rendered
1360
1377
  outline.style.display = 'none';
1378
+ outline._staggerIndex = overlayIndex++;
1361
1379
  el._impeccableOverlay = outline;
1362
1380
  visibilityObserver.observe(el);
1363
1381
 
@@ -1378,8 +1396,13 @@ if (IS_BROWSER) {
1378
1396
  background: LABEL_BG, color: 'white',
1379
1397
  fontFamily: 'system-ui, sans-serif', fontSize: '13px',
1380
1398
  display: 'flex', alignItems: 'center', pointerEvents: 'auto',
1381
- height: '36px',
1399
+ height: '36px', overflow: 'hidden', maxWidth: '100vw',
1400
+ transform: 'translateY(-100%)',
1401
+ transition: 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
1382
1402
  });
1403
+ requestAnimationFrame(() => requestAnimationFrame(() => {
1404
+ banner.style.transform = 'translateY(0)';
1405
+ }));
1383
1406
 
1384
1407
  // Scrollable findings area
1385
1408
  const scrollArea = document.createElement('div');
@@ -1473,6 +1496,8 @@ if (IS_BROWSER) {
1473
1496
  // Skip browser extension elements (Claude, etc.)
1474
1497
  const elId = el.id || '';
1475
1498
  if (elId.startsWith('claude-') || elId.startsWith('cic-')) continue;
1499
+ // Skip html/body -- page-level findings go in the banner, not a full-page overlay
1500
+ if (el === document.body || el === document.documentElement) continue;
1476
1501
 
1477
1502
  const findings = [
1478
1503
  ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
@@ -1922,31 +1947,108 @@ const REGEX_ANALYZERS = [
1922
1947
  },
1923
1948
  ];
1924
1949
 
1925
- function detectText(content, filePath) {
1926
- const findings = [];
1927
- const lines = content.split('\n');
1950
+ // ---------------------------------------------------------------------------
1951
+ // Style block extraction (Vue/Svelte <style> blocks)
1952
+ // ---------------------------------------------------------------------------
1953
+
1954
+ function extractStyleBlocks(content, ext) {
1955
+ ext = ext.toLowerCase();
1956
+ if (ext !== '.vue' && ext !== '.svelte') return [];
1957
+ const blocks = [];
1958
+ const re = /<style[^>]*>([\s\S]*?)<\/style>/gi;
1959
+ let m;
1960
+ while ((m = re.exec(content)) !== null) {
1961
+ const before = content.substring(0, m.index);
1962
+ const startLine = before.split('\n').length + 1;
1963
+ blocks.push({ content: m[1], startLine });
1964
+ }
1965
+ return blocks;
1966
+ }
1967
+
1968
+ // ---------------------------------------------------------------------------
1969
+ // CSS-in-JS extraction (styled-components, emotion)
1970
+ // ---------------------------------------------------------------------------
1971
+
1972
+ const CSS_IN_JS_EXTENSIONS = new Set(['.js', '.ts', '.jsx', '.tsx']);
1973
+
1974
+ function extractCSSinJS(content, ext) {
1975
+ ext = ext.toLowerCase();
1976
+ if (!CSS_IN_JS_EXTENSIONS.has(ext)) return [];
1977
+ const blocks = [];
1978
+ const re = /(?:styled(?:\.\w+|\([^)]+\))|css)\s*`([\s\S]*?)`/g;
1979
+ let m;
1980
+ while ((m = re.exec(content)) !== null) {
1981
+ const before = content.substring(0, m.index);
1982
+ const startLine = before.split('\n').length;
1983
+ blocks.push({ content: m[1], startLine });
1984
+ }
1985
+ return blocks;
1986
+ }
1928
1987
 
1988
+ function runRegexMatchers(lines, filePath, lineOffset = 0, blockContext = null) {
1989
+ const findings = [];
1929
1990
  for (const matcher of REGEX_MATCHERS) {
1930
1991
  for (let i = 0; i < lines.length; i++) {
1931
1992
  const line = lines[i];
1932
1993
  matcher.regex.lastIndex = 0;
1933
1994
  let m;
1934
1995
  while ((m = matcher.regex.exec(line)) !== null) {
1935
- if (matcher.test(m, line)) {
1936
- findings.push(finding(matcher.id, filePath, matcher.fmt(m, line), i + 1));
1996
+ // For extracted blocks, use nearby lines as context for multi-line CSS patterns
1997
+ const context = blockContext
1998
+ ? lines.slice(Math.max(0, i - 3), Math.min(lines.length, i + 4)).join(' ')
1999
+ : line;
2000
+ if (matcher.test(m, context)) {
2001
+ findings.push(finding(matcher.id, filePath, matcher.fmt(m, context), i + 1 + lineOffset));
1937
2002
  }
1938
2003
  }
1939
2004
  }
1940
2005
  }
2006
+ return findings;
2007
+ }
2008
+
2009
+ function detectText(content, filePath) {
2010
+ const findings = [];
2011
+ const lines = content.split('\n');
2012
+ const ext = filePath ? (filePath.match(/\.\w+$/)?.[0] || '').toLowerCase() : '';
2013
+
2014
+ // Run regex matchers on the full file content (catches Tailwind classes, inline styles)
2015
+ // Enable block context for CSS files where related properties span multiple lines
2016
+ const cssLike = new Set(['.css', '.scss', '.less']);
2017
+ findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null));
2018
+
2019
+ // Extract and scan <style> blocks from Vue/Svelte SFCs
2020
+ const styleBlocks = extractStyleBlocks(content, ext);
2021
+ for (const block of styleBlocks) {
2022
+ const blockLines = block.content.split('\n');
2023
+ findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true));
2024
+ }
2025
+
2026
+ // Extract and scan CSS-in-JS template literals
2027
+ const cssJsBlocks = extractCSSinJS(content, ext);
2028
+ for (const block of cssJsBlocks) {
2029
+ const blockLines = block.content.split('\n');
2030
+ findings.push(...runRegexMatchers(blockLines, filePath, block.startLine - 1, true));
2031
+ }
2032
+
2033
+ // Deduplicate findings (same antipattern + similar snippet, within 2 lines)
2034
+ const deduped = [];
2035
+ for (const f of findings) {
2036
+ const isDupe = deduped.some(d =>
2037
+ d.antipattern === f.antipattern &&
2038
+ d.snippet === f.snippet &&
2039
+ Math.abs(d.line - f.line) <= 2
2040
+ );
2041
+ if (!isDupe) deduped.push(f);
2042
+ }
1941
2043
 
1942
2044
  // Page-level analyzers only run on full pages
1943
2045
  if (isFullPage(content)) {
1944
2046
  for (const analyzer of REGEX_ANALYZERS) {
1945
- findings.push(...analyzer(content, filePath));
2047
+ deduped.push(...analyzer(content, filePath));
1946
2048
  }
1947
2049
  }
1948
2050
 
1949
- return findings;
2051
+ return deduped;
1950
2052
  }
1951
2053
 
1952
2054
  // ---------------------------------------------------------------------------
@@ -1993,7 +2095,8 @@ function formatFindings(findings, jsonMode) {
1993
2095
  }
1994
2096
  const out = [];
1995
2097
  for (const [file, items] of Object.entries(grouped)) {
1996
- out.push(`\n${file}`);
2098
+ const importNote = items[0]?.importedBy?.length ? ` (imported by ${items[0].importedBy.join(', ')})` : '';
2099
+ out.push(`\n${file}${importNote}`);
1997
2100
  for (const item of items) {
1998
2101
  out.push(` ${item.line ? `line ${item.line}: ` : ''}[${item.antipattern}] ${item.snippet}`);
1999
2102
  out.push(` → ${item.description}`);
@@ -2022,10 +2125,175 @@ async function handleStdin() {
2022
2125
  return detectText(input, '<stdin>');
2023
2126
  }
2024
2127
 
2128
+ // ---------------------------------------------------------------------------
2129
+ // Import graph (multi-file awareness)
2130
+ // ---------------------------------------------------------------------------
2131
+
2132
+ function resolveImport(specifier, fromDir, fileSet) {
2133
+ if (!/^[./]/.test(specifier)) return null; // skip bare specifiers
2134
+ const base = path.resolve(fromDir, specifier);
2135
+ if (fileSet.has(base)) return base;
2136
+ for (const ext of SCANNABLE_EXTENSIONS) {
2137
+ const withExt = base + ext;
2138
+ if (fileSet.has(withExt)) return withExt;
2139
+ }
2140
+ // index file convention
2141
+ for (const ext of SCANNABLE_EXTENSIONS) {
2142
+ const indexFile = path.join(base, 'index' + ext);
2143
+ if (fileSet.has(indexFile)) return indexFile;
2144
+ }
2145
+ return null;
2146
+ }
2147
+
2148
+ function buildImportGraph(files) {
2149
+ const fileSet = new Set(files);
2150
+ const graph = new Map();
2151
+
2152
+ for (const file of files) {
2153
+ const content = fs.readFileSync(file, 'utf-8');
2154
+ const dir = path.dirname(file);
2155
+ const imports = new Set();
2156
+
2157
+ // ES imports: import ... from '...' and import '...'
2158
+ const esRe = /import\s+(?:[\s\S]*?from\s+)?['"]([^'"]+)['"]/g;
2159
+ let m;
2160
+ while ((m = esRe.exec(content)) !== null) {
2161
+ const resolved = resolveImport(m[1], dir, fileSet);
2162
+ if (resolved) imports.add(resolved);
2163
+ }
2164
+
2165
+ // CSS @import
2166
+ const cssRe = /@import\s+(?:url\(\s*)?['"]?([^'");\s]+)['"]?\s*\)?/g;
2167
+ while ((m = cssRe.exec(content)) !== null) {
2168
+ const resolved = resolveImport(m[1], dir, fileSet);
2169
+ if (resolved) imports.add(resolved);
2170
+ }
2171
+
2172
+ // SCSS @use / @forward
2173
+ const scssRe = /@(?:use|forward)\s+['"]([^'"]+)['"]/g;
2174
+ while ((m = scssRe.exec(content)) !== null) {
2175
+ const resolved = resolveImport(m[1], dir, fileSet);
2176
+ if (resolved) imports.add(resolved);
2177
+ }
2178
+
2179
+ graph.set(file, imports);
2180
+ }
2181
+ return graph;
2182
+ }
2183
+
2184
+ // ---------------------------------------------------------------------------
2185
+ // Framework dev server detection
2186
+ // ---------------------------------------------------------------------------
2187
+
2188
+ const FRAMEWORK_CONFIGS = [
2189
+ { name: 'Next.js', files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], defaultPort: 3000,
2190
+ portRe: /port\s*[:=]\s*(\d+)/,
2191
+ fingerprint: { header: 'x-powered-by', value: /next/i } },
2192
+ { name: 'SvelteKit', files: ['svelte.config.js', 'svelte.config.ts'], defaultPort: 5173,
2193
+ portRe: /port\s*[:=]\s*(\d+)/,
2194
+ fingerprint: { header: 'x-sveltekit-page', value: null } },
2195
+ { name: 'Nuxt', files: ['nuxt.config.js', 'nuxt.config.ts'], defaultPort: 3000,
2196
+ portRe: /port\s*[:=]\s*(\d+)/,
2197
+ fingerprint: { header: 'x-powered-by', value: /nuxt/i } },
2198
+ { name: 'Vite', files: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'], defaultPort: 5173,
2199
+ portRe: /port\s*[:=]\s*(\d+)/,
2200
+ fingerprint: { body: /@vite\/client/ } },
2201
+ { name: 'Astro', files: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'], defaultPort: 4321,
2202
+ portRe: /port\s*[:=]\s*(\d+)/,
2203
+ fingerprint: { body: /astro/i } },
2204
+ { name: 'Angular', files: ['angular.json'], defaultPort: 4200,
2205
+ portRe: /"port"\s*:\s*(\d+)/,
2206
+ fingerprint: { body: /ng-version/i } },
2207
+ { name: 'Remix', files: ['remix.config.js', 'remix.config.ts'], defaultPort: 3000,
2208
+ portRe: /port\s*[:=]\s*(\d+)/,
2209
+ fingerprint: { header: 'x-powered-by', value: /remix/i } },
2210
+ ];
2211
+
2212
+ function detectFrameworkConfig(dir) {
2213
+ let entries;
2214
+ try { entries = fs.readdirSync(dir); } catch { return null; }
2215
+ const entrySet = new Set(entries);
2216
+
2217
+ for (const cfg of FRAMEWORK_CONFIGS) {
2218
+ const match = cfg.files.find(f => entrySet.has(f));
2219
+ if (!match) continue;
2220
+
2221
+ const configPath = path.join(dir, match);
2222
+ let port = cfg.defaultPort;
2223
+ try {
2224
+ const content = fs.readFileSync(configPath, 'utf-8');
2225
+ const portMatch = content.match(cfg.portRe);
2226
+ if (portMatch) port = parseInt(portMatch[1], 10);
2227
+ } catch { /* use default */ }
2228
+
2229
+ return { name: cfg.name, port, configPath, fingerprint: cfg.fingerprint };
2230
+ }
2231
+ return null;
2232
+ }
2233
+
2234
+ /**
2235
+ * Check if a port is listening and optionally verify it matches the expected framework.
2236
+ * Returns { listening: true, matched: true/false } or { listening: false }.
2237
+ */
2238
+ async function isPortListening(port, fingerprint = null) {
2239
+ if (!fingerprint) {
2240
+ // Simple TCP probe fallback
2241
+ const net = await import('node:net');
2242
+ return new Promise((resolve) => {
2243
+ const sock = net.default.createConnection({ port, host: '127.0.0.1' });
2244
+ sock.setTimeout(500);
2245
+ sock.on('connect', () => { sock.destroy(); resolve({ listening: true, matched: true }); });
2246
+ sock.on('error', () => resolve({ listening: false }));
2247
+ sock.on('timeout', () => { sock.destroy(); resolve({ listening: false }); });
2248
+ });
2249
+ }
2250
+
2251
+ // HTTP probe with fingerprint matching
2252
+ try {
2253
+ const controller = new AbortController();
2254
+ const timeout = setTimeout(() => controller.abort(), 2000);
2255
+ const res = await fetch(`http://localhost:${port}/`, { signal: controller.signal, redirect: 'follow' });
2256
+ clearTimeout(timeout);
2257
+
2258
+ // Check header fingerprint
2259
+ if (fingerprint.header) {
2260
+ const val = res.headers.get(fingerprint.header);
2261
+ if (val && (!fingerprint.value || fingerprint.value.test(val))) {
2262
+ return { listening: true, matched: true };
2263
+ }
2264
+ }
2265
+
2266
+ // Check body fingerprint
2267
+ if (fingerprint.body) {
2268
+ const body = await res.text();
2269
+ if (fingerprint.body.test(body)) {
2270
+ return { listening: true, matched: true };
2271
+ }
2272
+ }
2273
+
2274
+ // Port is listening but doesn't match the expected framework
2275
+ return { listening: true, matched: false };
2276
+ } catch {
2277
+ return { listening: false };
2278
+ }
2279
+ }
2280
+
2025
2281
  // ---------------------------------------------------------------------------
2026
2282
  // CLI
2027
2283
  // ---------------------------------------------------------------------------
2028
2284
 
2285
+ async function confirm(question) {
2286
+ const rl = (await import('node:readline')).default.createInterface({
2287
+ input: process.stdin, output: process.stderr,
2288
+ });
2289
+ return new Promise((resolve) => {
2290
+ rl.question(`${question} [Y/n] `, (answer) => {
2291
+ rl.close();
2292
+ resolve(!answer || /^y(es)?$/i.test(answer.trim()));
2293
+ });
2294
+ });
2295
+ }
2296
+
2029
2297
  function printUsage() {
2030
2298
  console.log(`Usage: impeccable detect [options] [file-or-dir-or-url...]
2031
2299
 
@@ -2078,13 +2346,74 @@ async function main() {
2078
2346
  catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
2079
2347
 
2080
2348
  if (stat.isDirectory()) {
2081
- for (const file of walkDir(resolved)) {
2349
+ // Check for framework dev server config (skip in JSON mode to avoid polluting output)
2350
+ if (!jsonMode) {
2351
+ const fwConfig = detectFrameworkConfig(resolved);
2352
+ if (fwConfig) {
2353
+ const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
2354
+ if (probe.listening && probe.matched) {
2355
+ process.stderr.write(
2356
+ `\n${fwConfig.name} dev server detected on localhost:${fwConfig.port}.\n` +
2357
+ `For more accurate results, scan the running site:\n` +
2358
+ ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
2359
+ );
2360
+ } else if (probe.listening && !probe.matched) {
2361
+ process.stderr.write(
2362
+ `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
2363
+ `Port ${fwConfig.port} is in use by another service. Start the ${fwConfig.name} dev server and scan via URL for best results.\n\n`
2364
+ );
2365
+ } else {
2366
+ process.stderr.write(
2367
+ `\n${fwConfig.name} project detected (${path.basename(fwConfig.configPath)}).\n` +
2368
+ `Start the dev server and scan via URL for best results:\n` +
2369
+ ` npx impeccable detect http://localhost:${fwConfig.port}\n\n`
2370
+ );
2371
+ }
2372
+ }
2373
+ }
2374
+
2375
+ const files = walkDir(resolved);
2376
+ const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
2377
+
2378
+ // Warn and confirm if scanning many files (jsdom is slow per HTML file)
2379
+ if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
2380
+ process.stderr.write(
2381
+ `\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
2382
+ `Scanning may take a while${htmlCount > 10 ? ' (jsdom processes each HTML file individually)' : ''}.\n` +
2383
+ `Use --fast to skip jsdom, or target a specific subdirectory.\n`
2384
+ );
2385
+ const ok = await confirm('Continue?');
2386
+ if (!ok) { process.stderr.write('Aborted.\n'); process.exit(0); }
2387
+ }
2388
+
2389
+ // Build import graph for multi-file awareness
2390
+ const graph = buildImportGraph(files);
2391
+ // Build reverse map: file -> set of files that import it
2392
+ const importedByMap = new Map();
2393
+ for (const [importer, imports] of graph) {
2394
+ for (const imported of imports) {
2395
+ if (!importedByMap.has(imported)) importedByMap.set(imported, new Set());
2396
+ importedByMap.get(imported).add(importer);
2397
+ }
2398
+ }
2399
+
2400
+ for (const file of files) {
2082
2401
  const ext = path.extname(file).toLowerCase();
2402
+ let fileFindings;
2083
2403
  if (!fastMode && HTML_EXTENSIONS.has(ext)) {
2084
- allFindings.push(...await detectHtml(file));
2404
+ fileFindings = await detectHtml(file);
2085
2405
  } else {
2086
- allFindings.push(...detectText(fs.readFileSync(file, 'utf-8'), file));
2406
+ fileFindings = detectText(fs.readFileSync(file, 'utf-8'), file);
2087
2407
  }
2408
+ // Annotate findings with import context
2409
+ const importers = importedByMap.get(file);
2410
+ if (importers && importers.size > 0) {
2411
+ const importerNames = [...importers].map(f => path.basename(f));
2412
+ for (const f of fileFindings) {
2413
+ f.importedBy = importerNames;
2414
+ }
2415
+ }
2416
+ allFindings.push(...fileFindings);
2088
2417
  }
2089
2418
  } else if (stat.isFile()) {
2090
2419
  const ext = path.extname(resolved).toLowerCase();
@@ -2105,6 +2434,124 @@ async function main() {
2105
2434
  process.exit(0);
2106
2435
  }
2107
2436
 
2437
+ // ---------------------------------------------------------------------------
2438
+ // Live detection server
2439
+ // ---------------------------------------------------------------------------
2440
+
2441
+ async function findOpenPort(start = 8400) {
2442
+ const net = await import('node:net');
2443
+ return new Promise((resolve) => {
2444
+ const server = net.default.createServer();
2445
+ server.listen(start, '127.0.0.1', () => {
2446
+ const port = server.address().port;
2447
+ server.close(() => resolve(port));
2448
+ });
2449
+ server.on('error', () => resolve(findOpenPort(start + 1)));
2450
+ });
2451
+ }
2452
+
2453
+ const LIVE_PID_FILE = path.join((await import('node:os')).default.tmpdir(), 'impeccable-live.json');
2454
+
2455
+ async function liveCli() {
2456
+ const args = process.argv.slice(2);
2457
+ const helpMode = args.includes('--help');
2458
+ const stopMode = args.includes('stop');
2459
+ const portArg = args.find(a => a.startsWith('--port='));
2460
+ const requestedPort = portArg ? parseInt(portArg.split('=')[1], 10) : null;
2461
+
2462
+ if (helpMode) {
2463
+ console.log(`Usage: impeccable-detect live [options]
2464
+
2465
+ Start a local server that serves the browser detection overlay script.
2466
+ Inject the script into any page to scan for anti-patterns in real time.
2467
+
2468
+ Commands:
2469
+ live Start the server (default)
2470
+ live stop Stop a running live server
2471
+
2472
+ Options:
2473
+ --port=PORT Use a specific port (default: auto-detect unused port)
2474
+ --help Show this help message
2475
+
2476
+ The server provides:
2477
+ /detect.js The detection overlay script (inject via <script> tag)
2478
+ /health Health check endpoint
2479
+ /stop Stop the server remotely`);
2480
+ process.exit(0);
2481
+ }
2482
+
2483
+ // Stop a running server
2484
+ if (stopMode) {
2485
+ try {
2486
+ const info = JSON.parse(fs.readFileSync(LIVE_PID_FILE, 'utf-8'));
2487
+ const res = await fetch(`http://localhost:${info.port}/stop`);
2488
+ if (res.ok) {
2489
+ console.log(`Stopped live server on port ${info.port}.`);
2490
+ }
2491
+ } catch {
2492
+ console.log('No running live server found.');
2493
+ }
2494
+ process.exit(0);
2495
+ }
2496
+
2497
+ const http = await import('node:http');
2498
+ const scriptPath = path.join(path.dirname(new URL(import.meta.url).pathname), 'detect-antipatterns-browser.js');
2499
+
2500
+ let browserScript;
2501
+ try {
2502
+ browserScript = fs.readFileSync(scriptPath, 'utf-8');
2503
+ } catch {
2504
+ process.stderr.write('Error: Browser script not found. Run `npm run build:browser` first.\n');
2505
+ process.exit(1);
2506
+ }
2507
+
2508
+ const port = requestedPort || await findOpenPort();
2509
+
2510
+ const shutdown = () => {
2511
+ try { fs.unlinkSync(LIVE_PID_FILE); } catch { /* ignore */ }
2512
+ server.close();
2513
+ process.exit(0);
2514
+ };
2515
+
2516
+ const server = http.default.createServer((req, res) => {
2517
+ // CORS headers for cross-origin injection
2518
+ res.setHeader('Access-Control-Allow-Origin', '*');
2519
+ res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
2520
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
2521
+
2522
+ if (req.url === '/detect.js' || req.url === '/') {
2523
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
2524
+ res.end(browserScript);
2525
+ } else if (req.url === '/health') {
2526
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2527
+ res.end(JSON.stringify({ status: 'ok', port }));
2528
+ } else if (req.url === '/stop') {
2529
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
2530
+ res.end('stopping');
2531
+ shutdown();
2532
+ } else {
2533
+ res.writeHead(404);
2534
+ res.end('Not found');
2535
+ }
2536
+ });
2537
+
2538
+ server.listen(port, '127.0.0.1', () => {
2539
+ // Write PID file so `live stop` can find us
2540
+ fs.writeFileSync(LIVE_PID_FILE, JSON.stringify({ pid: process.pid, port }));
2541
+
2542
+ const url = `http://localhost:${port}`;
2543
+ console.log(`Impeccable live detection server running on ${url}\n`);
2544
+ console.log(`Inject into any page:`);
2545
+ console.log(` const s = document.createElement('script');`);
2546
+ console.log(` s.src = '${url}/detect.js';`);
2547
+ console.log(` document.head.appendChild(s);\n`);
2548
+ console.log(`Stop: npx impeccable live stop`);
2549
+ });
2550
+
2551
+ process.on('SIGINT', shutdown);
2552
+ process.on('SIGTERM', shutdown);
2553
+ }
2554
+
2108
2555
  // ---------------------------------------------------------------------------
2109
2556
  // Entry point
2110
2557
  // ---------------------------------------------------------------------------
@@ -2125,7 +2572,11 @@ export {
2125
2572
  checkElementBorders, checkElementMotion, checkElementGlow, checkPageTypography, checkPageLayout, isNeutralColor, isFullPage,
2126
2573
  detectHtml, detectUrl, detectText,
2127
2574
  walkDir, formatFindings, SCANNABLE_EXTENSIONS, SKIP_DIRS,
2575
+ extractStyleBlocks, extractCSSinJS,
2576
+ buildImportGraph, resolveImport,
2577
+ detectFrameworkConfig, isPortListening, FRAMEWORK_CONFIGS,
2128
2578
  main as detectCli,
2579
+ liveCli,
2129
2580
  };
2130
2581
 
2131
2582
  // @browser-strip-end