From eee993149a119e4df8b7a80d73887f5cefa71dde Mon Sep 17 00:00:00 2001 From: Maksim <11676775+maksimgm@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:59:31 -0800 Subject: [PATCH] feat: add fail-on input to fail the action on warnings checks now return a structured result (check name, message and whether it breached) instead of pushing strings, so the action can fail on a chosen set of checks after the comment or artifact is written. closes #168 --- README.md | 18 ++ action.yml | 3 + build/main.js | 194 +++++++++++------- recipes/artifact/analyze.yml | 3 +- recipes/artifact/comment.yml | 3 +- src/checks/bundle-size.ts | 20 +- src/checks/dependency-count.ts | 12 +- src/checks/dependency-size.ts | 15 +- src/checks/duplicates.ts | 12 +- src/checks/install-scripts.ts | 12 +- src/checks/license.ts | 12 +- src/checks/provenance.ts | 12 +- src/checks/replacements.ts | 12 +- src/checks/result.ts | 48 +++++ src/main.ts | 80 +++++--- .../__snapshots__/bundle-size_test.ts.snap | 64 +++--- .../dependency-size_test.ts.snap | 32 +-- .../__snapshots__/duplicates_test.ts.snap | 24 ++- test/checks/bundle-size_test.ts | 60 +++--- test/checks/dependency-size_test.ts | 36 ++-- test/checks/duplicates_test.ts | 48 ++--- test/checks/install-scripts_test.ts | 43 ++-- test/checks/license_test.ts | 26 +-- test/checks/replacements_test.ts | 12 +- test/checks/result_test.ts | 45 ++++ 25 files changed, 514 insertions(+), 332 deletions(-) create mode 100644 src/checks/result.ts create mode 100644 test/checks/result_test.ts diff --git a/README.md b/README.md index e6076b6..453e3c1 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ jobs: | `detect-replacements` | Detect modules which have community suggested alternatives | No | `true` | | `detect-license-changes` | Detect when a dependency changes its license between versions | No | `true` | | `detect-install-scripts` | Detect when a newly added or upgraded dependency introduces install scripts | No | `true` | +| `fail-on` | Comma-separated list of checks that fail the action when they warn (see [Failing on Warnings](#failing-on-warnings)) | No | None | | `exclude-dev-dependencies` | Exclude devDependencies and their exclusive transitive dependencies from analysis | No | `false` | | `exclude-packages` | Comma-separated package names or wildcard patterns (e.g., `"@types/*, eslint-*"`) to exclude with their dependency trees | No | None | | `working-directory` | Working directory to scan for package lock file | No | None | @@ -145,6 +146,21 @@ You can disable this check with: detect-install-scripts: false ``` +## Failing on Warnings + +By default the action only reports, so the check always passes. To fail the action when certain checks warn, list them in `fail-on`. You can then mark the job as a required status check to block merging. + +```yaml +- name: Create Diff + uses: e18e/action-dependency-diff@v1 + with: + fail-on: dependency-count, dependency-size +``` + +The available checks are `dependency-count`, `dependency-size`, `duplicates`, `provenance`, `license`, `install-scripts`, `bundle-size` and `replacements`. Checks that aren't listed stay advisory. + +The comment (or artifact) is written before the action fails, so the report still shows up on the pull request. Size decreases, and reports shown because a threshold is `-1`, never fail the action. + ## Supported package managers - npm (package-lock.json) @@ -187,6 +203,8 @@ If you'd prefer not to use `pull_request_target`, you can use a two-workflow set mode: comment-from-artifact ``` +If you use `fail-on` with artifact mode, the analyze workflow fails when a listed check warns. Make sure the artifact is still uploaded and the comment workflow runs for failed runs too, as the recipes do. + See the [`recipes/artifact/`](./recipes/artifact/) directory for complete workflow files. ## Trust levels of packages diff --git a/action.yml b/action.yml index 86a5618..5d907a8 100644 --- a/action.yml +++ b/action.yml @@ -52,6 +52,9 @@ inputs: description: 'Detect when a newly added or upgraded dependency introduces install scripts' required: false default: true + fail-on: + description: 'Comma-separated list of checks that fail the action when they warn (dependency-count, dependency-size, duplicates, provenance, license, install-scripts, bundle-size, replacements). The comment or artifact is still written first.' + required: false exclude-dev-dependencies: description: 'Exclude devDependencies and their exclusive transitive dependencies from analysis' required: false diff --git a/build/main.js b/build/main.js index 9c15a20..e8ff375 100644 --- a/build/main.js +++ b/build/main.js @@ -24634,7 +24634,7 @@ var all = { }; // src/checks/replacements.ts -function scanForReplacements(messages, baseDependencies, currentDependencies) { +function scanForReplacements(baseDependencies, currentDependencies) { const replacementMessages = []; for (const [name] of currentDependencies) { if (!baseDependencies.has(name)) { @@ -24674,8 +24674,10 @@ function scanForReplacements(messages, baseDependencies, currentDependencies) { } } if (replacementMessages.length > 0) { - messages.push( - `## \u26A0\uFE0F Recommended Package Replacements + return { + check: "replacements", + breached: true, + message: `## \u26A0\uFE0F Recommended Package Replacements The following new packages or versions have community recommended replacements: @@ -24688,7 +24690,7 @@ ${replacementMessages.join("\n")} > They may not always be a straightforward migration, so please review carefully > and use the \`exclude-packages\` input if you want to ignore any of them in future. ` - ); + }; } } @@ -24733,7 +24735,7 @@ function computeParentPaths(lockfile, duplicateDependencyNames, dependencyMap) { traverse(lockfile.root, visitor); return parentPaths; } -function scanForDuplicates(messages, threshold, dependencyMap, baseDependencyMap, lockfilePath, lockfile) { +function scanForDuplicates(threshold, dependencyMap, baseDependencyMap, lockfilePath, lockfile) { const duplicateRows = []; const duplicateDependencyNames = /* @__PURE__ */ new Set(); for (const [packageName, currentVersionSet] of dependencyMap) { @@ -24791,18 +24793,20 @@ function scanForDuplicates(messages, threshold, dependencyMap, baseDependencyMap const helpMessage = exampleCommand ? ` \u{1F4A1} To find out what depends on a specific package, run: \`${exampleCommand}\`` : ""; - messages.push( - `## \u26A0\uFE0F New Duplicate Dependencies (found: ${duplicateRows.length}, threshold: ${threshold}) + return { + check: "duplicates", + breached: true, + message: `## \u26A0\uFE0F New Duplicate Dependencies (found: ${duplicateRows.length}, threshold: ${threshold}) | \u{1F4E6} Package | \u{1F4CB} Versions | | --- | --- | ${duplicateRows.join("\n")}${helpMessage}` - ); + }; } } // src/checks/dependency-count.ts -function scanForDependencyCount(messages, threshold, currentDeps, baseDeps) { +function scanForDependencyCount(threshold, currentDeps, baseDeps) { const currentDepCount = Array.from(currentDeps.values()).reduce( (sum, versions) => sum + versions.size, 0 @@ -24816,11 +24820,13 @@ function scanForDependencyCount(messages, threshold, currentDeps, baseDeps) { info(`Current dependency count: ${currentDepCount}`); info(`Dependency count increase: ${depIncrease}`); if (depIncrease >= threshold) { - messages.push( - `## \u26A0\uFE0F Dependency Count + return { + check: "dependency-count", + breached: true, + message: `## \u26A0\uFE0F Dependency Count This PR adds ${depIncrease} new dependencies (${baseDepCount} \u2192 ${currentDepCount}), which exceeds the threshold of ${threshold}.` - ); + }; } } @@ -24896,7 +24902,7 @@ async function removeUnsupportedOptionalDependencies(lockFile, versionInfo) { } } } -async function scanForDependencySize(messages, threshold, currentDeps, baseDeps, currentLockFile, baseLockFile) { +async function scanForDependencySize(threshold, currentDeps, baseDeps, currentLockFile, baseLockFile) { const newVersions = []; const removedVersions = []; for (const [packageName, currentVersionSet] of currentDeps) { @@ -24948,8 +24954,9 @@ async function scanForDependencySize(messages, threshold, currentDeps, baseDeps, const packageRows = displayEntries.map( ({ label, size }) => `| ${label} | ${size === null ? "_Unknown_" : formatBytes(size)} |` ).join("\n"); + const breached = threshold !== -1 && sizeData.totalSize >= threshold; let alert = ""; - if (threshold !== -1 && sizeData.totalSize >= threshold) { + if (breached) { alert = `> [!WARNING] > This PR adds ${formatBytes(sizeData.totalSize)} of new dependencies, which exceeds the threshold of ${formatBytes(threshold)}. @@ -24960,15 +24967,17 @@ async function scanForDependencySize(messages, threshold, currentDeps, baseDeps, `; } - messages.push( - `## \u{1F4CA} Dependency Size Changes + return { + check: "dependency-size", + breached, + message: `## \u{1F4CA} Dependency Size Changes ${alert}| \u{1F4E6} Package | \u{1F4CF} Size | | --- | --- | ${packageRows} **Total size change:** ${formatBytes(sizeData.totalSize)}` - ); + }; } } catch (err) { info(`Failed to calculate total dependency size increase: ${err}`); @@ -24976,7 +24985,7 @@ ${packageRows} } // src/checks/provenance.ts -async function scanForProvenance(messages, currentDeps, baseDeps) { +async function scanForProvenance(currentDeps, baseDeps) { const provenanceRows = []; for (const [packageName, currentVersionSet] of currentDeps) { const baseVersionSet = baseDeps.get(packageName); @@ -25010,8 +25019,10 @@ async function scanForProvenance(messages, currentDeps, baseDeps) { } } if (provenanceRows.length > 0) { - messages.push( - `## \u26A0\uFE0F Package Trust Level Decreased + return { + check: "provenance", + breached: true, + message: `## \u26A0\uFE0F Package Trust Level Decreased > [!CAUTION] > Decreased trust levels may indicate a higher risk of supply chain attacks. Please review these changes carefully. @@ -25019,12 +25030,12 @@ async function scanForProvenance(messages, currentDeps, baseDeps) { | \u{1F4E6} Package | \u{1F512} Before | \u{1F513} After | | --- | --- | --- | ${provenanceRows.join("\n")}` - ); + }; } } // src/checks/license.ts -async function scanForLicenses(messages, currentDeps, baseDeps) { +async function scanForLicenses(currentDeps, baseDeps) { const licenseRows = []; for (const [packageName, currentVersionSet] of currentDeps) { const baseVersionSet = baseDeps.get(packageName); @@ -25074,18 +25085,20 @@ async function scanForLicenses(messages, currentDeps, baseDeps) { } } if (licenseRows.length > 0) { - messages.push( - `## \u26A0\uFE0F License Changes + return { + check: "license", + breached: true, + message: `## \u26A0\uFE0F License Changes | \u{1F4E6} Package | \u{1F4DC} Previous License | \u{1F4DC} New License | | --- | --- | --- | ${licenseRows.join("\n")}` - ); + }; } } // src/checks/install-scripts.ts -async function scanForInstallScripts(messages, currentDeps, baseDeps) { +async function scanForInstallScripts(currentDeps, baseDeps) { const installScriptRows = []; for (const [packageName, currentVersionSet] of currentDeps) { const baseVersionSet = baseDeps.get(packageName); @@ -25130,8 +25143,10 @@ async function scanForInstallScripts(messages, currentDeps, baseDeps) { } } if (installScriptRows.length > 0) { - messages.push( - `## \u26A0\uFE0F Install Scripts Added + return { + check: "install-scripts", + breached: true, + message: `## \u26A0\uFE0F Install Scripts Added > [!WARNING] > These packages run scripts during \`npm install\`. New install scripts can execute arbitrary code and increase supply chain risk. Please review them carefully. @@ -25139,7 +25154,7 @@ async function scanForInstallScripts(messages, currentDeps, baseDeps) { | \u{1F4E6} Package | \u{1F504} Change | \u{1F527} Added Install Scripts | | --- | --- | --- | ${installScriptRows.join("\n")}` - ); + }; } } @@ -25147,7 +25162,7 @@ ${installScriptRows.join("\n")}` function formatBytesSigned(bytes) { return `${bytes > 0 ? "+" : ""}${formatBytes(bytes)}`; } -async function scanForBundleSize(messages, basePacks, sourcePacks, threshold) { +async function scanForBundleSize(basePacks, sourcePacks, threshold) { if (basePacks.length === 0 && sourcePacks.length === 0) { return; } @@ -25156,10 +25171,13 @@ async function scanForBundleSize(messages, basePacks, sourcePacks, threshold) { (change) => change.exceedsThreshold ); if (threshold === -1 && packWarnings.length === 0) { - messages.push(`## \u{1F4E6} Package Bundle Size + return { + check: "bundle-size", + breached: false, + message: `## \u{1F4E6} Package Bundle Size -No bundle size changes.`); - return; +No bundle size changes.` + }; } if (packWarnings.length > 0) { const hasDecreases = packWarnings.some((c) => c.sizeChange < 0); @@ -25174,14 +25192,47 @@ No bundle size changes.`); const thresholdText = threshold === -1 ? "" : ` These packages exceed the size change threshold of ${formatBytes(threshold)}: `; - messages.push( - `${heading} + return { + check: "bundle-size", + // with a threshold set, only increases over it are reported + breached: threshold !== -1, + message: `${heading} ${thresholdText} | \u{1F4E6} Package | \u{1F4CF} Base Size | \u{1F4CF} Source Size | \u{1F4C8} Size Change | | --- | --- | --- | --- | ${packRows}` - ); + }; + } +} + +// src/checks/result.ts +var checkNames = [ + "dependency-count", + "dependency-size", + "duplicates", + "provenance", + "license", + "install-scripts", + "bundle-size", + "replacements" +]; +function isCheckName(name) { + return checkNames.includes(name); +} +function parseFailOn(input) { + const checks = /* @__PURE__ */ new Set(); + for (const name of parseCommaList(input)) { + if (!isCheckName(name)) { + throw new Error( + `Unknown check "${name}" in fail-on. Valid checks are: ${checkNames.join(", ")}` + ); + } + checks.add(name); } + return checks; +} +function getFailedChecks(results, failOn) { + return results.filter((result) => result.breached && failOn.has(result.check)).map((result) => result.check); } // src/constants.ts @@ -25291,6 +25342,7 @@ async function analyzeAndComment() { getInput("pack-size-threshold") || "50000", 10 ); + const failOn = parseFailOn(getInput("fail-on")); if (Number.isNaN(prNumber) || prNumber < 1) { info("No valid pull request number was found. Skipping."); return; @@ -25371,32 +25423,39 @@ async function analyzeAndComment() { info(`Size threshold set to ${formatBytes(sizeThreshold)}`); info(`Duplicate threshold set to ${duplicateThreshold}`); info(`Pack size threshold set to ${formatBytes(packSizeThreshold)}`); - const messages = []; - scanForDependencyCount(messages, dependencyThreshold, currentDeps, baseDeps); + const results = []; + const addResult = (result) => { + if (result) { + results.push(result); + } + }; + addResult(scanForDependencyCount(dependencyThreshold, currentDeps, baseDeps)); if (duplicateThreshold > 0) { - scanForDuplicates( - messages, - duplicateThreshold, - currentDeps, - baseDeps, - lockfilePath, - parsedCurrentLock + addResult( + scanForDuplicates( + duplicateThreshold, + currentDeps, + baseDeps, + lockfilePath, + parsedCurrentLock + ) ); } - await scanForDependencySize( - messages, - sizeThreshold, - currentDeps, - baseDeps, - parsedCurrentLock, - parsedBaseLock + addResult( + await scanForDependencySize( + sizeThreshold, + currentDeps, + baseDeps, + parsedCurrentLock, + parsedBaseLock + ) ); - await scanForProvenance(messages, currentDeps, baseDeps); + addResult(await scanForProvenance(currentDeps, baseDeps)); if (detectInstallScripts) { - await scanForInstallScripts(messages, currentDeps, baseDeps); + addResult(await scanForInstallScripts(currentDeps, baseDeps)); } if (detectLicenseChanges) { - await scanForLicenses(messages, currentDeps, baseDeps); + addResult(await scanForLicenses(currentDeps, baseDeps)); } const basePackagesPattern = getInput("base-packages"); const sourcePackagesPattern = getInput("source-packages"); @@ -25410,11 +25469,8 @@ async function analyzeAndComment() { info( `Found ${basePacks.length} base packs and ${sourcePacks.length} source packs` ); - await scanForBundleSize( - messages, - basePacks, - sourcePacks, - packSizeThreshold + addResult( + await scanForBundleSize(basePacks, sourcePacks, packSizeThreshold) ); } catch (err) { info(`Failed to compare pack sizes: ${err}`); @@ -25437,8 +25493,10 @@ async function analyzeAndComment() { depTypes, excludePackages ); - scanForReplacements(messages, baseDependencies, currentDependencies); + addResult(scanForReplacements(baseDependencies, currentDependencies)); } + const messages = results.map((result) => result.message); + const failedChecks = getFailedChecks(results, failOn); const report = messages.length === 0 ? "## e18e dependency analysis\n\nNo dependency warnings found.\n" : messages.join("\n\n"); const commentBody = `${COMMENT_TAG} ${report}`; @@ -25453,19 +25511,17 @@ ${report}`; ); setOutput("artifact-path", outputPath); info(`Wrote artifact to ${outputPath}`); - return; - } - const octokit = getOctokit(token); - if (messages.length === 0) { - const existingCommentId = await findExistingComment(octokit, prNumber); - if (existingCommentId) { + } else { + const octokit = getOctokit(token); + if (messages.length > 0 || await findExistingComment(octokit, prNumber)) { await upsertComment(octokit, prNumber, commentBody); } else { info("No dependency warnings found. Skipping comment creation."); } - return; } - await upsertComment(octokit, prNumber, commentBody); + if (failedChecks.length > 0) { + setFailed(`Dependency checks failed: ${failedChecks.join(", ")}`); + } } async function run() { try { diff --git a/recipes/artifact/analyze.yml b/recipes/artifact/analyze.yml index 97ef442..142e850 100644 --- a/recipes/artifact/analyze.yml +++ b/recipes/artifact/analyze.yml @@ -19,7 +19,8 @@ jobs: with: mode: artifact - name: Upload Artifact - if: steps.analyze.outputs.artifact-path + # still upload when `fail-on` fails the analyze step + if: ${{ !cancelled() && steps.analyze.outputs.artifact-path }} uses: actions/upload-artifact@v4 with: name: e18e-diff-result diff --git a/recipes/artifact/comment.yml b/recipes/artifact/comment.yml index 632ecf7..8ec0b91 100644 --- a/recipes/artifact/comment.yml +++ b/recipes/artifact/comment.yml @@ -9,7 +9,8 @@ on: jobs: post_comment: runs-on: ubuntu-latest - if: github.event.workflow_run.conclusion == 'success' + # also post the report when `fail-on` failed the analyze run + if: github.event.workflow_run.conclusion == 'success' || github.event.workflow_run.conclusion == 'failure' permissions: pull-requests: write actions: read diff --git a/src/checks/bundle-size.ts b/src/checks/bundle-size.ts index cd1ef6d..4a8c3ac 100644 --- a/src/checks/bundle-size.ts +++ b/src/checks/bundle-size.ts @@ -1,16 +1,16 @@ import {formatBytes} from '../common.js'; import {comparePackSizes, type PackInfo} from '../packs.js'; +import type {CheckResult} from './result.js'; function formatBytesSigned(bytes: number): string { return `${bytes > 0 ? '+' : ''}${formatBytes(bytes)}`; } export async function scanForBundleSize( - messages: string[], basePacks: PackInfo[], sourcePacks: PackInfo[], threshold: number -): Promise { +): Promise { if (basePacks.length === 0 && sourcePacks.length === 0) { return; } @@ -21,8 +21,11 @@ export async function scanForBundleSize( ); if (threshold === -1 && packWarnings.length === 0) { - messages.push(`## šŸ“¦ Package Bundle Size\n\nNo bundle size changes.`); - return; + return { + check: 'bundle-size', + breached: false, + message: `## šŸ“¦ Package Bundle Size\n\nNo bundle size changes.` + }; } if (packWarnings.length > 0) { @@ -50,12 +53,15 @@ export async function scanForBundleSize( ? '' : `\nThese packages exceed the size change threshold of ${formatBytes(threshold)}:\n`; - messages.push( - `${heading} + return { + check: 'bundle-size', + // with a threshold set, only increases over it are reported + breached: threshold !== -1, + message: `${heading} ${thresholdText} | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | ${packRows}` - ); + }; } } diff --git a/src/checks/dependency-count.ts b/src/checks/dependency-count.ts index 1c7daa7..aec6362 100644 --- a/src/checks/dependency-count.ts +++ b/src/checks/dependency-count.ts @@ -1,11 +1,11 @@ import * as core from '@actions/core'; +import type {CheckResult} from './result.js'; export function scanForDependencyCount( - messages: string[], threshold: number, currentDeps: Map>, baseDeps: Map> -): void { +): CheckResult | undefined { const currentDepCount = Array.from(currentDeps.values()).reduce( (sum, versions) => sum + versions.size, 0 @@ -20,10 +20,12 @@ export function scanForDependencyCount( core.info(`Dependency count increase: ${depIncrease}`); if (depIncrease >= threshold) { - messages.push( - `## āš ļø Dependency Count + return { + check: 'dependency-count', + breached: true, + message: `## āš ļø Dependency Count This PR adds ${depIncrease} new dependencies (${baseDepCount} → ${currentDepCount}), which exceeds the threshold of ${threshold}.` - ); + }; } } diff --git a/src/checks/dependency-size.ts b/src/checks/dependency-size.ts index d41ba99..918cb8c 100644 --- a/src/checks/dependency-size.ts +++ b/src/checks/dependency-size.ts @@ -6,6 +6,7 @@ import { isSupportedArchitecture } from '../npm.js'; import {formatBytes} from '../common.js'; +import type {CheckResult} from './result.js'; interface PackageGroup { added: Array<{version: string; size: number | null}>; @@ -118,13 +119,12 @@ async function removeUnsupportedOptionalDependencies( } export async function scanForDependencySize( - messages: string[], threshold: number, currentDeps: Map>, baseDeps: Map>, currentLockFile: ParsedLockFile, baseLockFile: ParsedLockFile -): Promise { +): Promise { const newVersions: Array<{ name: string; version: string; @@ -204,22 +204,25 @@ export async function scanForDependencySize( ) .join('\n'); + const breached = threshold !== -1 && sizeData.totalSize >= threshold; let alert = ''; - if (threshold !== -1 && sizeData.totalSize >= threshold) { + if (breached) { alert = `> [!WARNING]\n> This PR adds ${formatBytes(sizeData.totalSize)} of new dependencies, which exceeds the threshold of ${formatBytes(threshold)}.\n\n`; } else if (sizeData.totalSize < 0) { alert = `> [!NOTE]\n> :tada: This PR removes ${formatBytes(Math.abs(sizeData.totalSize))} of dependencies.\n\n`; } - messages.push( - `## šŸ“Š Dependency Size Changes + return { + check: 'dependency-size', + breached, + message: `## šŸ“Š Dependency Size Changes ${alert}| šŸ“¦ Package | šŸ“ Size | | --- | --- | ${packageRows} **Total size change:** ${formatBytes(sizeData.totalSize)}` - ); + }; } } catch (err) { core.info(`Failed to calculate total dependency size increase: ${err}`); diff --git a/src/checks/duplicates.ts b/src/checks/duplicates.ts index 5c302ec..bef36b8 100644 --- a/src/checks/duplicates.ts +++ b/src/checks/duplicates.ts @@ -1,4 +1,5 @@ import {type ParsedLockFile, traverse, type VisitorFn} from 'lockparse'; +import type {CheckResult} from './result.js'; function getLsCommand( lockfilePath: string, @@ -53,13 +54,12 @@ function computeParentPaths( } export function scanForDuplicates( - messages: string[], threshold: number, dependencyMap: Map>, baseDependencyMap: Map>, lockfilePath: string, lockfile: ParsedLockFile -): void { +): CheckResult | undefined { const duplicateRows: string[] = []; const duplicateDependencyNames = new Set(); @@ -130,12 +130,14 @@ export function scanForDuplicates( const helpMessage = exampleCommand ? `\n\nšŸ’” To find out what depends on a specific package, run: \`${exampleCommand}\`` : ''; - messages.push( - `## āš ļø New Duplicate Dependencies (found: ${duplicateRows.length}, threshold: ${threshold}) + return { + check: 'duplicates', + breached: true, + message: `## āš ļø New Duplicate Dependencies (found: ${duplicateRows.length}, threshold: ${threshold}) | šŸ“¦ Package | šŸ“‹ Versions | | --- | --- | ${duplicateRows.join('\n')}${helpMessage}` - ); + }; } } diff --git a/src/checks/install-scripts.ts b/src/checks/install-scripts.ts index fddea60..8ef55f4 100644 --- a/src/checks/install-scripts.ts +++ b/src/checks/install-scripts.ts @@ -1,11 +1,11 @@ import * as core from '@actions/core'; import {getInstallScriptsForPackageVersions} from '../npm.js'; +import type {CheckResult} from './result.js'; export async function scanForInstallScripts( - messages: string[], currentDeps: Map>, baseDeps: Map> -): Promise { +): Promise { const installScriptRows: string[] = []; for (const [packageName, currentVersionSet] of currentDeps) { @@ -59,8 +59,10 @@ export async function scanForInstallScripts( } if (installScriptRows.length > 0) { - messages.push( - `## āš ļø Install Scripts Added + return { + check: 'install-scripts', + breached: true, + message: `## āš ļø Install Scripts Added > [!WARNING] > These packages run scripts during \`npm install\`. New install scripts can execute arbitrary code and increase supply chain risk. Please review them carefully. @@ -68,6 +70,6 @@ export async function scanForInstallScripts( | šŸ“¦ Package | šŸ”„ Change | šŸ”§ Added Install Scripts | | --- | --- | --- | ${installScriptRows.join('\n')}` - ); + }; } } diff --git a/src/checks/license.ts b/src/checks/license.ts index e49197c..b93d540 100644 --- a/src/checks/license.ts +++ b/src/checks/license.ts @@ -1,11 +1,11 @@ import * as core from '@actions/core'; import {getLicensesForPackageVersions} from '../npm.js'; +import type {CheckResult} from './result.js'; export async function scanForLicenses( - messages: string[], currentDeps: Map>, baseDeps: Map> -): Promise { +): Promise { const licenseRows: string[] = []; for (const [packageName, currentVersionSet] of currentDeps) { @@ -65,12 +65,14 @@ export async function scanForLicenses( } if (licenseRows.length > 0) { - messages.push( - `## āš ļø License Changes + return { + check: 'license', + breached: true, + message: `## āš ļø License Changes | šŸ“¦ Package | šŸ“œ Previous License | šŸ“œ New License | | --- | --- | --- | ${licenseRows.join('\n')}` - ); + }; } } diff --git a/src/checks/provenance.ts b/src/checks/provenance.ts index d5af4e7..5f9bc53 100644 --- a/src/checks/provenance.ts +++ b/src/checks/provenance.ts @@ -1,11 +1,11 @@ import * as core from '@actions/core'; import {getMinTrustLevel, getProvenanceForPackageVersions} from '../npm.js'; +import type {CheckResult} from './result.js'; export async function scanForProvenance( - messages: string[], currentDeps: Map>, baseDeps: Map> -): Promise { +): Promise { const provenanceRows: string[] = []; for (const [packageName, currentVersionSet] of currentDeps) { @@ -47,8 +47,10 @@ export async function scanForProvenance( } if (provenanceRows.length > 0) { - messages.push( - `## āš ļø Package Trust Level Decreased + return { + check: 'provenance', + breached: true, + message: `## āš ļø Package Trust Level Decreased > [!CAUTION] > Decreased trust levels may indicate a higher risk of supply chain attacks. Please review these changes carefully. @@ -56,6 +58,6 @@ export async function scanForProvenance( | šŸ“¦ Package | šŸ”’ Before | šŸ”“ After | | --- | --- | --- | ${provenanceRows.join('\n')}` - ); + }; } } diff --git a/src/checks/replacements.ts b/src/checks/replacements.ts index c1ad338..2c1be00 100644 --- a/src/checks/replacements.ts +++ b/src/checks/replacements.ts @@ -1,10 +1,10 @@ import {all as allReplacements, resolveDocUrl} from 'module-replacements'; +import type {CheckResult} from './result.js'; export function scanForReplacements( - messages: string[], baseDependencies: Map, currentDependencies: Map -): void { +): CheckResult | undefined { const replacementMessages: string[] = []; for (const [name] of currentDependencies) { @@ -55,8 +55,10 @@ export function scanForReplacements( } if (replacementMessages.length > 0) { - messages.push( - `## āš ļø Recommended Package Replacements + return { + check: 'replacements', + breached: true, + message: `## āš ļø Recommended Package Replacements The following new packages or versions have community recommended replacements: @@ -69,6 +71,6 @@ ${replacementMessages.join('\n')} > They may not always be a straightforward migration, so please review carefully > and use the \`exclude-packages\` input if you want to ignore any of them in future. ` - ); + }; } } diff --git a/src/checks/result.ts b/src/checks/result.ts new file mode 100644 index 0000000..d808b17 --- /dev/null +++ b/src/checks/result.ts @@ -0,0 +1,48 @@ +import {parseCommaList} from '../common.js'; + +export const checkNames = [ + 'dependency-count', + 'dependency-size', + 'duplicates', + 'provenance', + 'license', + 'install-scripts', + 'bundle-size', + 'replacements' +] as const; + +export type CheckName = (typeof checkNames)[number]; + +export interface CheckResult { + check: CheckName; + message: string; + // false for informational reports, e.g. a size decrease or a size report + // shown because the threshold is -1 + breached: boolean; +} + +function isCheckName(name: string): name is CheckName { + return (checkNames as readonly string[]).includes(name); +} + +export function parseFailOn(input: string): Set { + const checks = new Set(); + for (const name of parseCommaList(input)) { + if (!isCheckName(name)) { + throw new Error( + `Unknown check "${name}" in fail-on. Valid checks are: ${checkNames.join(', ')}` + ); + } + checks.add(name); + } + return checks; +} + +export function getFailedChecks( + results: CheckResult[], + failOn: Set +): CheckName[] { + return results + .filter((result) => result.breached && failOn.has(result.check)) + .map((result) => result.check); +} diff --git a/src/main.ts b/src/main.ts index e86a546..da133bd 100644 --- a/src/main.ts +++ b/src/main.ts @@ -28,6 +28,11 @@ import {scanForLicenses} from './checks/license.js'; import {scanForInstallScripts} from './checks/install-scripts.js'; import {scanForBundleSize} from './checks/bundle-size.js'; import {formatBytes, parseCommaList} from './common.js'; +import { + type CheckResult, + getFailedChecks, + parseFailOn +} from './checks/result.js'; import {ARTIFACT_FILENAME, COMMENT_TAG} from './constants.js'; import {findExistingComment, upsertComment, writeJobSummary} from './github.js'; @@ -95,6 +100,7 @@ async function analyzeAndComment(): Promise { core.getInput('pack-size-threshold') || '50000', 10 ); + const failOn = parseFailOn(core.getInput('fail-on')); if (Number.isNaN(prNumber) || prNumber < 1) { core.info('No valid pull request number was found. Skipping.'); @@ -187,37 +193,44 @@ async function analyzeAndComment(): Promise { core.info(`Duplicate threshold set to ${duplicateThreshold}`); core.info(`Pack size threshold set to ${formatBytes(packSizeThreshold)}`); - const messages: string[] = []; + const results: CheckResult[] = []; + const addResult = (result: CheckResult | undefined): void => { + if (result) { + results.push(result); + } + }; - scanForDependencyCount(messages, dependencyThreshold, currentDeps, baseDeps); + addResult(scanForDependencyCount(dependencyThreshold, currentDeps, baseDeps)); if (duplicateThreshold > 0) { - scanForDuplicates( - messages, - duplicateThreshold, - currentDeps, - baseDeps, - lockfilePath, - parsedCurrentLock + addResult( + scanForDuplicates( + duplicateThreshold, + currentDeps, + baseDeps, + lockfilePath, + parsedCurrentLock + ) ); } - await scanForDependencySize( - messages, - sizeThreshold, - currentDeps, - baseDeps, - parsedCurrentLock, - parsedBaseLock + addResult( + await scanForDependencySize( + sizeThreshold, + currentDeps, + baseDeps, + parsedCurrentLock, + parsedBaseLock + ) ); - await scanForProvenance(messages, currentDeps, baseDeps); + addResult(await scanForProvenance(currentDeps, baseDeps)); if (detectInstallScripts) { - await scanForInstallScripts(messages, currentDeps, baseDeps); + addResult(await scanForInstallScripts(currentDeps, baseDeps)); } if (detectLicenseChanges) { - await scanForLicenses(messages, currentDeps, baseDeps); + addResult(await scanForLicenses(currentDeps, baseDeps)); } const basePackagesPattern = core.getInput('base-packages'); @@ -236,11 +249,8 @@ async function analyzeAndComment(): Promise { `Found ${basePacks.length} base packs and ${sourcePacks.length} source packs` ); - await scanForBundleSize( - messages, - basePacks, - sourcePacks, - packSizeThreshold + addResult( + await scanForBundleSize(basePacks, sourcePacks, packSizeThreshold) ); } catch (err) { core.info(`Failed to compare pack sizes: ${err}`); @@ -269,9 +279,12 @@ async function analyzeAndComment(): Promise { excludePackages ); - scanForReplacements(messages, baseDependencies, currentDependencies); + addResult(scanForReplacements(baseDependencies, currentDependencies)); } + const messages = results.map((result) => result.message); + const failedChecks = getFailedChecks(results, failOn); + const report = messages.length === 0 ? '## e18e dependency analysis\n\nNo dependency warnings found.\n' @@ -292,22 +305,21 @@ async function analyzeAndComment(): Promise { core.setOutput('artifact-path', outputPath); core.info(`Wrote artifact to ${outputPath}`); - return; - } + } else { + const octokit = github.getOctokit(token); - const octokit = github.getOctokit(token); - - if (messages.length === 0) { - const existingCommentId = await findExistingComment(octokit, prNumber); - if (existingCommentId) { + if (messages.length > 0 || (await findExistingComment(octokit, prNumber))) { await upsertComment(octokit, prNumber, commentBody); } else { core.info('No dependency warnings found. Skipping comment creation.'); } - return; } - await upsertComment(octokit, prNumber, commentBody); + // fail after the comment or artifact is written, so the report still + // shows up on the pull request + if (failedChecks.length > 0) { + core.setFailed(`Dependency checks failed: ${failedChecks.join(', ')}`); + } } async function run(): Promise { diff --git a/test/checks/__snapshots__/bundle-size_test.ts.snap b/test/checks/__snapshots__/bundle-size_test.ts.snap index af71a71..83e6796 100644 --- a/test/checks/__snapshots__/bundle-size_test.ts.snap +++ b/test/checks/__snapshots__/bundle-size_test.ts.snap @@ -1,84 +1,100 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`scanForBundleSize > should report no bundle size change with threshold=-1 when diff is 0 1`] = ` -[ - "## šŸ“¦ Package Bundle Size +{ + "breached": false, + "check": "bundle-size", + "message": "## šŸ“¦ Package Bundle Size No bundle size changes.", -] +} `; exports[`scanForBundleSize > should report size decrease when threshold is -1 1`] = ` -[ - "## šŸŽ‰ Package Size Decrease +{ + "breached": false, + "check": "bundle-size", + "message": "## šŸŽ‰ Package Size Decrease | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | my-package | 200 kB | 100 kB | -100 kB |", -] +} `; exports[`scanForBundleSize > should show both decreases and increases when threshold is -1 1`] = ` -[ - "## šŸ“¦ Package Bundle Size Changes +{ + "breached": false, + "check": "bundle-size", + "message": "## šŸ“¦ Package Bundle Size Changes | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | pkg-b | 50 kB | 150 kB | +100 kB | | pkg-a | 200 kB | 100 kB | -100 kB |", -] +} `; exports[`scanForBundleSize > should show new packages when threshold is -1 1`] = ` -[ - "## āš ļø Package Size Increase +{ + "breached": false, + "check": "bundle-size", + "message": "## āš ļø Package Size Increase | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | new-package | New | 50 kB | +50 kB |", -] +} `; exports[`scanForBundleSize > should show only increases when threshold is -1 and no decreases 1`] = ` -[ - "## āš ļø Package Size Increase +{ + "breached": false, + "check": "bundle-size", + "message": "## āš ļø Package Size Increase | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | my-package | 100 kB | 200 kB | +100 kB |", -] +} `; exports[`scanForBundleSize > should show removed packages when threshold is -1 1`] = ` -[ - "## šŸŽ‰ Package Size Decrease +{ + "breached": false, + "check": "bundle-size", + "message": "## šŸŽ‰ Package Size Decrease | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | old-package | 50 kB | Removed | -50 kB |", -] +} `; exports[`scanForBundleSize > should warn about an increase regardless of other packages decreasing 1`] = ` -[ - "## āš ļø Package Size Increase +{ + "breached": true, + "check": "bundle-size", + "message": "## āš ļø Package Size Increase These packages exceed the size change threshold of 50 kB: | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | pkg-b | 50 kB | 150 kB | +100 kB |", -] +} `; exports[`scanForBundleSize > should warn about size increase exceeding threshold 1`] = ` -[ - "## āš ļø Package Size Increase +{ + "breached": true, + "check": "bundle-size", + "message": "## āš ļø Package Size Increase These packages exceed the size change threshold of 50 kB: | šŸ“¦ Package | šŸ“ Base Size | šŸ“ Source Size | šŸ“ˆ Size Change | | --- | --- | --- | --- | | my-package | 100 kB | 200 kB | +100 kB |", -] +} `; diff --git a/test/checks/__snapshots__/dependency-size_test.ts.snap b/test/checks/__snapshots__/dependency-size_test.ts.snap index 70188f1..b974e38 100644 --- a/test/checks/__snapshots__/dependency-size_test.ts.snap +++ b/test/checks/__snapshots__/dependency-size_test.ts.snap @@ -15,8 +15,10 @@ exports[`scanForDependencySize > should not report changes below the threshold 1 `; exports[`scanForDependencySize > should report negative upgrades on one line 1`] = ` -[ - "## šŸ“Š Dependency Size Changes +{ + "breached": false, + "check": "dependency-size", + "message": "## šŸ“Š Dependency Size Changes > [!NOTE] > :tada: This PR removes 138.5 kB of dependencies. @@ -26,7 +28,7 @@ exports[`scanForDependencySize > should report negative upgrades on one line 1`] | chai@5.0.0 → chai@5.0.2 | -138.5 kB | **Total size change:** -138.5 kB", -] +} `; exports[`scanForDependencySize > should report negative upgrades on one line 2`] = ` @@ -45,8 +47,10 @@ exports[`scanForDependencySize > should report negative upgrades on one line 2`] `; exports[`scanForDependencySize > should report new dependencies exceeding the threshold 1`] = ` -[ - "## šŸ“Š Dependency Size Changes +{ + "breached": true, + "check": "dependency-size", + "message": "## šŸ“Š Dependency Size Changes > [!WARNING] > This PR adds 23.6 MB of new dependencies, which exceeds the threshold of 1 kB. @@ -56,7 +60,7 @@ exports[`scanForDependencySize > should report new dependencies exceeding the th | typescript@5.9.3 | 23.6 MB | **Total size change:** 23.6 MB", -] +} `; exports[`scanForDependencySize > should report new dependencies exceeding the threshold 2`] = ` @@ -74,8 +78,10 @@ exports[`scanForDependencySize > should report new dependencies exceeding the th `; exports[`scanForDependencySize > should report removals when threshold is -1 1`] = ` -[ - "## šŸ“Š Dependency Size Changes +{ + "breached": false, + "check": "dependency-size", + "message": "## šŸ“Š Dependency Size Changes > [!NOTE] > :tada: This PR removes 27 kB of dependencies. @@ -85,7 +91,7 @@ exports[`scanForDependencySize > should report removals when threshold is -1 1`] | tinyexec@1.0.0 | -27 kB | **Total size change:** -27 kB", -] +} `; exports[`scanForDependencySize > should report removals when threshold is -1 2`] = ` @@ -103,8 +109,10 @@ exports[`scanForDependencySize > should report removals when threshold is -1 2`] `; exports[`scanForDependencySize > should report upgrades on one line 1`] = ` -[ - "## šŸ“Š Dependency Size Changes +{ + "breached": true, + "check": "dependency-size", + "message": "## šŸ“Š Dependency Size Changes > [!WARNING] > This PR adds 137.8 kB of new dependencies, which exceeds the threshold of 1 B. @@ -114,7 +122,7 @@ exports[`scanForDependencySize > should report upgrades on one line 1`] = ` | chai@5.0.2 → chai@5.0.3 | 137.8 kB | **Total size change:** 137.8 kB", -] +} `; exports[`scanForDependencySize > should report upgrades on one line 2`] = ` diff --git a/test/checks/__snapshots__/duplicates_test.ts.snap b/test/checks/__snapshots__/duplicates_test.ts.snap index 4d4f3eb..302afdb 100644 --- a/test/checks/__snapshots__/duplicates_test.ts.snap +++ b/test/checks/__snapshots__/duplicates_test.ts.snap @@ -1,37 +1,43 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`scanForDuplicates > should only report packages with more versions than the base 1`] = ` -[ - "## āš ļø New Duplicate Dependencies (found: 1, threshold: 1) +{ + "breached": true, + "check": "duplicates", + "message": "## āš ļø New Duplicate Dependencies (found: 1, threshold: 1) | šŸ“¦ Package | šŸ“‹ Versions | | --- | --- | | package-a |
2 versions
  • root-package@1.0.0
    • **package-a@1.0.0**

  • root-package@1.0.0
    • package-b@3.0.0
      • **package-a@1.1.0**

| šŸ’” To find out what depends on a specific package, run: \`npm ls example-package\`", -] +} `; exports[`scanForDuplicates > should report duplicates when threshold is exceeded 1`] = ` -[ - "## āš ļø New Duplicate Dependencies (found: 1, threshold: 1) +{ + "breached": true, + "check": "duplicates", + "message": "## āš ļø New Duplicate Dependencies (found: 1, threshold: 1) | šŸ“¦ Package | šŸ“‹ Versions | | --- | --- | | package-a |
2 versions
  • root-package@1.0.0
    • **package-a@1.0.0**

  • root-package@1.0.0
    • package-b@2.0.0
      • **package-a@1.1.0**

| šŸ’” To find out what depends on a specific package, run: \`npm ls example-package\`", -] +} `; exports[`scanForDuplicates > should truncate long parent paths in the report 1`] = ` -[ - "## āš ļø New Duplicate Dependencies (found: 1, threshold: 1) +{ + "breached": true, + "check": "duplicates", + "message": "## āš ļø New Duplicate Dependencies (found: 1, threshold: 1) | šŸ“¦ Package | šŸ“‹ Versions | | --- | --- | | package-a |
2 versions
  • root-package@1.0.0
    • **package-a@1.0.0**

  • root-package@1.0.0
    • package-0@1.0.0
      • ...
        • package-18@1.0.0
          • package-19@1.0.0
            • **package-a@1.1.0**

| šŸ’” To find out what depends on a specific package, run: \`npm ls example-package\`", -] +} `; diff --git a/test/checks/bundle-size_test.ts b/test/checks/bundle-size_test.ts index a9a691e..d61b366 100644 --- a/test/checks/bundle-size_test.ts +++ b/test/checks/bundle-size_test.ts @@ -13,119 +13,107 @@ function makePack(packageName: string, size: number): PackInfo { describe('scanForBundleSize', () => { it('should do nothing when no packs are provided', async () => { - const messages: string[] = []; - await scanForBundleSize(messages, [], [], 50000); + const result = await scanForBundleSize([], [], 50000); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should report no bundle size change when diff is 0', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 100000)]; const sourcePacks = [makePack('my-package', 100000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, 50000); + const result = await scanForBundleSize(basePacks, sourcePacks, 50000); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should report no bundle size change with threshold=-1 when diff is 0', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 100000)]; const sourcePacks = [makePack('my-package', 100000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, -1); + const result = await scanForBundleSize(basePacks, sourcePacks, -1); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should not report anything when diff is 0 and threshold is not -1', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 100000)]; const sourcePacks = [makePack('my-package', 100000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, 50000); + const result = await scanForBundleSize(basePacks, sourcePacks, 50000); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should warn about size increase exceeding threshold', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 100000)]; const sourcePacks = [makePack('my-package', 200000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, 50000); + const result = await scanForBundleSize(basePacks, sourcePacks, 50000); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should not warn about size increase below threshold', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 100000)]; const sourcePacks = [makePack('my-package', 120000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, 50000); + const result = await scanForBundleSize(basePacks, sourcePacks, 50000); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should warn about an increase regardless of other packages decreasing', async () => { - const messages: string[] = []; const basePacks = [makePack('pkg-a', 200000), makePack('pkg-b', 50000)]; const sourcePacks = [makePack('pkg-a', 100000), makePack('pkg-b', 150000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, 50000); + const result = await scanForBundleSize(basePacks, sourcePacks, 50000); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should report size decrease when threshold is -1', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 200000)]; const sourcePacks = [makePack('my-package', 100000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, -1); + const result = await scanForBundleSize(basePacks, sourcePacks, -1); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should show both decreases and increases when threshold is -1', async () => { - const messages: string[] = []; const basePacks = [makePack('pkg-a', 200000), makePack('pkg-b', 50000)]; const sourcePacks = [makePack('pkg-a', 100000), makePack('pkg-b', 150000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, -1); + const result = await scanForBundleSize(basePacks, sourcePacks, -1); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should show only increases when threshold is -1 and no decreases', async () => { - const messages: string[] = []; const basePacks = [makePack('my-package', 100000)]; const sourcePacks = [makePack('my-package', 200000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, -1); + const result = await scanForBundleSize(basePacks, sourcePacks, -1); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should show new packages when threshold is -1', async () => { - const messages: string[] = []; const basePacks: PackInfo[] = []; const sourcePacks = [makePack('new-package', 50000)]; - await scanForBundleSize(messages, basePacks, sourcePacks, -1); + const result = await scanForBundleSize(basePacks, sourcePacks, -1); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should show removed packages when threshold is -1', async () => { - const messages: string[] = []; const basePacks = [makePack('old-package', 50000)]; const sourcePacks: PackInfo[] = []; - await scanForBundleSize(messages, basePacks, sourcePacks, -1); + const result = await scanForBundleSize(basePacks, sourcePacks, -1); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); }); diff --git a/test/checks/dependency-size_test.ts b/test/checks/dependency-size_test.ts index ebe562c..45dc048 100644 --- a/test/checks/dependency-size_test.ts +++ b/test/checks/dependency-size_test.ts @@ -75,13 +75,11 @@ describe('scanForDependencySize', () => { }); it('should do nothing if no dependency changes', async () => { - const messages: string[] = []; const threshold = 1; const {currentDeps, baseDeps, currentLockFile, baseLockFile} = createMockObjects({}, {}); - await scanForDependencySize( - messages, + const result = await scanForDependencySize( threshold, currentDeps, baseDeps, @@ -89,11 +87,10 @@ describe('scanForDependencySize', () => { baseLockFile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should report new dependencies exceeding the threshold', async () => { - const messages: string[] = []; const threshold = 1000; const {currentDeps, baseDeps, currentLockFile, baseLockFile} = createMockObjects( @@ -103,8 +100,7 @@ describe('scanForDependencySize', () => { } ); - await scanForDependencySize( - messages, + const result = await scanForDependencySize( threshold, currentDeps, baseDeps, @@ -112,12 +108,11 @@ describe('scanForDependencySize', () => { baseLockFile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); expect(coreLogs).toMatchSnapshot(); }); it('should report removals when threshold is -1', async () => { - const messages: string[] = []; const threshold = -1; const {currentDeps, baseDeps, currentLockFile, baseLockFile} = createMockObjects( @@ -127,8 +122,7 @@ describe('scanForDependencySize', () => { {} ); - await scanForDependencySize( - messages, + const result = await scanForDependencySize( threshold, currentDeps, baseDeps, @@ -136,12 +130,11 @@ describe('scanForDependencySize', () => { baseLockFile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); expect(coreLogs).toMatchSnapshot(); }); it('should not report changes below the threshold', async () => { - const messages: string[] = []; const threshold = 50_000; const {currentDeps, baseDeps, currentLockFile, baseLockFile} = createMockObjects( @@ -151,8 +144,7 @@ describe('scanForDependencySize', () => { } ); - await scanForDependencySize( - messages, + const result = await scanForDependencySize( threshold, currentDeps, baseDeps, @@ -160,12 +152,11 @@ describe('scanForDependencySize', () => { baseLockFile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); expect(coreLogs).toMatchSnapshot(); }); it('should report upgrades on one line', async () => { - const messages: string[] = []; const threshold = 1; const {currentDeps, baseDeps, currentLockFile, baseLockFile} = createMockObjects( @@ -177,8 +168,7 @@ describe('scanForDependencySize', () => { } ); - await scanForDependencySize( - messages, + const result = await scanForDependencySize( threshold, currentDeps, baseDeps, @@ -186,12 +176,11 @@ describe('scanForDependencySize', () => { baseLockFile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); expect(coreLogs).toMatchSnapshot(); }); it('should report negative upgrades on one line', async () => { - const messages: string[] = []; const threshold = -1; const {currentDeps, baseDeps, currentLockFile, baseLockFile} = createMockObjects( @@ -203,8 +192,7 @@ describe('scanForDependencySize', () => { } ); - await scanForDependencySize( - messages, + const result = await scanForDependencySize( threshold, currentDeps, baseDeps, @@ -212,7 +200,7 @@ describe('scanForDependencySize', () => { baseLockFile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); expect(coreLogs).toMatchSnapshot(); }); }); diff --git a/test/checks/duplicates_test.ts b/test/checks/duplicates_test.ts index 082baa7..a25c374 100644 --- a/test/checks/duplicates_test.ts +++ b/test/checks/duplicates_test.ts @@ -4,7 +4,6 @@ import type {ParsedLockFile, ParsedDependency} from 'lockparse'; describe('scanForDuplicates', () => { it('should do nothing if no duplicates are found', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0'])], @@ -24,8 +23,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, new Map(), @@ -33,11 +31,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should report duplicates when threshold is exceeded', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.1.0'])], @@ -81,8 +78,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, new Map(), @@ -90,11 +86,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should do nothing when duplicates are below threshold', () => { - const messages: string[] = []; const threshold = 2; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.1.0'])], @@ -138,8 +133,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, new Map(), @@ -147,11 +141,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should truncate long parent paths in the report', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.1.0'])] @@ -202,8 +195,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, new Map(), @@ -211,11 +203,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); it('should not report duplicates which already exist in the base', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.1.0'])] @@ -237,8 +228,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, baseDependencyMap, @@ -246,11 +236,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should not report duplicates when the version count is unchanged', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.2.0'])] @@ -272,8 +261,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, baseDependencyMap, @@ -281,11 +269,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should not report duplicates when versions are removed', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.1.0'])] @@ -307,8 +294,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, baseDependencyMap, @@ -316,11 +302,10 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should only report packages with more versions than the base', () => { - const messages: string[] = []; const threshold = 1; const dependencyMap = new Map>([ ['package-a', new Set(['1.0.0', '1.1.0'])], @@ -384,8 +369,7 @@ describe('scanForDuplicates', () => { } }; - scanForDuplicates( - messages, + const result = scanForDuplicates( threshold, dependencyMap, baseDependencyMap, @@ -393,6 +377,6 @@ describe('scanForDuplicates', () => { lockfile ); - expect(messages).toMatchSnapshot(); + expect(result).toMatchSnapshot(); }); }); diff --git a/test/checks/install-scripts_test.ts b/test/checks/install-scripts_test.ts index fde1fa0..dbe8bd0 100644 --- a/test/checks/install-scripts_test.ts +++ b/test/checks/install-scripts_test.ts @@ -22,15 +22,14 @@ describe('scanForInstallScripts', () => { createMeta('pkg-new', '1.0.0', {postinstall: 'node install.js'}) ); - const messages: string[] = []; const baseDeps = new Map>(); const currentDeps = new Map([['pkg-new', new Set(['1.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(1); - expect(messages[0]).toContain('## āš ļø Install Scripts Added'); - expect(messages[0]).toContain( + expect(result).toBeDefined(); + expect(result?.message).toContain('## āš ļø Install Scripts Added'); + expect(result?.message).toContain( '| pkg-new@1.0.0 | New package | `postinstall` |' ); }); @@ -45,14 +44,13 @@ describe('scanForInstallScripts', () => { }) ); - const messages: string[] = []; const baseDeps = new Map([['pkg-upgrade', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-upgrade', new Set(['2.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(1); - expect(messages[0]).toContain( + expect(result).toBeDefined(); + expect(result?.message).toContain( '| pkg-upgrade@2.0.0 | Upgraded | `install`, `postinstall` |' ); }); @@ -70,14 +68,13 @@ describe('scanForInstallScripts', () => { }) ); - const messages: string[] = []; const baseDeps = new Map([['pkg-added-script', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-added-script', new Set(['2.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(1); - expect(messages[0]).toContain( + expect(result).toBeDefined(); + expect(result?.message).toContain( '| pkg-added-script@2.0.0 | Upgraded | `preinstall` |' ); }); @@ -92,13 +89,12 @@ describe('scanForInstallScripts', () => { createMeta('pkg-existing', '2.0.0', {postinstall: 'node install.js'}) ); - const messages: string[] = []; const baseDeps = new Map([['pkg-existing', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-existing', new Set(['2.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should ignore non-install lifecycle scripts', async () => { @@ -111,25 +107,23 @@ describe('scanForInstallScripts', () => { }) ); - const messages: string[] = []; const baseDeps = new Map>(); const currentDeps = new Map([['pkg-other-scripts', new Set(['1.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should skip packages with no metadata', async () => { metaCache.set('pkg-missing@1.0.0', null); - const messages: string[] = []; const baseDeps = new Map>(); const currentDeps = new Map([['pkg-missing', new Set(['1.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should not report packages that were not upgraded', async () => { @@ -138,12 +132,11 @@ describe('scanForInstallScripts', () => { createMeta('pkg-unchanged', '1.0.0', {postinstall: 'node install.js'}) ); - const messages: string[] = []; const baseDeps = new Map([['pkg-unchanged', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-unchanged', new Set(['1.0.0'])]]); - await scanForInstallScripts(messages, currentDeps, baseDeps); + const result = await scanForInstallScripts(currentDeps, baseDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); }); diff --git a/test/checks/license_test.ts b/test/checks/license_test.ts index 2eca09c..5a62d61 100644 --- a/test/checks/license_test.ts +++ b/test/checks/license_test.ts @@ -20,53 +20,49 @@ describe('scanForLicenses', () => { metaCache.set('pkg-a@1.0.0', createMeta('pkg-a', '1.0.0', 'MIT')); metaCache.set('pkg-a@2.0.0', createMeta('pkg-a', '2.0.0', 'GPL-3.0')); - const messages: string[] = []; const baseDeps = new Map([['pkg-a', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-a', new Set(['2.0.0'])]]); - await scanForLicenses(messages, currentDeps, baseDeps); + const result = await scanForLicenses(currentDeps, baseDeps); - expect(messages).toHaveLength(1); - expect(messages[0]).toContain('## āš ļø License Changes'); - expect(messages[0]).toContain('| pkg-a@2.0.0 | MIT | GPL-3.0 |'); + expect(result).toBeDefined(); + expect(result?.message).toContain('## āš ļø License Changes'); + expect(result?.message).toContain('| pkg-a@2.0.0 | MIT | GPL-3.0 |'); }); it('should not report when license is unchanged or differs by case', async () => { metaCache.set('pkg-a@1.0.0', createMeta('pkg-a', '1.0.0', 'mit')); metaCache.set('pkg-a@2.0.0', createMeta('pkg-a', '2.0.0', 'MIT')); - const messages: string[] = []; const baseDeps = new Map([['pkg-a', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-a', new Set(['2.0.0'])]]); - await scanForLicenses(messages, currentDeps, baseDeps); + const result = await scanForLicenses(currentDeps, baseDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should not report for newly added dependencies that were not in base', async () => { metaCache.set('pkg-a@1.0.0', createMeta('pkg-a', '1.0.0', 'GPL-3.0')); - const messages: string[] = []; const baseDeps = new Map>(); const currentDeps = new Map([['pkg-a', new Set(['1.0.0'])]]); - await scanForLicenses(messages, currentDeps, baseDeps); + const result = await scanForLicenses(currentDeps, baseDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); it('should report Unknown when the new version drops its license field', async () => { metaCache.set('pkg-a@1.0.0', createMeta('pkg-a', '1.0.0', 'MIT')); metaCache.set('pkg-a@2.0.0', createMeta('pkg-a', '2.0.0', undefined)); - const messages: string[] = []; const baseDeps = new Map([['pkg-a', new Set(['1.0.0'])]]); const currentDeps = new Map([['pkg-a', new Set(['2.0.0'])]]); - await scanForLicenses(messages, currentDeps, baseDeps); + const result = await scanForLicenses(currentDeps, baseDeps); - expect(messages).toHaveLength(1); - expect(messages[0]).toContain('| pkg-a@2.0.0 | MIT | Unknown |'); + expect(result).toBeDefined(); + expect(result?.message).toContain('| pkg-a@2.0.0 | MIT | Unknown |'); }); }); diff --git a/test/checks/replacements_test.ts b/test/checks/replacements_test.ts index 8d57ecf..37c39e6 100644 --- a/test/checks/replacements_test.ts +++ b/test/checks/replacements_test.ts @@ -3,23 +3,21 @@ import {scanForReplacements} from '../../src/checks/replacements.js'; describe('scanForReplacements', () => { it('should report replacement for newly added dependency', () => { - const messages: string[] = []; const baseDeps = new Map(); const currentDeps = new Map([['is-odd', '^3.0.0']]); - scanForReplacements(messages, baseDeps, currentDeps); + const result = scanForReplacements(baseDeps, currentDeps); - expect(messages).toHaveLength(1); - expect(messages[0]).toContain('is-odd'); + expect(result).toBeDefined(); + expect(result?.message).toContain('is-odd'); }); it('should not report replacement if dependency already existed in base', () => { - const messages: string[] = []; const baseDeps = new Map([['is-odd', '^3.0.0']]); const currentDeps = new Map([['is-odd', '^3.0.1']]); - scanForReplacements(messages, baseDeps, currentDeps); + const result = scanForReplacements(baseDeps, currentDeps); - expect(messages).toHaveLength(0); + expect(result).toBeUndefined(); }); }); diff --git a/test/checks/result_test.ts b/test/checks/result_test.ts new file mode 100644 index 0000000..72180d3 --- /dev/null +++ b/test/checks/result_test.ts @@ -0,0 +1,45 @@ +import {describe, expect, it} from 'vitest'; +import { + type CheckResult, + getFailedChecks, + parseFailOn +} from '../../src/checks/result.js'; + +describe('parseFailOn', () => { + it('should return an empty set for an empty input', () => { + expect(parseFailOn('')).toEqual(new Set()); + }); + + it('should parse a comma-separated list of checks', () => { + expect( + parseFailOn('dependency-count, dependency-size ,provenance') + ).toEqual(new Set(['dependency-count', 'dependency-size', 'provenance'])); + }); + + it('should throw on an unknown check', () => { + expect(() => parseFailOn('dependency-count, size')).toThrow( + 'Unknown check "size" in fail-on' + ); + }); +}); + +describe('getFailedChecks', () => { + const results: CheckResult[] = [ + {check: 'dependency-count', message: '', breached: true}, + {check: 'dependency-size', message: '', breached: false}, + {check: 'duplicates', message: '', breached: true} + ]; + + it('should return nothing when fail-on is empty', () => { + expect(getFailedChecks(results, new Set())).toEqual([]); + }); + + it('should only return breached checks listed in fail-on', () => { + expect( + getFailedChecks( + results, + new Set(['dependency-count', 'dependency-size', 'provenance']) + ) + ).toEqual(['dependency-count']); + }); +});