Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<file>" (<reason>)` 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 "<file>" (...)` 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)
Expand Down
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<file>" (<reason>)` 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:
Expand Down
19 changes: 18 additions & 1 deletion bin/svgforge.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
32 changes: 32 additions & 0 deletions lib/report.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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}`));
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
14 changes: 8 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion pnpm-workspace.yaml
Original file line number Diff line number Diff line change
@@ -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
46 changes: 46 additions & 0 deletions test/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 => {
Expand Down
1 change: 1 addition & 0 deletions test/fixtures/invalid.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions test/fixtures/without-dims.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading