mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff94918ddc | ||
|
|
894b95b988 | ||
|
|
f4f16e3802 | ||
|
|
5a7e2837d2 | ||
|
|
f2f9958b3d | ||
|
|
1e36c86315 | ||
|
|
8b326fc81e |
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -9,3 +9,7 @@ The `skill/reference/ios.md` and `skill/reference/android.md` platform reference
|
||||
**Original work:** https://github.com/ehmo/platform-design-skills
|
||||
**Original license:** MIT
|
||||
**Author:** ehmo
|
||||
|
||||
## Static HTML parser bundle
|
||||
|
||||
`cli/engine/vendor/static-html-parsers.mjs` is a generated bundle of the parser packages the static-HTML detector needs at runtime. Skill and plugin installs copy that file with the detector; they do not install these packages from npm. Complete copyright and license texts for every package included in the bundle ship beside it in `cli/engine/vendor/static-html-parsers.LICENSES.txt`.
|
||||
|
||||
@@ -427,7 +427,7 @@ npx impeccable ignores add-value overused-font Inter --reason "Brand font"
|
||||
|
||||
The detector catches 61 deterministic issues across AI slop (side-tab borders, purple gradients, bounce easing, dark glows) and general design quality (line length, cramped padding, small touch targets, skipped headings, and more).
|
||||
|
||||
Human-readable findings are diagnostics written to stderr, so redirect them with `2> findings.txt`. Use `--json` for machine-readable results on stdout. URL scans inspect the rendered DOM, computed layout, and accessible linked stylesheets; browser security still prevents reading cross-origin CSS without CORS. A clean detector run is evidence, not proof of visual or accessibility quality: it does not replace inspecting the rendered experience across relevant viewports.
|
||||
Human-readable findings are diagnostics written to stderr, so redirect them with `2> findings.txt`. Use `--json` for machine-readable results on stdout. Exit `0` means the scan completed without primary findings, exit `2` means it completed with primary findings, and exit `1` means at least one requested target could not be scanned; operational failure takes precedence for a partial multi-target scan. URL scans inspect the rendered DOM, computed layout, and accessible linked stylesheets; browser security still prevents reading cross-origin CSS without CORS. A clean detector run is evidence, not proof of visual or accessibility quality: it does not replace inspecting the rendered experience across relevant viewports.
|
||||
|
||||
By default, `detect` respects the same `.impeccable/config.json` and `.impeccable/config.local.json` detector config as the design hook: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. Hook lifecycle settings such as `hook.enabled` only affect automatic hook execution.
|
||||
|
||||
|
||||
+5
-2
@@ -60,8 +60,11 @@ npx impeccable detect --fast src/
|
||||
|
||||
## Exit Codes
|
||||
|
||||
- `0`: no issues found
|
||||
- `2`: anti-patterns detected
|
||||
- `0`: scan completed with no primary findings (advisories may still be listed)
|
||||
- `1`: at least one requested target could not be scanned
|
||||
- `2`: scan completed with primary findings
|
||||
|
||||
Operational failure takes precedence when a multi-target scan is partial. In JSON mode, stdout remains a findings array and diagnostics are written to stderr.
|
||||
|
||||
## Options
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@babel/parser": "^8.0.4",
|
||||
"ai": "^7.0.14",
|
||||
"archiver": "^8.0.0",
|
||||
"esbuild": "0.28.1",
|
||||
"playwright": "^1.59.1",
|
||||
"svelte": "^5",
|
||||
"zod": "^4.3.6",
|
||||
@@ -73,6 +74,58 @@
|
||||
|
||||
"@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.1", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.28.1", "", { "os": "android", "cpu": "arm" }, "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ=="],
|
||||
|
||||
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.1", "", { "os": "android", "cpu": "arm64" }, "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg=="],
|
||||
|
||||
"@esbuild/android-x64": ["@esbuild/android-x64@0.28.1", "", { "os": "android", "cpu": "x64" }, "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng=="],
|
||||
|
||||
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q=="],
|
||||
|
||||
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ=="],
|
||||
|
||||
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw=="],
|
||||
|
||||
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ=="],
|
||||
|
||||
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.1", "", { "os": "linux", "cpu": "arm" }, "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ=="],
|
||||
|
||||
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g=="],
|
||||
|
||||
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.1", "", { "os": "linux", "cpu": "ia32" }, "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w=="],
|
||||
|
||||
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.1", "", { "os": "linux", "cpu": "none" }, "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg=="],
|
||||
|
||||
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.1", "", { "os": "linux", "cpu": "none" }, "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ=="],
|
||||
|
||||
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ=="],
|
||||
|
||||
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.1", "", { "os": "linux", "cpu": "none" }, "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ=="],
|
||||
|
||||
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag=="],
|
||||
|
||||
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.1", "", { "os": "linux", "cpu": "x64" }, "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA=="],
|
||||
|
||||
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.1", "", { "os": "none", "cpu": "arm64" }, "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw=="],
|
||||
|
||||
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.1", "", { "os": "none", "cpu": "x64" }, "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg=="],
|
||||
|
||||
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.1", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q=="],
|
||||
|
||||
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw=="],
|
||||
|
||||
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.1", "", { "os": "none", "cpu": "arm64" }, "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg=="],
|
||||
|
||||
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.1", "", { "os": "sunos", "cpu": "x64" }, "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ=="],
|
||||
|
||||
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA=="],
|
||||
|
||||
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg=="],
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.1", "", { "os": "win32", "cpu": "x64" }, "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A=="],
|
||||
|
||||
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
|
||||
|
||||
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
|
||||
@@ -225,6 +278,8 @@
|
||||
|
||||
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
|
||||
|
||||
"esbuild": ["esbuild@0.28.1", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw=="],
|
||||
|
||||
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
|
||||
|
||||
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
|
||||
|
||||
+70
-21
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -291,7 +297,11 @@ async function detectCli() {
|
||||
// apply by default. `--no-config` (raw scan) and the dedicated
|
||||
// `--no-inline-ignores` both turn them off.
|
||||
const inlineIgnoresEnabled = configEnabled && !args.includes('--no-inline-ignores');
|
||||
const baseScanOptions = { inlineIgnores: inlineIgnoresEnabled };
|
||||
let hadOperationalFailure = false;
|
||||
const baseScanOptions = {
|
||||
inlineIgnores: inlineIgnoresEnabled,
|
||||
onOperationalFailure: () => { hadOperationalFailure = true; },
|
||||
};
|
||||
if (viewport) baseScanOptions.viewport = viewport;
|
||||
// DESIGN.md must resolve from EACH scan target's own project root, not from
|
||||
// process.cwd(): scanning project B's files from inside project A applied A's
|
||||
@@ -309,6 +319,10 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +333,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +361,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +404,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +420,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +435,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +478,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +492,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -112,12 +112,8 @@ async function detectHtml(filePath, options = {}) {
|
||||
ruleId: 'import-static-parser',
|
||||
target: filePath,
|
||||
}, async () => {
|
||||
const [htmlparser2, cssSelect, csstree, domutils] = await Promise.all([
|
||||
import('htmlparser2'),
|
||||
import('css-select'),
|
||||
import('css-tree'),
|
||||
import('domutils'),
|
||||
]);
|
||||
const parsers = await import(new URL('../../vendor/static-html-parsers.mjs', import.meta.url).href);
|
||||
const { htmlparser2, cssSelect, csstree, domutils } = parsers;
|
||||
return {
|
||||
parseDocument: htmlparser2.parseDocument,
|
||||
selectAll: cssSelect.selectAll,
|
||||
@@ -127,21 +123,26 @@ async function detectHtml(filePath, options = {}) {
|
||||
domutils,
|
||||
};
|
||||
});
|
||||
} catch (err) {
|
||||
if (!globalThis.__impeccableStaticHtmlWarned) {
|
||||
globalThis.__impeccableStaticHtmlWarned = true;
|
||||
|
||||
process.stderr.write(
|
||||
'impeccable detect: DEGRADED - HTML parser modules unavailable ' +
|
||||
'(htmlparser2, css-select, css-tree, domutils).\n' +
|
||||
'Falling back to regex matching. Custom properties, selector matching and computed ' +
|
||||
'contrast are NOT evaluated; findings are an undercount, not a clean bill of health.\n'
|
||||
);
|
||||
} catch {
|
||||
if (!globalThis.__impeccableStaticHtmlWarned) {
|
||||
globalThis.__impeccableStaticHtmlWarned = true;
|
||||
process.stderr.write(
|
||||
'impeccable detect: DEGRADED - HTML parser modules unavailable ' +
|
||||
'(htmlparser2, css-select, css-tree, domutils).\n' +
|
||||
'Falling back to regex matching. Custom properties, selector matching and computed ' +
|
||||
'contrast are NOT evaluated; findings are an undercount, not a clean bill of health.\n',
|
||||
);
|
||||
}
|
||||
if (typeof options.onOperationalFailure === 'function') {
|
||||
options.onOperationalFailure({
|
||||
engine: 'static-html',
|
||||
reason: 'parser-bundle-unavailable',
|
||||
target: filePath,
|
||||
});
|
||||
}
|
||||
return detectText(html, filePath, options);
|
||||
}
|
||||
|
||||
return detectText(html, filePath, options);
|
||||
}
|
||||
|
||||
const resolvedPath = path.resolve(filePath);
|
||||
const fileDir = path.dirname(resolvedPath);
|
||||
const root = profileStep(profile, {
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
Static HTML parser bundle: third-party licenses
|
||||
Generated by scripts/build-static-html-parsers.js. Do not edit.
|
||||
|
||||
Package: boolbase@2.0.0
|
||||
License: ISC
|
||||
|
||||
Copyright (c) 2014-2015, Felix Boehm <me@feedic.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: css-select@7.0.0
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: css-tree@3.2.1
|
||||
License: MIT
|
||||
|
||||
Copyright (C) 2016-2026 by Roman Dvornov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: css-what@8.0.0
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: dom-serializer@3.1.1
|
||||
License: MIT
|
||||
|
||||
Copyright © 2022 The Cheerio contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: domelementtype@3.0.0
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: domhandler@6.0.1
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: domutils@4.0.2
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: entities@8.0.0
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: htmlparser2@12.0.0
|
||||
License: MIT
|
||||
|
||||
Copyright 2010, 2011, Chris Winberry <chris@winberry.net>. All rights reserved.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to
|
||||
deal in the Software without restriction, including without limitation the
|
||||
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
IN THE SOFTWARE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: nth-check@3.0.1
|
||||
License: BSD-2-Clause
|
||||
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
------------------------------------------------------------------------
|
||||
|
||||
Package: source-map-js@1.2.1
|
||||
License: BSD-3-Clause
|
||||
|
||||
Copyright (c) 2009-2011, Mozilla Foundation and contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the names of the Mozilla Foundation nor the names of project
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+19
File diff suppressed because one or more lines are too long
+4
-2
@@ -42,9 +42,10 @@
|
||||
"scripts": {
|
||||
"build:skills": "bun run scripts/build.js --skip-root-sync",
|
||||
"build:skills:release": "bun run scripts/build.js",
|
||||
"build": "bun run build:skills && mkdir -p build/_data && rm -rf build/_data/dist && cp -R dist build/_data/dist",
|
||||
"build:release": "bun run build:skills:release && mkdir -p build/_data && rm -rf build/_data/dist && cp -R dist build/_data/dist",
|
||||
"build": "node scripts/build-static-html-parsers.js --check && bun run build:skills && mkdir -p build/_data && rm -rf build/_data/dist && cp -R dist build/_data/dist",
|
||||
"build:release": "node scripts/build-static-html-parsers.js --check && bun run build:skills:release && mkdir -p build/_data && rm -rf build/_data/dist && cp -R dist build/_data/dist",
|
||||
"build:browser": "node scripts/build-browser-detector.js",
|
||||
"build:static-html-parsers": "node scripts/build-static-html-parsers.js",
|
||||
"build:extension": "node scripts/build-extension.js",
|
||||
"clean": "rm -rf dist build",
|
||||
"rebuild": "bun run clean && bun run build",
|
||||
@@ -93,6 +94,7 @@
|
||||
"@babel/parser": "^8.0.4",
|
||||
"ai": "^7.0.14",
|
||||
"archiver": "^8.0.0",
|
||||
"esbuild": "0.28.1",
|
||||
"playwright": "^1.59.1",
|
||||
"svelte": "^5",
|
||||
"zod": "^4.3.6"
|
||||
|
||||
@@ -285,10 +285,31 @@ function resolveEnvContextDir(cwd) {
|
||||
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
|
||||
}
|
||||
|
||||
function resolveTargetPath(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
if (fs.existsSync(abs)) return abs;
|
||||
return findUniqueBareTarget(cwd, targetPath) || abs;
|
||||
}
|
||||
|
||||
function findUniqueBareTarget(cwd, targetPath) {
|
||||
const absCwd = path.resolve(cwd);
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(absCwd, targetPath);
|
||||
const rel = path.relative(absCwd, abs);
|
||||
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
||||
const segments = rel.split(path.sep).filter(Boolean);
|
||||
if (segments.length !== 1) return null;
|
||||
const name = segments[0];
|
||||
const repoRoot = findMonorepoRoot(absCwd);
|
||||
if (!repoRoot) return null;
|
||||
const matches = discoverTargetCandidates(repoRoot).filter((candidate) => candidate.name === name);
|
||||
if (matches.length !== 1) return null;
|
||||
return path.resolve(repoRoot, matches[0].path);
|
||||
}
|
||||
|
||||
function resolveTargetDir(cwd, options = {}) {
|
||||
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
|
||||
if (!targetPath || !String(targetPath).trim()) return cwd;
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
const abs = resolveTargetPath(cwd, targetPath);
|
||||
try {
|
||||
const stat = fs.statSync(abs);
|
||||
return stat.isDirectory() ? abs : path.dirname(abs);
|
||||
@@ -1188,13 +1209,19 @@ async function cli() {
|
||||
throw err;
|
||||
}
|
||||
const targetProvided = hasTargetOption(cliOptions);
|
||||
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
|
||||
const resolvedTargetPath = targetProvided
|
||||
? resolveTargetPath(process.cwd(), cliOptions.targetPath)
|
||||
: null;
|
||||
const targetExists = targetProvided ? fs.existsSync(resolvedTargetPath) : null;
|
||||
const selection = resolveTargetSelection(process.cwd(), cliOptions);
|
||||
if (selection) {
|
||||
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
|
||||
process.exit(0);
|
||||
}
|
||||
const ctx = loadContext(process.cwd(), cliOptions);
|
||||
const ctx = loadContext(
|
||||
process.cwd(),
|
||||
resolvedTargetPath ? { targetPath: resolvedTargetPath } : cliOptions,
|
||||
);
|
||||
const updateDirective = await computeUpdateDirective();
|
||||
|
||||
if (!ctx.hasProduct) {
|
||||
@@ -1308,11 +1335,6 @@ function hasTargetOption(options) {
|
||||
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
|
||||
}
|
||||
|
||||
function pathExistsForTarget(cwd, targetPath) {
|
||||
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
|
||||
return fs.existsSync(abs);
|
||||
}
|
||||
|
||||
const HOOK_MANIFESTS_BY_PROVIDER = Object.freeze({
|
||||
'claude-code': ['.claude/settings.local.json', '.claude/settings.json'],
|
||||
codex: ['.codex/hooks.json'],
|
||||
|
||||
@@ -189,6 +189,12 @@ Output streams:
|
||||
Human-readable findings go to stderr so stdout stays available for structured
|
||||
output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.
|
||||
|
||||
Exit status:
|
||||
0 Scan completed with no primary findings (advisories may still be listed)
|
||||
1 At least one requested target could not be scanned
|
||||
2 Scan completed with primary findings
|
||||
Operational failure takes precedence when a multi-target scan is partial.
|
||||
|
||||
Project config:
|
||||
Respects .impeccable/config.json and .impeccable/config.local.json detector
|
||||
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
|
||||
@@ -309,6 +315,11 @@ async function detectCli() {
|
||||
if (helpMode) { printUsage(); process.exit(0); }
|
||||
|
||||
let allFindings = [];
|
||||
let hadOperationalFailure = false;
|
||||
const reportLocalScanFailure = (target, error) => {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: cannot scan ${target}: ${error.message}\n`);
|
||||
};
|
||||
|
||||
if (!process.stdin.isTTY && targets.length === 0) {
|
||||
allFindings = await handleStdin(scanOptionsFor);
|
||||
@@ -319,11 +330,22 @@ async function detectCli() {
|
||||
// browser-grade scan of a local artifact can pass file:///abs/path.html
|
||||
// instead of the bare path (which stays on the static engine).
|
||||
const urlTargetCount = paths.filter(target => URL_TARGET_RE.test(target)).length;
|
||||
const browserDetector = urlTargetCount > 1 ? await createBrowserDetector() : null;
|
||||
let browserDetector = null;
|
||||
let browserSetupFailed = false;
|
||||
if (urlTargetCount > 1) {
|
||||
try {
|
||||
browserDetector = await createBrowserDetector();
|
||||
} catch (e) {
|
||||
browserSetupFailed = true;
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const target of paths) {
|
||||
if (URL_TARGET_RE.test(target)) {
|
||||
if (browserSetupFailed) continue;
|
||||
// A file:// URL points at a local artifact, so its design system
|
||||
// resolves from that file's project. A remote http(s) URL has no
|
||||
// local project — it gets base options (no design system), never
|
||||
@@ -336,14 +358,21 @@ async function detectCli() {
|
||||
? (url) => browserDetector.detectUrl(url, urlOptions)
|
||||
: (url) => detectUrl(url, urlOptions);
|
||||
allFindings.push(...await scanner(target));
|
||||
} catch (e) { process.stderr.write(`Error: ${e.message}\n`); }
|
||||
} catch (e) {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Error: ${e.message}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = path.resolve(target);
|
||||
let stat;
|
||||
try { stat = fs.statSync(resolved); }
|
||||
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
|
||||
catch {
|
||||
hadOperationalFailure = true;
|
||||
process.stderr.write(`Warning: cannot access ${target}\n`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
|
||||
@@ -372,7 +401,7 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
|
||||
const files = walkDir(resolved)
|
||||
const files = walkDir(resolved, reportLocalScanFailure)
|
||||
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
|
||||
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
|
||||
|
||||
@@ -388,7 +417,11 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
// Build import graph for multi-file awareness
|
||||
const graph = buildImportGraph(files);
|
||||
const unreadableFiles = new Set();
|
||||
const graph = buildImportGraph(files, (file, error) => {
|
||||
unreadableFiles.add(file);
|
||||
reportLocalScanFailure(file, error);
|
||||
});
|
||||
// Build reverse map: file -> set of files that import it
|
||||
const importedByMap = new Map();
|
||||
for (const [importer, imports] of graph) {
|
||||
@@ -399,24 +432,33 @@ async function detectCli() {
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
if (unreadableFiles.has(file)) continue;
|
||||
try {
|
||||
// Each file resolves its own project design system (cached by root),
|
||||
// so a scan spanning sibling projects applies the right rules per file.
|
||||
const fileOptions = scanOptionsFor(file);
|
||||
const fileFindings = await detectLocalFile(file, fileOptions);
|
||||
// Annotate findings with import context
|
||||
const importers = importedByMap.get(file);
|
||||
if (importers && importers.size > 0) {
|
||||
const importerNames = [...importers].map(f => path.basename(f));
|
||||
for (const f of fileFindings) {
|
||||
f.importedBy = importerNames;
|
||||
}
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(file, error);
|
||||
}
|
||||
allFindings.push(...fileFindings);
|
||||
}
|
||||
} else if (stat.isFile()) {
|
||||
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
try {
|
||||
const fileOptions = scanOptionsFor(resolved);
|
||||
allFindings.push(...await detectLocalFile(resolved, fileOptions));
|
||||
} catch (error) {
|
||||
reportLocalScanFailure(target, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -433,6 +475,10 @@ async function detectCli() {
|
||||
// advisory-only scan still prints its notes but exits 0 (a clean pass), so
|
||||
// advisory rules never break CI or block automation.
|
||||
const { primary, advisory } = partitionAdvisory(allFindings);
|
||||
// Exit 1 means at least one requested scan could not complete. It takes
|
||||
// precedence over exit 2 because findings from the remaining targets do not
|
||||
// turn a partial scan into a complete one.
|
||||
const exitCode = hadOperationalFailure ? 1 : (primary.length > 0 ? 2 : 0);
|
||||
|
||||
if (allFindings.length > 0) {
|
||||
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
|
||||
@@ -443,10 +489,10 @@ async function detectCli() {
|
||||
}
|
||||
}
|
||||
else process.stderr.write(formatFindings(allFindings, false) + '\n');
|
||||
process.exit(primary.length > 0 ? 2 : 0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
if (jsonMode) process.stdout.write('[]\n');
|
||||
process.exit(0);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
export { formatFindings, handleStdin, confirm, printUsage, detectCli };
|
||||
|
||||
@@ -46,15 +46,20 @@ const IMPORT_SPECIFIER_PATTERNS = [
|
||||
/@(?:use|forward)\s+['"]([^'"]+)['"]/g,
|
||||
];
|
||||
|
||||
function walkDir(dir) {
|
||||
function walkDir(dir, onReadError = null) {
|
||||
const files = [];
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return files; }
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (onReadError) onReadError(dir, error);
|
||||
return files;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
if (entry.isDirectory() && entry.name.startsWith('.') && !HIDDEN_SOURCE_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkDir(full));
|
||||
if (entry.isDirectory()) files.push(...walkDir(full, onReadError));
|
||||
else if (hasScannableExtension(entry.name)) files.push(full);
|
||||
}
|
||||
return files;
|
||||
@@ -81,12 +86,19 @@ function resolveImport(specifier, fromDir, fileSet) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildImportGraph(files) {
|
||||
function buildImportGraph(files, onReadError = null) {
|
||||
const fileSet = new Set(files);
|
||||
const graph = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf-8');
|
||||
let content;
|
||||
try {
|
||||
content = fs.readFileSync(file, 'utf-8');
|
||||
} catch (error) {
|
||||
if (!onReadError) throw error;
|
||||
onReadError(file, error);
|
||||
continue;
|
||||
}
|
||||
const dir = path.dirname(file);
|
||||
const imports = new Set();
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Generates cli/engine/vendor/static-html-parsers.mjs
|
||||
* by bundling htmlparser2, css-select, css-tree, and domutils for skill/plugin installs.
|
||||
*
|
||||
* Run: node scripts/build-static-html-parsers.js
|
||||
* Check: node scripts/build-static-html-parsers.js --check
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { build } from 'esbuild';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
|
||||
const ENTRY = path.join(__dirname, 'lib/static-html-parsers.entry.mjs');
|
||||
const OUT_DIR = path.join(ROOT, 'cli/engine/vendor');
|
||||
const BUNDLE_NAME = 'static-html-parsers.mjs';
|
||||
const LICENSES_NAME = 'static-html-parsers.LICENSES.txt';
|
||||
const MAX_BUNDLE_BYTES = 256 * 1024;
|
||||
const HEADER = `/**
|
||||
* GENERATED -- do not edit. Source: scripts/lib/static-html-parsers.entry.mjs
|
||||
* Rebuild: node scripts/build-static-html-parsers.js
|
||||
*
|
||||
* Bundles htmlparser2, css-select, css-tree, and domutils for skill/plugin installs.
|
||||
* Third-party licenses: see static-html-parsers.LICENSES.txt.
|
||||
*/
|
||||
`;
|
||||
|
||||
function packageRoots(inputs) {
|
||||
const roots = new Map();
|
||||
for (const input of Object.keys(inputs)) {
|
||||
const segments = input.replaceAll('\\', '/').split('/');
|
||||
const marker = segments.lastIndexOf('node_modules');
|
||||
if (marker < 0 || marker + 1 >= segments.length) continue;
|
||||
|
||||
const nameParts = segments[marker + 1].startsWith('@')
|
||||
? segments.slice(marker + 1, marker + 3)
|
||||
: segments.slice(marker + 1, marker + 2);
|
||||
const packageName = nameParts.join('/');
|
||||
const packageRoot = path.resolve(ROOT, ...segments.slice(0, marker + 1), ...nameParts);
|
||||
roots.set(packageRoot, packageName);
|
||||
}
|
||||
return [...roots]
|
||||
.map(([packageRoot, packageName]) => [packageName, packageRoot])
|
||||
.sort(([aName, aRoot], [bName, bRoot]) =>
|
||||
aName.localeCompare(bName) || aRoot.localeCompare(bRoot));
|
||||
}
|
||||
|
||||
function buildLicenseFile(inputs) {
|
||||
const sections = packageRoots(inputs).map(([packageName, packageRoot]) => {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
|
||||
const licenseFile = fs.readdirSync(packageRoot)
|
||||
.filter((name) => /^licen[cs]e(?:\.|$)/i.test(name))
|
||||
.sort()[0];
|
||||
if (!licenseFile) throw new Error(`No license file found for bundled package ${packageName}`);
|
||||
|
||||
const licenseText = fs.readFileSync(path.join(packageRoot, licenseFile), 'utf8')
|
||||
.replaceAll('\r\n', '\n')
|
||||
.replace(/[ \t]+$/gm, '')
|
||||
.trim();
|
||||
return [
|
||||
`Package: ${packageName}@${manifest.version}`,
|
||||
`License: ${manifest.license}`,
|
||||
'',
|
||||
licenseText,
|
||||
].join('\n');
|
||||
});
|
||||
|
||||
return [
|
||||
'Static HTML parser bundle: third-party licenses',
|
||||
'Generated by scripts/build-static-html-parsers.js. Do not edit.',
|
||||
'',
|
||||
sections.join('\n\n------------------------------------------------------------------------\n\n'),
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function generate() {
|
||||
const result = await build({
|
||||
absWorkingDir: ROOT,
|
||||
bundle: true,
|
||||
entryPoints: [ENTRY],
|
||||
format: 'esm',
|
||||
legalComments: 'none',
|
||||
metafile: true,
|
||||
minify: true,
|
||||
platform: 'node',
|
||||
target: 'node22',
|
||||
write: false,
|
||||
});
|
||||
const bundle = HEADER + result.outputFiles[0].text;
|
||||
if (Buffer.byteLength(bundle) > MAX_BUNDLE_BYTES) {
|
||||
throw new Error(
|
||||
`${BUNDLE_NAME} is ${(Buffer.byteLength(bundle) / 1024).toFixed(1)} KB; ` +
|
||||
`the ${MAX_BUNDLE_BYTES / 1024} KB limit prevents provider-copy bloat`,
|
||||
);
|
||||
}
|
||||
return new Map([
|
||||
[BUNDLE_NAME, bundle],
|
||||
[LICENSES_NAME, buildLicenseFile(result.metafile.inputs)],
|
||||
]);
|
||||
}
|
||||
|
||||
function checkDirectoryArg() {
|
||||
const index = process.argv.indexOf('--check-dir');
|
||||
if (index < 0) return OUT_DIR;
|
||||
if (!process.argv.includes('--check') || !process.argv[index + 1]) {
|
||||
throw new Error('--check-dir requires --check and a directory path');
|
||||
}
|
||||
return path.resolve(process.argv[index + 1]);
|
||||
}
|
||||
|
||||
const generated = await generate();
|
||||
if (process.argv.includes('--check')) {
|
||||
const checkDir = checkDirectoryArg();
|
||||
for (const [name, fresh] of generated) {
|
||||
const committedPath = path.join(checkDir, name);
|
||||
const committed = fs.existsSync(committedPath) ? fs.readFileSync(committedPath, 'utf8') : null;
|
||||
if (fresh !== committed) {
|
||||
process.stderr.write(
|
||||
`${path.relative(ROOT, committedPath)} is stale. ` +
|
||||
'Run: node scripts/build-static-html-parsers.js\n',
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||||
for (const [name, contents] of generated) {
|
||||
const output = path.join(OUT_DIR, name);
|
||||
fs.writeFileSync(output, contents);
|
||||
console.log(`Generated ${path.relative(ROOT, output)} (${(Buffer.byteLength(contents) / 1024).toFixed(1)} KB)`);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * as htmlparser2 from 'htmlparser2';
|
||||
export * as cssSelect from 'css-select';
|
||||
export * as domutils from 'domutils';
|
||||
import parse from 'css-tree/parser';
|
||||
import generate from 'css-tree/generator';
|
||||
export const csstree = { parse, generate };
|
||||
@@ -25,7 +25,7 @@ export const SUITES = {
|
||||
description: 'Build, provider transforms, CLI helpers, context, and storage unit tests.',
|
||||
triggers: [
|
||||
...COMMON_INFRA_PATTERNS,
|
||||
/^scripts\/(?!benchmark-detector|build-browser-detector|build-extension)/,
|
||||
/^scripts\/(?!benchmark-detector|build-browser-detector|build-static-html-parsers|build-extension|lib\/static-html-parsers\.entry)/,
|
||||
/^skill\/(SKILL\.src\.md|agents\/|reference\/|scripts\/(cleanup-deprecated|comp-diff|comp-spec|build-phase|font-match|data\/font-index|concept-seed|generate-image|context|context-signals|critique-storage|design-parser|doctor|hook|impeccable-paths|is-generated|lib\/(artifact-schema|png|raster|image-metrics|font-fingerprint|font-index|hero-checks|composition-catalog|concept-catalog|provider|staleness|staleness-deep|staleness-notice|surface-briefs|target-slug|template-extensions)|pin|surface-brief))/,
|
||||
/^README(\.npm)?\.md$/,
|
||||
/^cli\/bin\//,
|
||||
@@ -95,7 +95,8 @@ export const SUITES = {
|
||||
...COMMON_INFRA_PATTERNS,
|
||||
/^cli\/engine\//,
|
||||
/^extension\/(background|content|detector|devtools|popup|manifest\.json)/,
|
||||
/^scripts\/(benchmark-detector|build-browser-detector|build-extension)\.js$/,
|
||||
/^scripts\/(benchmark-detector|build-browser-detector|build-static-html-parsers|build-extension)\.js$/,
|
||||
/^scripts\/lib\/static-html-parsers\.entry\.mjs$/,
|
||||
/^site\/(pages\/detector|public\/antipattern|data\/anti-patterns-catalog\.js)/,
|
||||
/^tests\/fixtures\/antipatterns/,
|
||||
],
|
||||
@@ -119,6 +120,7 @@ export const SUITES = {
|
||||
'tests/detect-cli-design-contamination.test.mjs',
|
||||
'tests/detect-cli-design-monorepo.test.mjs',
|
||||
'tests/detect-cli-stdin-dispatch.test.mjs',
|
||||
'tests/detect-static-html-skill-install.test.mjs',
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -2648,6 +2648,21 @@ describe('walkDir', () => {
|
||||
expect(walkDir('/nonexistent/path/12345')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('reports directory traversal errors to an optional handler', () => {
|
||||
const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-walk-error-'));
|
||||
try {
|
||||
const missing = path.join(parent, 'missing');
|
||||
const errors = [];
|
||||
|
||||
expect(walkDir(missing, (dir, error) => {
|
||||
errors.push({ dir, code: error.code });
|
||||
})).toHaveLength(0);
|
||||
expect(errors).toEqual([{ dir: missing, code: 'ENOENT' }]);
|
||||
} finally {
|
||||
fs.rmSync(parent, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// Issue #303: when impeccable (or any agent tool) is installed into a
|
||||
// project's .claude/.cursor/etc. tree, a root scan descended into the
|
||||
// vendored skill code and reported the detector's own example strings as
|
||||
@@ -3684,6 +3699,23 @@ describe('buildImportGraph', () => {
|
||||
expect(imp).toContain(MF);
|
||||
}
|
||||
});
|
||||
|
||||
test('reports unreadable files and continues building the graph', async () => {
|
||||
await withStaticFixture({
|
||||
'readable.css': '@import "./missing.css";\n',
|
||||
}, ({ dir }) => {
|
||||
const readable = path.join(dir, 'readable.css');
|
||||
const missing = path.join(dir, 'missing.css');
|
||||
const errors = [];
|
||||
const graph = buildImportGraph([missing, readable], (file, error) => {
|
||||
errors.push({ file, code: error.code });
|
||||
});
|
||||
|
||||
expect(errors).toEqual([{ file: missing, code: 'ENOENT' }]);
|
||||
expect(graph.get(readable)).toEqual(new Set([missing]));
|
||||
expect(graph.has(missing)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveImport', () => {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { after, describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const engineDir = path.join(root, 'cli', 'engine');
|
||||
const skillDetect = path.join(root, 'skill', 'scripts', 'detect.mjs');
|
||||
const configDep = path.join(root, 'cli', 'lib', 'impeccable-config.mjs');
|
||||
|
||||
const CSS = ':root{--grad:linear-gradient(90deg,#7C3AED,#EC4899)}\n.hero h1{background:var(--grad);-webkit-background-clip:text;background-clip:text;color:transparent}';
|
||||
const HTML = '<html><head><link rel=stylesheet href=s.css></head><body><div class=hero><h1>Hi</h1></div></body></html>';
|
||||
|
||||
function copyDir(src, dest) {
|
||||
fs.mkdirSync(dest, { recursive: true });
|
||||
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
||||
const srcPath = path.join(src, entry.name);
|
||||
const destPath = path.join(dest, entry.name);
|
||||
if (entry.isDirectory()) copyDir(srcPath, destPath);
|
||||
else fs.copyFileSync(srcPath, destPath);
|
||||
}
|
||||
}
|
||||
|
||||
function copyDetectorExternalDeps(scriptsDir) {
|
||||
fs.mkdirSync(path.join(scriptsDir, 'lib'), { recursive: true });
|
||||
fs.copyFileSync(configDep, path.join(scriptsDir, 'lib', 'impeccable-config.mjs'));
|
||||
}
|
||||
|
||||
function writeFixture(dir) {
|
||||
fs.writeFileSync(path.join(dir, 's.css'), CSS);
|
||||
fs.writeFileSync(path.join(dir, 'p.html'), HTML);
|
||||
}
|
||||
|
||||
function runDetect(cwd, detectRel, htmlRel = 'p.html') {
|
||||
const detectPath = path.join(cwd, detectRel);
|
||||
return spawnSync(
|
||||
process.execPath,
|
||||
[detectPath, '--json', '--no-config', '--no-design-system', htmlRel],
|
||||
{ cwd, encoding: 'utf8' },
|
||||
);
|
||||
}
|
||||
|
||||
function assertFullEngine(result) {
|
||||
assert.doesNotMatch(result.stderr, /DEGRADED/);
|
||||
const findings = JSON.parse(result.stdout);
|
||||
assert.ok(findings.some((item) => item.antipattern === 'gradient-text'));
|
||||
assert.equal(result.status, 2);
|
||||
}
|
||||
|
||||
function assertDegraded(result) {
|
||||
assert.match(result.stderr, /DEGRADED/);
|
||||
assert.equal(result.status, 1);
|
||||
JSON.parse(result.stdout);
|
||||
}
|
||||
|
||||
const tempDirs = [];
|
||||
|
||||
after(() => {
|
||||
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('static HTML parsers in skill/plugin installs', () => {
|
||||
it('resolves parsers from a skill-shaped scripts/ tree with no node_modules', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-skill-detect-'));
|
||||
tempDirs.push(tmp);
|
||||
fs.mkdirSync(path.join(tmp, 'scripts'), { recursive: true });
|
||||
fs.copyFileSync(skillDetect, path.join(tmp, 'scripts', 'detect.mjs'));
|
||||
copyDir(engineDir, path.join(tmp, 'scripts', 'detector'));
|
||||
copyDetectorExternalDeps(path.join(tmp, 'scripts'));
|
||||
writeFixture(tmp);
|
||||
|
||||
assertFullEngine(runDetect(tmp, path.join('scripts', 'detect.mjs')));
|
||||
});
|
||||
|
||||
it('resolves parsers from a plugin cache skills/impeccable/scripts/ tree', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-plugin-detect-'));
|
||||
tempDirs.push(tmp);
|
||||
const scriptsDir = path.join(tmp, 'skills', 'impeccable', 'scripts');
|
||||
fs.mkdirSync(scriptsDir, { recursive: true });
|
||||
fs.copyFileSync(skillDetect, path.join(scriptsDir, 'detect.mjs'));
|
||||
copyDir(engineDir, path.join(scriptsDir, 'detector'));
|
||||
copyDetectorExternalDeps(scriptsDir);
|
||||
writeFixture(tmp);
|
||||
|
||||
assertFullEngine(runDetect(tmp, path.join('skills', 'impeccable', 'scripts', 'detect.mjs')));
|
||||
});
|
||||
|
||||
it('exits 1 when the vendor bundle is missing', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-skill-degraded-'));
|
||||
tempDirs.push(tmp);
|
||||
fs.mkdirSync(path.join(tmp, 'scripts'), { recursive: true });
|
||||
fs.copyFileSync(skillDetect, path.join(tmp, 'scripts', 'detect.mjs'));
|
||||
copyDir(engineDir, path.join(tmp, 'scripts', 'detector'));
|
||||
copyDetectorExternalDeps(path.join(tmp, 'scripts'));
|
||||
fs.unlinkSync(path.join(tmp, 'scripts', 'detector', 'vendor', 'static-html-parsers.mjs'));
|
||||
writeFixture(tmp);
|
||||
|
||||
assertDegraded(runDetect(tmp, path.join('scripts', 'detect.mjs')));
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,14 @@
|
||||
import { describe, test, expect, afterEach } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { launchBrowser, detectUrl, splitScanUrl } from '../cli/engine/engines/browser/detect-url.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
// launchBrowser prefers the system-installed Chrome on Windows to dodge the
|
||||
// bundled-Chrome GPU crash-loop (issue #372), and keeps the pinned bundled
|
||||
// build everywhere else. The function takes the puppeteer module as a
|
||||
@@ -38,6 +45,50 @@ function makePuppeteer({ failChannel = false } = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function runWithoutPuppeteer(args, files = {}, { nodeArgs = [] } = {}) {
|
||||
const isolatedRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-no-puppeteer-'));
|
||||
try {
|
||||
const cliRoot = path.join(isolatedRoot, 'cli');
|
||||
fs.mkdirSync(cliRoot, { recursive: true });
|
||||
fs.cpSync(path.join(ROOT, 'cli', 'engine'), path.join(cliRoot, 'engine'), { recursive: true });
|
||||
fs.cpSync(path.join(ROOT, 'cli', 'lib'), path.join(cliRoot, 'lib'), { recursive: true });
|
||||
for (const [relativePath, contents] of Object.entries(files)) {
|
||||
const filePath = path.join(isolatedRoot, relativePath);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, contents);
|
||||
}
|
||||
return spawnSync(
|
||||
'node',
|
||||
[...nodeArgs, path.join(cliRoot, 'engine', 'detect-antipatterns.mjs'), '--json', ...args],
|
||||
{ cwd: isolatedRoot, encoding: 'utf8' },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(isolatedRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const DENY_FS_PRELOAD = `
|
||||
const fs = require('node:fs');
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const originalReaddirSync = fs.readdirSync;
|
||||
fs.readFileSync = function (file, ...args) {
|
||||
if (String(file).endsWith('unreadable.css')) {
|
||||
const error = new Error('simulated EACCES');
|
||||
error.code = 'EACCES';
|
||||
throw error;
|
||||
}
|
||||
return originalReadFileSync.call(this, file, ...args);
|
||||
};
|
||||
fs.readdirSync = function (dir, ...args) {
|
||||
if (String(dir).endsWith('unreadable-dir')) {
|
||||
const error = new Error('simulated directory EACCES');
|
||||
error.code = 'EACCES';
|
||||
throw error;
|
||||
}
|
||||
return originalReaddirSync.call(this, dir, ...args);
|
||||
};
|
||||
`;
|
||||
|
||||
describe('launchBrowser', () => {
|
||||
test('Windows: prefers system Chrome via channel:chrome', async () => {
|
||||
setPlatform('win32');
|
||||
@@ -81,6 +132,122 @@ describe('launchBrowser', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('detect CLI browser failures', () => {
|
||||
test('exits 1 with valid empty JSON when Puppeteer is unavailable', () => {
|
||||
const result = runWithoutPuppeteer(['https://example.com']);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('[]\n');
|
||||
expect(result.stderr).toContain('puppeteer is required for URL scanning');
|
||||
});
|
||||
|
||||
test('reports a shared multi-URL setup failure once and exits 1', () => {
|
||||
const result = runWithoutPuppeteer(['https://example.com', 'https://example.org']);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('[]\n');
|
||||
expect(result.stderr.match(/puppeteer is required for URL scanning/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('operational failure takes precedence over findings from another target', () => {
|
||||
const result = runWithoutPuppeteer(
|
||||
['https://example.com', 'page.css'],
|
||||
{ 'page.css': '.hero { animation: bounce 1s linear infinite; }\n' },
|
||||
);
|
||||
const findings = JSON.parse(result.stdout);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(findings.some(finding => finding.antipattern === 'bounce-easing')).toBe(true);
|
||||
expect(result.stderr).toContain('puppeteer is required for URL scanning');
|
||||
});
|
||||
|
||||
test('exits 1 when an explicitly requested local target cannot be accessed', () => {
|
||||
const result = runWithoutPuppeteer(['missing.css']);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('[]\n');
|
||||
expect(result.stderr).toContain('Warning: cannot access missing.css');
|
||||
});
|
||||
|
||||
test('missing local target takes precedence over findings from another target', () => {
|
||||
const result = runWithoutPuppeteer(
|
||||
['missing.css', 'page.css'],
|
||||
{ 'page.css': '.hero { animation: bounce 1s linear infinite; }\n' },
|
||||
);
|
||||
const findings = JSON.parse(result.stdout);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(findings.some(finding => finding.antipattern === 'bounce-easing')).toBe(true);
|
||||
expect(result.stderr).toContain('Warning: cannot access missing.css');
|
||||
});
|
||||
|
||||
test('unreadable local file exits 1 with valid empty JSON and no stack trace', () => {
|
||||
const result = runWithoutPuppeteer(
|
||||
['unreadable.css'],
|
||||
{
|
||||
'deny-fs.cjs': DENY_FS_PRELOAD,
|
||||
'unreadable.css': '.hero { color: red; }\n',
|
||||
},
|
||||
{ nodeArgs: ['--require=./deny-fs.cjs'] },
|
||||
);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('[]\n');
|
||||
expect(result.stderr).toContain('Error: cannot scan unreadable.css: simulated EACCES');
|
||||
expect(result.stderr).not.toContain('at detectLocalFile');
|
||||
});
|
||||
|
||||
test('unreadable directory file preserves findings from readable siblings', () => {
|
||||
const result = runWithoutPuppeteer(
|
||||
['styles'],
|
||||
{
|
||||
'deny-fs.cjs': DENY_FS_PRELOAD,
|
||||
'styles/unreadable.css': '.hero { color: red; }\n',
|
||||
'styles/page.css': '.hero { animation: bounce 1s linear infinite; }\n',
|
||||
},
|
||||
{ nodeArgs: ['--require=./deny-fs.cjs'] },
|
||||
);
|
||||
const findings = JSON.parse(result.stdout);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(findings.some(finding => finding.antipattern === 'bounce-easing')).toBe(true);
|
||||
expect(result.stderr.match(/simulated EACCES/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('unreadable local directory exits 1 with valid empty JSON', () => {
|
||||
const result = runWithoutPuppeteer(
|
||||
['unreadable-dir'],
|
||||
{
|
||||
'deny-fs.cjs': DENY_FS_PRELOAD,
|
||||
'unreadable-dir/page.css': '.hero { color: red; }\n',
|
||||
},
|
||||
{ nodeArgs: ['--require=./deny-fs.cjs'] },
|
||||
);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stdout).toBe('[]\n');
|
||||
expect(result.stderr).toContain('Error: cannot scan');
|
||||
expect(result.stderr).toContain('unreadable-dir: simulated directory EACCES');
|
||||
});
|
||||
|
||||
test('unreadable nested directory preserves findings from readable siblings', () => {
|
||||
const result = runWithoutPuppeteer(
|
||||
['project'],
|
||||
{
|
||||
'deny-fs.cjs': DENY_FS_PRELOAD,
|
||||
'project/unreadable-dir/hidden.css': '.hero { color: red; }\n',
|
||||
'project/page.css': '.hero { animation: bounce 1s linear infinite; }\n',
|
||||
},
|
||||
{ nodeArgs: ['--require=./deny-fs.cjs'] },
|
||||
);
|
||||
const findings = JSON.parse(result.stdout);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(findings.some(finding => finding.antipattern === 'bounce-easing')).toBe(true);
|
||||
expect(result.stderr.match(/simulated directory EACCES/g)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('splitScanUrl', () => {
|
||||
test('strips http(s) userinfo and returns credentials', () => {
|
||||
expect(splitScanUrl('https://user:pass@example.com')).toEqual({
|
||||
|
||||
@@ -1,9 +1,34 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'fs';
|
||||
import os from 'node:os';
|
||||
import path from 'path';
|
||||
import { readSourceFiles } from '../../scripts/lib/utils.js';
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const VENDOR_DIR = path.join(ROOT, 'cli/engine/vendor');
|
||||
const VENDOR_FILES = [
|
||||
'static-html-parsers.mjs',
|
||||
'static-html-parsers.LICENSES.txt',
|
||||
];
|
||||
|
||||
function runFreshnessCheck(checkDir) {
|
||||
const args = [path.join(ROOT, 'scripts/build-static-html-parsers.js'), '--check'];
|
||||
if (checkDir) args.push('--check-dir', checkDir);
|
||||
return spawnSync(process.execPath, args, { cwd: ROOT, encoding: 'utf8' });
|
||||
}
|
||||
|
||||
function withCopiedVendor(callback) {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-parser-vendor-'));
|
||||
try {
|
||||
for (const name of VENDOR_FILES) {
|
||||
fs.copyFileSync(path.join(VENDOR_DIR, name), path.join(tempDir, name));
|
||||
}
|
||||
callback(tempDir);
|
||||
} finally {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('skill detector bundle', () => {
|
||||
test('adds the detector wrapper and engine files to skill scripts', () => {
|
||||
@@ -16,6 +41,53 @@ describe('skill detector bundle', () => {
|
||||
expect(scriptNames.has('detector/detect-antipatterns-browser.js')).toBe(true);
|
||||
expect(scriptNames.has('detector/cli/main.mjs')).toBe(true);
|
||||
expect(scriptNames.has('detector/engines/static-html/detect-html.mjs')).toBe(true);
|
||||
expect(scriptNames.has('detector/vendor/static-html-parsers.mjs')).toBe(true);
|
||||
expect(scriptNames.has('detector/vendor/static-html-parsers.LICENSES.txt')).toBe(true);
|
||||
});
|
||||
|
||||
test('static HTML parser vendor bundle matches a fresh rebuild', () => {
|
||||
const result = runFreshnessCheck();
|
||||
expect(result.status).toBe(0);
|
||||
});
|
||||
|
||||
test('static HTML parser --check fails when the vendor bundle is stale', () => {
|
||||
withCopiedVendor((tempDir) => {
|
||||
const vendor = path.join(tempDir, 'static-html-parsers.mjs');
|
||||
fs.appendFileSync(vendor, '// stale\n');
|
||||
const result = runFreshnessCheck(tempDir);
|
||||
expect(result.status).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
test('static HTML parser --check fails when bundled licenses are stale', () => {
|
||||
withCopiedVendor((tempDir) => {
|
||||
const licenses = path.join(tempDir, 'static-html-parsers.LICENSES.txt');
|
||||
fs.appendFileSync(licenses, 'stale\n');
|
||||
const result = runFreshnessCheck(tempDir);
|
||||
expect(result.status).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
test('static HTML parser bundle stays compact and carries every dependency license', () => {
|
||||
const bundle = fs.readFileSync(path.join(VENDOR_DIR, 'static-html-parsers.mjs'));
|
||||
const licenses = fs.readFileSync(path.join(VENDOR_DIR, 'static-html-parsers.LICENSES.txt'), 'utf8');
|
||||
expect(bundle.byteLength).toBeLessThanOrEqual(256 * 1024);
|
||||
for (const packageName of [
|
||||
'boolbase',
|
||||
'css-select',
|
||||
'css-tree',
|
||||
'css-what',
|
||||
'dom-serializer',
|
||||
'domelementtype',
|
||||
'domhandler',
|
||||
'domutils',
|
||||
'entities',
|
||||
'htmlparser2',
|
||||
'nth-check',
|
||||
'source-map-js',
|
||||
]) {
|
||||
expect(licenses).toContain(`Package: ${packageName}@`);
|
||||
}
|
||||
});
|
||||
|
||||
test('critique references the bundled detector command', () => {
|
||||
|
||||
Reference in New Issue
Block a user