diff --git a/CHANGELOG.md b/CHANGELOG.md index 53345bc..922ec27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Added + +* Skipped shapes are surfaced consistently. Every shape that cannot be processed is written + to `stderr` immediately as `Skipping "" ()` and counted on an extra + `skipped …` line in the end-of-run summary: + + * **Invalid SVG/XML** is reported with the actual parser reason — e.g. + `Invalid SVG file (Opening and ending tag mismatch: "rect" != "svg")` — instead of + xmldom's `Reporting fatalError … caused …` boilerplate. The raw `[xmldom fatalError]` + console noise is gone. + * **SVGs without a determinable size** when the optional `@resvg/resvg-js` dimension + fallback is missing (see below) are counted as `… without dimensions`. + +* The run summary reports whether the `@resvg/resvg-js` dimension-fallback package is + installed (`resvg available` vs. `resvg not installed`). It is only needed for + the unusual case of an SVG without a `viewBox` or `width`/`height`: such a shape is + skipped with an immediate **warning** on `stderr` — `Skipping "" (...)` carrying + the install command (`npm install @resvg/resvg-js`) — no `NaN` viewBox values are + emitted, and the summary ends with that install recommendation. + ## 3.0.0 — Vento-based sprite generation ### Changed (breaking) diff --git a/README.md b/README.md index 5fe7e6e..d1335df 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,35 @@ svgforge [options] files Run `svgforge --help` to get a full list of all available options, or consult the [command line reference](docs/command-line.md). +After each run the CLI prints a compact summary to `stderr`: processed shapes, active modes, +written files and elapsed time. It also reports whether the +[`@resvg/resvg-js`](https://www.npmjs.com/package/@resvg/resvg-js) dimension fallback — only +used for the unusual case of SVGs without a `viewBox` or `width`/`height` — is installed: + +```text +shapes 42 processed +modes view (example: yes) +resvg available +output 3 files → out +elapsed 0.51s (concurrency 4) +``` + +Skipped shapes — files that could not be processed, e.g. invalid SVG/XML, or SVGs without +a determinable size when the fallback is missing — never end up in the sprite. Every skip is +printed immediately as `Skipping "" ()` and counted on an extra summary line: + +```text +shapes 3 processed +skipped 1 (1 failed) +modes symbol (inline: no, example: no) +``` + +When the `@resvg/resvg-js` package is missing and the fallback is needed for an SVG without a +`viewBox` or `width`/`height`, such a shape is skipped as well: the summary shows +`resvg not installed`, the skip is counted as `without dimensions`, no invalid `NaN` +viewBox values are produced, and the summary ends with the recommendation +`npm install @resvg/resvg-js` to enable the fallback. + ### Examples Create a `view` sprite of all SVG files in `assets/` and write the result — along with an example HTML document — to the `out/` directory: diff --git a/bin/svgforge.js b/bin/svgforge.js index 1dbd0d2..a888323 100755 --- a/bin/svgforge.js +++ b/bin/svgforge.js @@ -19,7 +19,12 @@ import {fileURLToPath} from 'node:url'; import {load} from 'js-yaml'; import yargs from 'yargs'; import SVGSpriter from '@svgforge/svgforge'; -import {deepMerge, isObject, zipObject} from '@svgforge/svgforge/utils'; +import { + deepMerge, + isObject, + zipObject, + isResvgAvailable, +} from '@svgforge/svgforge/utils'; import {createProgressBar} from '../lib/progress.js'; import {printSummary} from '../lib/report.js'; @@ -554,6 +559,14 @@ async function main() { // while they are still being added. const progressBar = createProgressBar(spriter, config.quiet); + // Report skipped shapes as they happen — e.g. SVGs without dimensions when + // the optional `@resvg/resvg-js` fallback is not installed, or files that are + // not valid SVG/XML. The summary counts them and, for missing dimensions, + // ends with the install recommendation. + spriter.on('shape-skipped', ({file, error}) => { + process.stderr.write(`Skipping "${file}" (${error.message})\n`); + }); + // Glob (>= 9, incl. fs.globSync) returns paths without the "./" segment, so // the base directory marker has to be detected on the original pattern. A // literal "/./" segment marks the directory from which shape ID traversal @@ -614,6 +627,10 @@ async function main() { dest: config.dest ?? '.', elapsedMs: Date.now() - startedAt, concurrency: spriter._limit, + resvg: isResvgAvailable(), + dimensionSkipped: spriter._dimensionSkipped ?? 0, + errorSkipped: spriter._errorSkipped ?? 0, + cliVersion: version, }); } catch (error) { console.error(error); diff --git a/lib/report.js b/lib/report.js index 2cfb029..5d6c0ed 100644 --- a/lib/report.js +++ b/lib/report.js @@ -61,6 +61,10 @@ function describeMode(mode, modeConfig) { @param {string} stats.dest Main output directory @param {number} stats.elapsedMs Elapsed run time in milliseconds @param {number} [stats.concurrency] Maximum number of concurrently processed shapes + @param {boolean} [stats.resvg] Whether the optional `@resvg/resvg-js` dimension fallback is available + @param {number} [stats.dimensionSkipped] Number of shapes skipped because their dimensions could not be calculated + @param {number} [stats.errorSkipped] Number of shapes skipped because they could not be processed + @param {string} [stats.cliVersion] Version of the CLI itself, appended to the summary @returns {string[]} Summary lines */ export function formatSummary(stats) { @@ -71,11 +75,39 @@ export function formatSummary(stats) { ? ` (concurrency ${stats.concurrency})` : ''; + // When shapes were skipped because the dimension fallback is unavailable, + // finish with the install recommendation. + const tip = !stats.resvg && stats.dimensionSkipped > 0 + ? ['tip', 'npm install @resvg/resvg-js (enables the dimension fallback)'] + : undefined; + + // `processed` counts every added input, including shapes that were dropped + // during processing, so the skipped ones get their own line to stay visible. + const dimensionSkipped = stats.dimensionSkipped ?? 0; + const errorSkipped = stats.errorSkipped ?? 0; + const skippedParts = [ + errorSkipped > 0 ? `${errorSkipped} failed` : undefined, + dimensionSkipped > 0 ? `${dimensionSkipped} without dimensions` : undefined, + ].filter(Boolean); + const skippedRow = skippedParts.length > 0 + ? [['skipped', `${dimensionSkipped + errorSkipped} (${skippedParts.join(', ')})`]] + : []; + + // The CLI version identifies the tool that produced the output; printed + // before the tip so an actionable recommendation always closes the summary. + const versionRow = stats.cliVersion + ? [['version', `svgforge-cli ${stats.cliVersion}`]] + : []; + const entries = [ ['shapes', `${stats.processed} processed${excluded}`], + ...skippedRow, ['modes', modes.length > 0 ? modes.join(', ') : 'none'], + ['resvg', stats.resvg ? 'available' : 'not installed'], ['output', `${stats.files} file${stats.files === 1 ? '' : 's'} → ${stats.dest}`], ['elapsed', `${(stats.elapsedMs / 1000).toFixed(2)}s${concurrency}`], + ...versionRow, + ...(tip ? [tip] : []), ]; return entries.map(([label, value]) => fit(`${label.padEnd(LABEL_WIDTH)}${value}`)); diff --git a/package.json b/package.json index 6cb0867..fee91d9 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "test:coverage": "mkdir -p coverage && node --test --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info" }, "dependencies": { - "@svgforge/svgforge": "^3.0.0", + "@svgforge/svgforge": "^3.1.0", "js-yaml": "^5.4.3", "vinyl": "^3.0.1", "yargs": "^18.2.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b2dc6..0e80138 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,7 +1,7 @@ lockfileVersion: '9.0' settings: - autoInstallPeers: true + autoInstallPeers: false excludeLinksFromLockfile: false importers: @@ -9,8 +9,8 @@ importers: .: dependencies: '@svgforge/svgforge': - specifier: ^3.0.0 - version: 3.0.0 + specifier: ^3.1.0 + version: 3.1.0(@resvg/resvg-js@2.6.2) js-yaml: specifier: ^5.4.3 version: 5.4.3 @@ -307,9 +307,11 @@ packages: peerDependencies: eslint: ^9.0.0 || ^10.0.0 - '@svgforge/svgforge@3.0.0': - resolution: {integrity: sha512-WjtHoZ4xEHXL5VpNA0hCRAH89WA58sKFeJTiN3I5TljQ5TCw1Rj3nAjR0elOJqyAp/RLVmg6rEY9f9rBhWLoZg==} + '@svgforge/svgforge@3.1.0': + resolution: {integrity: sha512-epW+Dpt+NfZBZUvi1xr+hrTEIZBlX3klHKKQQdPunRD4ayMKyjGtYmNIZvPZNIJtfcSguICyZZojOQ5xUhVsog==} engines: {node: '>=24'} + peerDependencies: + '@resvg/resvg-js': ^2.6.2 '@tybys/wasm-util@0.10.4': resolution: {integrity: sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==} @@ -2169,7 +2171,7 @@ snapshots: estraverse: 5.3.0 picomatch: 4.0.7 - '@svgforge/svgforge@3.0.0': + '@svgforge/svgforge@3.1.0(@resvg/resvg-js@2.6.2)': dependencies: '@resvg/resvg-js': 2.6.2 '@xmldom/xmldom': 0.9.12 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index b660724..d1eae43 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,4 +1,8 @@ allowBuilds: unrs-resolver: true minimumReleaseAgeExclude: - - '@svgforge/svgforge@3.0.0' + - '@svgforge/svgforge@3.1.0' +peerDependencyRules: + ignoreMissing: + - '@resvg/resvg-js' +autoInstallPeers: false diff --git a/test/cli.test.js b/test/cli.test.js index 48c7649..79e965e 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -45,6 +45,15 @@ describe('svgforge-cli', () => { assert.match(stdout, /\d+\.\d+\.\d+/u); }); + it('reports the CLI version in the end-of-run summary', async () => { + await withTemporaryDir(async dir => { + const dest = path.join(dir, 'out'); + const {stderr} = await execCli(['--symbol', `--dest=${dest}`, ...svgFiles]); + + assert.match(stderr, /^version\s+svgforge-cli \d+\.\d+\.\d+$/mu); + }); + }); + it('prints usage information for --help', async () => { const {stdout} = await execCli(['--help']); assert.match(stdout, /^Usage:/mu); @@ -589,6 +598,43 @@ describe('svgforge-cli', () => { }); }); + describe('dimension fallback without @resvg/resvg-js', () => { + const withoutDims = path.join(fixtureDir, 'without-dims.svg'); + + it('warns with the install hint and skips the shape when the fallback is missing', async () => { + // The warning path only exists while the optional package is not + // installed; the test environment runs the development install without + // it, so the test self-skips if resvg is installed manually. + const {isResvgAvailable} = await import('@svgforge/svgforge/utils'); + if (isResvgAvailable()) { + return; + } + + await withTemporaryDir(async dir => { + const dest = path.join(dir, 'out'); + const {stderr} = await execCli(['--symbol', `--dest=${dest}`, withoutDims]); + + assert.match(stderr, /Skipping "without-dims"/u); + assert.match(stderr, /npm install @resvg\/resvg-js/u); + assert.match(stderr, /tip\s+npm install @resvg\/resvg-js/u); + }); + }); + }); + + describe('invalid SVG input', () => { + const invalid = path.join(fixtureDir, 'invalid.svg'); + + it('reports the skipped file with the parser reason and counts it in the summary', async () => { + await withTemporaryDir(async dir => { + const dest = path.join(dir, 'out'); + const {stderr} = await execCli(['--symbol', `--dest=${dest}`, invalid]); + + assert.match(stderr, /Skipping ".*invalid\.svg" \(Invalid SVG file \(.+/u); + assert.match(stderr, /skipped\s+1 \(1 failed\)/u); + }); + }); + }); + describe('short aliases', () => { it('accepts the short argument syntax', async () => { await withTemporaryDir(async dir => { diff --git a/test/fixtures/invalid.svg b/test/fixtures/invalid.svg new file mode 100644 index 0000000..8dde55e --- /dev/null +++ b/test/fixtures/invalid.svg @@ -0,0 +1 @@ + diff --git a/test/fixtures/without-dims.svg b/test/fixtures/without-dims.svg new file mode 100644 index 0000000..9e1a4fd --- /dev/null +++ b/test/fixtures/without-dims.svg @@ -0,0 +1 @@ + diff --git a/test/report.test.js b/test/report.test.js index 354eec3..24baf90 100644 --- a/test/report.test.js +++ b/test/report.test.js @@ -12,17 +12,33 @@ describe('formatSummary', () => { dest: 'dist/material', elapsedMs: 420, concurrency: 4, + resvg: true, }); assert.deepEqual(lines, [ 'shapes 61 processed', 'modes symbol (inline: no, example: yes)', + 'resvg available', 'output 3 files → dist/material', 'elapsed 0.42s (concurrency 4)', ]); assert.ok(lines.every(line => line.length <= 80), 'all lines within 80 characters'); }); + it('reports the CLI version when it is provided', () => { + const lines = formatSummary({ + processed: 2, + modes: {symbol: {}}, + files: 1, + dest: '.', + elapsedMs: 500, + resvg: true, + cliVersion: '3.1.0', + }); + + assert.equal(lines.at(-1), 'version svgforge-cli 3.1.0'); + }); + it('describes every active mode with its enabled options', () => { const lines = formatSummary({ processed: 8, @@ -39,7 +55,7 @@ describe('formatSummary', () => { assert.equal(lines[1], 'modes view (example: no, render: css), defs (inline: yes, example: yes)'); }); - it('reports excluded input files and a single output file', () => { + it('reports the optional resvg fallback status', () => { const lines = formatSummary({ processed: 5, skipped: 3, @@ -47,10 +63,74 @@ describe('formatSummary', () => { files: 1, dest: '.', elapsedMs: 1000, + resvg: false, }); assert.equal(lines[0], 'shapes 5 processed (3 excluded)'); - assert.equal(lines[2], 'output 1 file → .'); + assert.equal(lines[2], 'resvg not installed'); + }); + + it('appends an install tip when shapes were skipped for missing dimensions', () => { + const lines = formatSummary({ + processed: 2, + skipped: 0, + modes: {symbol: {}}, + files: 1, + dest: '.', + elapsedMs: 500, + resvg: false, + dimensionSkipped: 1, + }); + + assert.equal(lines[1], 'skipped 1 (1 without dimensions)'); + assert.equal(lines[3], 'resvg not installed'); + assert.equal(lines[6], 'tip npm install @resvg/resvg-js (enables the dimension fallback)'); + }); + + it('lists skipped shapes with the reason they were dropped', () => { + const lines = formatSummary({ + processed: 4, + skipped: 0, + modes: {symbol: {}}, + files: 1, + dest: '.', + elapsedMs: 500, + resvg: true, + dimensionSkipped: 1, + errorSkipped: 2, + }); + + assert.equal(lines[0], 'shapes 4 processed'); + assert.equal(lines[1], 'skipped 3 (2 failed, 1 without dimensions)'); + }); + + it('omits the skipped line when nothing was dropped', () => { + const lines = formatSummary({ + processed: 4, + skipped: 0, + modes: {symbol: {}}, + files: 1, + dest: '.', + elapsedMs: 500, + resvg: true, + dimensionSkipped: 0, + errorSkipped: 0, + }); + + assert.equal(lines[1], 'modes symbol (example: no)'); + }); + + it('omits the install tip when no shapes needed the fallback', () => { + const lines = formatSummary({ + processed: 2, + files: 1, + dest: '.', + elapsedMs: 500, + resvg: false, + dimensionSkipped: 0, + }); + + assert.equal(lines.length, 5); }); it('omits unknown modes and an unknown concurrency limit', () => { @@ -62,7 +142,8 @@ describe('formatSummary', () => { }); assert.equal(lines[1], 'modes none'); - assert.equal(lines[3], 'elapsed 0.00s'); + assert.equal(lines[2], 'resvg not installed'); + assert.equal(lines[4], 'elapsed 0.00s'); }); it('cuts overly long lines down to 80 characters', () => { @@ -73,10 +154,11 @@ describe('formatSummary', () => { dest: 'dist/'.repeat(50), elapsedMs: 420, concurrency: 4, + resvg: true, }); assert.ok(lines.every(line => line.length <= 80), 'all lines within 80 characters'); - assert.ok(lines[2].endsWith('…'), 'the cut line is marked with an ellipsis'); + assert.ok(lines[3].endsWith('…'), 'the cut line is marked with an ellipsis'); }); }); @@ -96,9 +178,10 @@ describe('printSummary', () => { dest: 'dist/material', elapsedMs: 420, concurrency: 4, + resvg: true, }, stream); - assert.equal(chunks.length, 4); + assert.equal(chunks.length, 5); assert.ok(chunks.every(chunk => chunk.endsWith('\n')), 'every line is newline terminated'); assert.equal(chunks.join(''), `${formatSummary({ processed: 61, @@ -107,6 +190,7 @@ describe('printSummary', () => { dest: 'dist/material', elapsedMs: 420, concurrency: 4, + resvg: true, }).join('\n')}\n`); }); });