summaryrefslogtreecommitdiff
path: root/node_modules/svgo/lib
diff options
context:
space:
mode:
authorlittleblack111 <littleblack11111@gmail.com>2024-01-04 11:07:54 +0800
committerlittleblack111 <littleblack11111@gmail.com>2024-01-04 11:07:54 +0800
commit275f9dc0bdf3e58aa36b800f55f8648fbc55d8af (patch)
tree81c7cf120fb703cfd5e3162f2366033d9fe5c7f8 /node_modules/svgo/lib
parent2b4ab36917baef56c7ce1602966f941be15af785 (diff)
upgrade
Diffstat (limited to 'node_modules/svgo/lib')
-rw-r--r--node_modules/svgo/lib/parser.js6
-rw-r--r--node_modules/svgo/lib/path.js141
-rw-r--r--node_modules/svgo/lib/stringifier.js2
-rw-r--r--node_modules/svgo/lib/style.js59
-rw-r--r--node_modules/svgo/lib/svgo.d.ts4
-rw-r--r--node_modules/svgo/lib/svgo.js4
-rw-r--r--node_modules/svgo/lib/svgo/coa.js68
-rw-r--r--node_modules/svgo/lib/svgo/plugins.js2
-rw-r--r--node_modules/svgo/lib/svgo/tools.js43
-rw-r--r--node_modules/svgo/lib/types.d.ts14
-rw-r--r--node_modules/svgo/lib/xast.js2
11 files changed, 195 insertions, 150 deletions
diff --git a/node_modules/svgo/lib/parser.js b/node_modules/svgo/lib/parser.js
index aeed3f09..4637acf1 100644
--- a/node_modules/svgo/lib/parser.js
+++ b/node_modules/svgo/lib/parser.js
@@ -100,7 +100,7 @@ const parseSvg = (data, from) => {
*/
let current = root;
/**
- * @type {Array<XastParent>}
+ * @type {XastParent[]}
*/
const stack = [root];
@@ -213,7 +213,7 @@ const parseSvg = (data, from) => {
sax.ontext = (text) => {
if (current.type === 'element') {
// prevent trimming of meaningful whitespace inside textual tags
- if (textElems.includes(current.name)) {
+ if (textElems.has(current.name)) {
/**
* @type {XastText}
*/
@@ -249,7 +249,7 @@ const parseSvg = (data, from) => {
e.line + 1,
e.column,
data,
- from
+ from,
);
if (e.message.indexOf('Unexpected end') === -1) {
throw error;
diff --git a/node_modules/svgo/lib/path.js b/node_modules/svgo/lib/path.js
index 1e383dd9..814ee2e3 100644
--- a/node_modules/svgo/lib/path.js
+++ b/node_modules/svgo/lib/path.js
@@ -1,6 +1,6 @@
'use strict';
-const { removeLeadingZero } = require('./svgo/tools');
+const { removeLeadingZero, toFixed } = require('./svgo/tools');
/**
* @typedef {import('./types').PathDataItem} PathDataItem
@@ -135,11 +135,11 @@ const readNumber = (string, cursor) => {
};
/**
- * @type {(string: string) => Array<PathDataItem>}
+ * @type {(string: string) => PathDataItem[]}
*/
const parsePathData = (string) => {
/**
- * @type {Array<PathDataItem>}
+ * @type {PathDataItem[]}
*/
const pathData = [];
/**
@@ -243,15 +243,20 @@ const parsePathData = (string) => {
exports.parsePathData = parsePathData;
/**
- * @type {(number: number, precision?: number) => string}
+ * @type {(number: number, precision?: number) => {
+ * roundedStr: string,
+ * rounded: number
+ * }}
*/
-const stringifyNumber = (number, precision) => {
+const roundAndStringify = (number, precision) => {
if (precision != null) {
- const ratio = 10 ** precision;
- number = Math.round(number * ratio) / ratio;
+ number = toFixed(number, precision);
}
- // remove zero whole from decimal number
- return removeLeadingZero(number);
+
+ return {
+ roundedStr: removeLeadingZero(number),
+ rounded: number,
+ };
};
/**
@@ -267,83 +272,109 @@ const stringifyNumber = (number, precision) => {
*/
const stringifyArgs = (command, args, precision, disableSpaceAfterFlags) => {
let result = '';
- let prev = '';
- for (let i = 0; i < args.length; i += 1) {
- const number = args[i];
- const numberString = stringifyNumber(number, precision);
+ let previous;
+
+ for (let i = 0; i < args.length; i++) {
+ const { roundedStr, rounded } = roundAndStringify(args[i], precision);
if (
disableSpaceAfterFlags &&
(command === 'A' || command === 'a') &&
// consider combined arcs
(i % 7 === 4 || i % 7 === 5)
) {
- result += numberString;
- } else if (i === 0 || numberString.startsWith('-')) {
+ result += roundedStr;
+ } else if (i === 0 || rounded < 0) {
// avoid space before first and negative numbers
- result += numberString;
- } else if (prev.includes('.') && numberString.startsWith('.')) {
+ result += roundedStr;
+ } else if (
+ !Number.isInteger(previous) &&
+ rounded != 0 &&
+ rounded < 1 &&
+ rounded > -1
+ ) {
// remove space before decimal with zero whole
// only when previous number is also decimal
- result += numberString;
+ result += roundedStr;
} else {
- result += ` ${numberString}`;
+ result += ` ${roundedStr}`;
}
- prev = numberString;
+ previous = rounded;
}
+
return result;
};
/**
* @typedef {{
- * pathData: Array<PathDataItem>;
+ * pathData: PathDataItem[];
* precision?: number;
* disableSpaceAfterFlags?: boolean;
* }} StringifyPathDataOptions
*/
/**
- * @type {(options: StringifyPathDataOptions) => string}
+ * @param {StringifyPathDataOptions} options
+ * @returns {string}
*/
const stringifyPathData = ({ pathData, precision, disableSpaceAfterFlags }) => {
- // combine sequence of the same commands
- let combined = [];
- for (let i = 0; i < pathData.length; i += 1) {
+ if (pathData.length === 1) {
+ const { command, args } = pathData[0];
+ return (
+ command + stringifyArgs(command, args, precision, disableSpaceAfterFlags)
+ );
+ }
+
+ let result = '';
+ let prev = { ...pathData[0] };
+
+ // match leading moveto with following lineto
+ if (pathData[1].command === 'L') {
+ prev.command = 'M';
+ } else if (pathData[1].command === 'l') {
+ prev.command = 'm';
+ }
+
+ for (let i = 1; i < pathData.length; i++) {
const { command, args } = pathData[i];
- if (i === 0) {
- combined.push({ command, args });
- } else {
- /**
- * @type {PathDataItem}
- */
- const last = combined[combined.length - 1];
- // match leading moveto with following lineto
- if (i === 1) {
- if (command === 'L') {
- last.command = 'M';
- }
- if (command === 'l') {
- last.command = 'm';
- }
+ if (
+ (prev.command === command &&
+ prev.command !== 'M' &&
+ prev.command !== 'm') ||
+ // combine matching moveto and lineto sequences
+ (prev.command === 'M' && command === 'L') ||
+ (prev.command === 'm' && command === 'l')
+ ) {
+ prev.args = [...prev.args, ...args];
+ if (i === pathData.length - 1) {
+ result +=
+ prev.command +
+ stringifyArgs(
+ prev.command,
+ prev.args,
+ precision,
+ disableSpaceAfterFlags,
+ );
}
- if (
- (last.command === command &&
- last.command !== 'M' &&
- last.command !== 'm') ||
- // combine matching moveto and lineto sequences
- (last.command === 'M' && command === 'L') ||
- (last.command === 'm' && command === 'l')
- ) {
- last.args = [...last.args, ...args];
+ } else {
+ result +=
+ prev.command +
+ stringifyArgs(
+ prev.command,
+ prev.args,
+ precision,
+ disableSpaceAfterFlags,
+ );
+
+ if (i === pathData.length - 1) {
+ result +=
+ command +
+ stringifyArgs(command, args, precision, disableSpaceAfterFlags);
} else {
- combined.push({ command, args });
+ prev = { command, args };
}
}
}
- let result = '';
- for (const { command, args } of combined) {
- result +=
- command + stringifyArgs(command, args, precision, disableSpaceAfterFlags);
- }
+
return result;
};
exports.stringifyPathData = stringifyPathData;
diff --git a/node_modules/svgo/lib/stringifier.js b/node_modules/svgo/lib/stringifier.js
index e50e723c..1a710869 100644
--- a/node_modules/svgo/lib/stringifier.js
+++ b/node_modules/svgo/lib/stringifier.js
@@ -235,7 +235,7 @@ const stringifyElement = (node, config, state) => {
tagCloseStart = defaults.tagCloseStart;
tagCloseEnd = defaults.tagCloseEnd;
openIndent = '';
- } else if (textElems.includes(node.name)) {
+ } else if (textElems.has(node.name)) {
tagOpenEnd = defaults.tagOpenEnd;
tagCloseStart = defaults.tagCloseStart;
closeIndent = '';
diff --git a/node_modules/svgo/lib/style.js b/node_modules/svgo/lib/style.js
index 29e4a538..0e62afb9 100644
--- a/node_modules/svgo/lib/style.js
+++ b/node_modules/svgo/lib/style.js
@@ -16,7 +16,6 @@
const csstree = require('css-tree');
const csswhat = require('css-what');
const {
- // @ts-ignore internal api
syntax: { specificity },
} = require('csso');
const { visit, matches } = require('./xast.js');
@@ -34,7 +33,7 @@ const csstreeWalkSkip = csstree.walk.skip;
*/
const parseRule = (ruleNode, dynamic) => {
/**
- * @type {Array<StylesheetDeclaration>}
+ * @type {StylesheetDeclaration[]}
*/
const declarations = [];
// collect declarations
@@ -74,10 +73,10 @@ const parseRule = (ruleNode, dynamic) => {
};
/**
- * @type {(css: string, dynamic: boolean) => Array<StylesheetRule>}
+ * @type {(css: string, dynamic: boolean) => StylesheetRule[]}
*/
const parseStylesheet = (css, dynamic) => {
- /** @type {Array<StylesheetRule>} */
+ /** @type {StylesheetRule[]} */
const rules = [];
const ast = csstree.parse(css, {
parseValue: false,
@@ -108,10 +107,10 @@ const parseStylesheet = (css, dynamic) => {
};
/**
- * @type {(css: string) => Array<StylesheetDeclaration>}
+ * @type {(css: string) => StylesheetDeclaration[]}
*/
const parseStyleDeclarations = (css) => {
- /** @type {Array<StylesheetDeclaration>} */
+ /** @type {StylesheetDeclaration[]} */
const declarations = [];
const ast = csstree.parse(css, {
context: 'declarationList',
@@ -130,7 +129,9 @@ const parseStyleDeclarations = (css) => {
};
/**
- * @type {(stylesheet: Stylesheet, node: XastElement) => ComputedStyles}
+ * @param {Stylesheet} stylesheet
+ * @param {XastElement} node
+ * @returns {ComputedStyles}
*/
const computeOwnStyle = (stylesheet, node) => {
/** @type {ComputedStyles} */
@@ -139,7 +140,7 @@ const computeOwnStyle = (stylesheet, node) => {
// collect attributes
for (const [name, value] of Object.entries(node.attributes)) {
- if (attrsGroups.presentation.includes(name)) {
+ if (attrsGroups.presentation.has(name)) {
computedStyle[name] = { type: 'static', inherited: false, value };
importantStyles.set(name, false);
}
@@ -217,29 +218,31 @@ exports.compareSpecificity = compareSpecificity;
* @type {(root: XastRoot) => Stylesheet}
*/
const collectStylesheet = (root) => {
- /** @type {Array<StylesheetRule>} */
+ /** @type {StylesheetRule[]} */
const rules = [];
/** @type {Map<XastElement, XastParent>} */
const parents = new Map();
+
visit(root, {
element: {
enter: (node, parentNode) => {
- // store parents
parents.set(node, parentNode);
- // find and parse all styles
- if (node.name === 'style') {
+
+ if (node.name !== 'style') {
+ return;
+ }
+
+ if (
+ node.attributes.type == null ||
+ node.attributes.type === '' ||
+ node.attributes.type === 'text/css'
+ ) {
const dynamic =
node.attributes.media != null && node.attributes.media !== 'all';
- if (
- node.attributes.type == null ||
- node.attributes.type === '' ||
- node.attributes.type === 'text/css'
- ) {
- const children = node.children;
- for (const child of children) {
- if (child.type === 'text' || child.type === 'cdata') {
- rules.push(...parseStylesheet(child.value, dynamic));
- }
+
+ for (const child of node.children) {
+ if (child.type === 'text' || child.type === 'cdata') {
+ rules.push(...parseStylesheet(child.value, dynamic));
}
}
}
@@ -253,11 +256,12 @@ const collectStylesheet = (root) => {
exports.collectStylesheet = collectStylesheet;
/**
- * @type {(stylesheet: Stylesheet, node: XastElement) => ComputedStyles}
+ * @param {Stylesheet} stylesheet
+ * @param {XastElement} node
+ * @returns {ComputedStyles}
*/
const computeStyle = (stylesheet, node) => {
const { parents } = stylesheet;
- // collect inherited styles
const computedStyles = computeOwnStyle(stylesheet, node);
let parent = parents.get(node);
while (parent != null && parent.type !== 'root') {
@@ -265,9 +269,8 @@ const computeStyle = (stylesheet, node) => {
for (const [name, computed] of Object.entries(inheritedStyles)) {
if (
computedStyles[name] == null &&
- // ignore not inheritable styles
- inheritableAttrs.includes(name) === true &&
- presentationNonInheritableGroupAttrs.includes(name) === false
+ inheritableAttrs.has(name) &&
+ !presentationNonInheritableGroupAttrs.has(name)
) {
computedStyles[name] = { ...computed, inherited: true };
}
@@ -295,7 +298,7 @@ const includesAttrSelector = (
selector,
name,
value = null,
- traversed = false
+ traversed = false,
) => {
const selectors =
typeof selector === 'string'
diff --git a/node_modules/svgo/lib/svgo.d.ts b/node_modules/svgo/lib/svgo.d.ts
index d98d1293..d4e9e3c2 100644
--- a/node_modules/svgo/lib/svgo.d.ts
+++ b/node_modules/svgo/lib/svgo.d.ts
@@ -61,9 +61,9 @@ export declare function optimize(input: string, config?: Config): Output;
*/
export declare function loadConfig(
configFile: string,
- cwd?: string
+ cwd?: string,
): Promise<Config>;
export declare function loadConfig(
configFile?: null,
- cwd?: string
+ cwd?: string,
): Promise<Config | null>;
diff --git a/node_modules/svgo/lib/svgo.js b/node_modules/svgo/lib/svgo.js
index c19c0a40..acb1f72e 100644
--- a/node_modules/svgo/lib/svgo.js
+++ b/node_modules/svgo/lib/svgo.js
@@ -67,7 +67,7 @@ const optimize = (input, config) => {
const plugins = config.plugins || ['preset-default'];
if (!Array.isArray(plugins)) {
throw Error(
- 'malformed config, `plugins` property must be an array.\nSee more info here: https://github.com/svg/svgo#configuration'
+ 'malformed config, `plugins` property must be an array.\nSee more info here: https://github.com/svg/svgo#configuration',
);
}
const resolvedPlugins = plugins
@@ -76,7 +76,7 @@ const optimize = (input, config) => {
if (resolvedPlugins.length < plugins.length) {
console.warn(
- 'Warning: plugins list includes null or undefined elements, these will be ignored.'
+ 'Warning: plugins list includes null or undefined elements, these will be ignored.',
);
}
const globalOverrides = {};
diff --git a/node_modules/svgo/lib/svgo/coa.js b/node_modules/svgo/lib/svgo/coa.js
index c7f2c827..8e638d06 100644
--- a/node_modules/svgo/lib/svgo/coa.js
+++ b/node_modules/svgo/lib/svgo/coa.js
@@ -35,43 +35,43 @@ module.exports = function makeProgram(program) {
.option('-s, --string <STRING>', 'Input SVG data string')
.option(
'-f, --folder <FOLDER>',
- 'Input folder, optimize and rewrite all *.svg files'
+ 'Input folder, optimize and rewrite all *.svg files',
)
.option(
'-o, --output <OUTPUT...>',
- 'Output file or folder (by default the same as the input), "-" for STDOUT'
+ 'Output file or folder (by default the same as the input), "-" for STDOUT',
)
.option(
'-p, --precision <INTEGER>',
- 'Set number of digits in the fractional part, overrides plugins params'
+ 'Set number of digits in the fractional part, overrides plugins params',
)
.option('--config <CONFIG>', 'Custom config file, only .js is supported')
.option(
'--datauri <FORMAT>',
- 'Output as Data URI string (base64), URI encoded (enc) or unencoded (unenc)'
+ 'Output as Data URI string (base64), URI encoded (enc) or unencoded (unenc)',
)
.option(
'--multipass',
- 'Pass over SVGs multiple times to ensure all optimizations are applied'
+ 'Pass over SVGs multiple times to ensure all optimizations are applied',
)
.option('--pretty', 'Make SVG pretty printed')
.option('--indent <INTEGER>', 'Indent number when pretty printing SVGs')
.option(
'--eol <EOL>',
- 'Line break to use when outputting SVG: lf, crlf. If unspecified, uses platform default.'
+ 'Line break to use when outputting SVG: lf, crlf. If unspecified, uses platform default.',
)
.option('--final-newline', 'Ensure SVG ends with a line break')
.option(
'-r, --recursive',
- "Use with '--folder'. Optimizes *.svg files in folders recursively."
+ "Use with '--folder'. Optimizes *.svg files in folders recursively.",
)
.option(
'--exclude <PATTERN...>',
- "Use with '--folder'. Exclude files matching regular expression pattern."
+ "Use with '--folder'. Exclude files matching regular expression pattern.",
)
.option(
'-q, --quiet',
- 'Only output error messages, not regular status messages'
+ 'Only output error messages, not regular status messages',
)
.option('--show-plugins', 'Show available plugins and exit')
// used by picocolors internally
@@ -88,7 +88,7 @@ async function action(args, opts, command) {
const number = Number.parseInt(opts.precision, 10);
if (Number.isNaN(number)) {
console.error(
- "error: option '-p, --precision' argument must be an integer number"
+ "error: option '-p, --precision' argument must be an integer number",
);
process.exit(1);
} else {
@@ -103,7 +103,7 @@ async function action(args, opts, command) {
opts.datauri !== 'unenc'
) {
console.error(
- "error: option '--datauri' must have one of the following values: 'base64', 'enc' or 'unenc'"
+ "error: option '--datauri' must have one of the following values: 'base64', 'enc' or 'unenc'",
);
process.exit(1);
}
@@ -113,7 +113,7 @@ async function action(args, opts, command) {
const number = Number.parseInt(opts.indent, 10);
if (Number.isNaN(number)) {
console.error(
- "error: option '--indent' argument must be an integer number"
+ "error: option '--indent' argument must be an integer number",
);
process.exit(1);
} else {
@@ -123,7 +123,7 @@ async function action(args, opts, command) {
if (opts.eol != null && opts.eol !== 'lf' && opts.eol !== 'crlf') {
console.error(
- "error: option '--eol' must have one of the following values: 'lf' or 'crlf'"
+ "error: option '--eol' must have one of the following values: 'lf' or 'crlf'",
);
process.exit(1);
}
@@ -155,7 +155,7 @@ async function action(args, opts, command) {
var nodeVersion = String(PKG.engines.node).match(/\d*(\.\d+)*/)[0];
if (parseFloat(process.versions.node) < parseFloat(nodeVersion)) {
throw Error(
- `${PKG.name} requires Node.js version ${nodeVersion} or higher.`
+ `${PKG.name} requires Node.js version ${nodeVersion} or higher.`,
);
}
}
@@ -254,16 +254,13 @@ async function action(args, opts, command) {
process.stdin
.on('data', (chunk) => (data += chunk))
.once('end', () =>
- processSVGData(config, { input: 'string' }, data, file).then(
- resolve,
- reject
- )
+ processSVGData(config, null, data, file).then(resolve, reject),
);
});
// file
} else {
await Promise.all(
- input.map((file, n) => optimizeFile(config, file, output[n]))
+ input.map((file, n) => optimizeFile(config, file, output[n])),
);
}
@@ -271,7 +268,7 @@ async function action(args, opts, command) {
} else if (opts.string) {
var data = decodeSVGDatauri(opts.string);
- return processSVGData(config, { input: 'string' }, data, output[0]);
+ return processSVGData(config, null, data, output[0]);
}
}
@@ -311,12 +308,12 @@ function processDirectory(config, dir, files, output) {
optimizeFile(
config,
fileDescription.inputPath,
- fileDescription.outputPath
- )
- )
+ fileDescription.outputPath,
+ ),
+ ),
)
: Promise.reject(
- new Error(`No SVG files have been found in '${dir}' directory.`)
+ new Error(`No SVG files have been found in '${dir}' directory.`),
);
}
@@ -334,7 +331,7 @@ function getFilesDescriptions(config, dir, files, output) {
.filter(
(name) =>
regSVGFile.test(name) &&
- !config.exclude.some((regExclude) => regExclude.test(name))
+ !config.exclude.some((regExclude) => regExclude.test(name)),
)
.map((name) => ({
inputPath: path.resolve(dir, name),
@@ -354,10 +351,10 @@ function getFilesDescriptions(config, dir, files, output) {
config,
subFolderPath,
subFolderFiles,
- subFolderOutput
+ subFolderOutput,
);
})
- .reduce((a, b) => [].concat(a, b), [])
+ .reduce((a, b) => [].concat(a, b), []),
)
: filesInThisFolder;
}
@@ -372,9 +369,8 @@ function getFilesDescriptions(config, dir, files, output) {
*/
function optimizeFile(config, file, output) {
return fs.promises.readFile(file, 'utf8').then(
- (data) =>
- processSVGData(config, { input: 'file', path: file }, data, output, file),
- (error) => checkOptimizeFileError(config, file, output, error)
+ (data) => processSVGData(config, { path: file }, data, output, file),
+ (error) => checkOptimizeFileError(config, file, output, error),
);
}
@@ -423,9 +419,9 @@ function processSVGData(config, info, data, output, input) {
new Error(
error.code === 'ENOTDIR'
? `Error: output '${output}' is not a directory.`
- : error
- )
- )
+ : error,
+ ),
+ ),
);
}
@@ -475,7 +471,7 @@ function printProfitInfo(inBytes, outBytes) {
ui[0],
ui[1](Math.abs(Math.round(profitPercent * 10) / 10) + '%'),
'=',
- Math.round((outBytes / 1024) * 1000) / 1000 + ' KiB'
+ Math.round((outBytes / 1024) * 1000) / 1000 + ' KiB',
);
}
@@ -493,7 +489,7 @@ function checkOptimizeFileError(config, input, output, error) {
return optimizeFolder(config, input, output);
} else if (error.code == 'ENOENT') {
return Promise.reject(
- new Error(`Error: no such file or directory '${error.path}'.`)
+ new Error(`Error: no such file or directory '${error.path}'.`),
);
}
return Promise.reject(error);
@@ -513,7 +509,7 @@ function checkWriteFileError(input, output, data, error) {
return fs.promises.writeFile(
path.resolve(output, path.basename(input)),
data,
- 'utf8'
+ 'utf8',
);
} else {
return Promise.reject(error);
diff --git a/node_modules/svgo/lib/svgo/plugins.js b/node_modules/svgo/lib/svgo/plugins.js
index efeb01b1..10e93e9c 100644
--- a/node_modules/svgo/lib/svgo/plugins.js
+++ b/node_modules/svgo/lib/svgo/plugins.js
@@ -49,7 +49,7 @@ const createPreset = ({ name, plugins }) => {
` name: '${name}',\n` +
` },\n` +
` '${pluginName}'\n` +
- `]\n`
+ `]\n`,
);
}
}
diff --git a/node_modules/svgo/lib/svgo/tools.js b/node_modules/svgo/lib/svgo/tools.js
index 5e6bd69c..2d5269ec 100644
--- a/node_modules/svgo/lib/svgo/tools.js
+++ b/node_modules/svgo/lib/svgo/tools.js
@@ -74,7 +74,7 @@ exports.decodeSVGDatauri = (str) => {
* @example
* [0, -1, .5, .5] → "0-1 .5.5"
*
- * @type {(data: Array<number>, params: CleanupOutDataParams, command?: PathDataCommand) => string}
+ * @type {(data: number[], params: CleanupOutDataParams, command?: PathDataCommand) => string}
*/
exports.cleanupOutData = (data, params, command) => {
let str = '';
@@ -124,23 +124,24 @@ exports.cleanupOutData = (data, params, command) => {
/**
* Remove floating-point numbers leading zero.
*
+ * @param {number} value
+ * @returns {string}
* @example
* 0.5 → .5
- *
- * @example
* -0.5 → -.5
- *
- * @type {(num: number) => string}
*/
-const removeLeadingZero = (num) => {
- var strNum = num.toString();
+const removeLeadingZero = (value) => {
+ const strValue = value.toString();
- if (0 < num && num < 1 && strNum.charAt(0) === '0') {
- strNum = strNum.slice(1);
- } else if (-1 < num && num < 0 && strNum.charAt(1) === '0') {
- strNum = strNum.charAt(0) + strNum.slice(2);
+ if (0 < value && value < 1 && strValue.startsWith('0')) {
+ return strValue.slice(1);
}
- return strNum;
+
+ if (-1 < value && value < 0 && strValue[1] === '0') {
+ return strValue[0] + strValue.slice(2);
+ }
+
+ return strValue;
};
exports.removeLeadingZero = removeLeadingZero;
@@ -161,7 +162,7 @@ const hasScripts = (node) => {
([attrKey, attrValue]) =>
(attrKey === 'href' || attrKey.endsWith(':href')) &&
attrValue != null &&
- attrValue.trimStart().startsWith('javascript:')
+ attrValue.trimStart().startsWith('javascript:'),
);
if (hasJsLinks) {
@@ -204,7 +205,7 @@ exports.includesUrlReference = includesUrlReference;
const findReferences = (attribute, value) => {
const results = [];
- if (referencesProps.includes(attribute)) {
+ if (referencesProps.has(attribute)) {
const matches = value.matchAll(regReferencesUrl);
for (const match of matches) {
results.push(match[2]);
@@ -228,3 +229,17 @@ const findReferences = (attribute, value) => {
return results.map((body) => decodeURI(body));
};
exports.findReferences = findReferences;
+
+/**
+ * Does the same as {@link Number.toFixed} but without casting
+ * the return value to a string.
+ *
+ * @param {number} num
+ * @param {number} precision
+ * @returns {number}
+ */
+const toFixed = (num, precision) => {
+ const pow = 10 ** precision;
+ return Math.round(num * pow) / pow;
+};
+exports.toFixed = toFixed;
diff --git a/node_modules/svgo/lib/types.d.ts b/node_modules/svgo/lib/types.d.ts
index f6260c6a..f61d9f18 100644
--- a/node_modules/svgo/lib/types.d.ts
+++ b/node_modules/svgo/lib/types.d.ts
@@ -31,7 +31,7 @@ export type XastElement = {
type: 'element';
name: string;
attributes: Record<string, string>;
- children: Array<XastChild>;
+ children: XastChild[];
};
export type XastChild =
@@ -44,7 +44,7 @@ export type XastChild =
export type XastRoot = {
type: 'root';
- children: Array<XastChild>;
+ children: XastChild[];
};
export type XastParent = XastRoot | XastElement;
@@ -108,10 +108,10 @@ export type PluginInfo = {
export type Plugin<Params> = (
root: XastRoot,
params: Params,
- info: PluginInfo
+ info: PluginInfo,
) => null | Visitor;
-export type Specificity = [number, number, number, number];
+export type Specificity = [number, number, number];
export type StylesheetDeclaration = {
name: string;
@@ -123,11 +123,11 @@ export type StylesheetRule = {
dynamic: boolean;
selector: string;
specificity: Specificity;
- declarations: Array<StylesheetDeclaration>;
+ declarations: StylesheetDeclaration[];
};
export type Stylesheet = {
- rules: Array<StylesheetRule>;
+ rules: StylesheetRule[];
parents: Map<XastElement, XastParent>;
};
@@ -168,7 +168,7 @@ export type PathDataCommand =
export type PathDataItem = {
command: PathDataCommand;
- args: Array<number>;
+ args: number[];
};
export type DataUri = 'base64' | 'enc' | 'unenc';
diff --git a/node_modules/svgo/lib/xast.js b/node_modules/svgo/lib/xast.js
index 7f14e2a8..9dca9646 100644
--- a/node_modules/svgo/lib/xast.js
+++ b/node_modules/svgo/lib/xast.js
@@ -16,7 +16,7 @@ const cssSelectOptions = {
};
/**
- * @type {(node: XastNode, selector: string) => Array<XastChild>}
+ * @type {(node: XastNode, selector: string) => XastChild[]}
*/
const querySelectorAll = (node, selector) => {
return selectAll(selector, node, cssSelectOptions);