code:
'use strict';

/**
 * @typedef {import('../lib/types').XastElement} XastElement
 */

const { visitSkip } = require('../lib/xast.js');
const { referencesProps } = require('./_collections.js');

exports.type = 'visitor';
exports.name = 'cleanupIDs';
exports.active = true;
exports.description = 'removes unused IDs and minifies used';

const regReferencesUrl = /\burl\(("|')?#(.+?)\1\)/;
const regReferencesHref = /^#(.+?)$/;
const regReferencesBegin = /(\w+)\./;
const generateIDchars = [
  'a',
  'b',
  'c',
  'd',
  'e',
  'f',
  'g',
  'h',
  'i',
  'j',
  'k',
  'l',
  'm',
  'n',
  'o',
  'p',
  'q',
  'r',
  's',
  't',
  'u',
  'v',
  'w',
  'x',
  'y',
  'z',
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
];
const maxIDindex = generateIDchars.length - 1;

/**
 * Check if an ID starts with any one of a list of strings.
 *
 * @type {(string: string, prefixes: Array<string>) => boolean}
 */
const hasStringPrefix = (string, prefixes) => {
  for (const prefix of prefixes) {
    if (string.startsWith(prefix)) {
      return true;
    }
  }
  return false;
};

/**
 * Generate unique minimal ID.
 *
 * @type {(currentID: null | Array<number>) => Array<number>}
 */
const generateID = (currentID) => {
  if (currentID == null) {
    return [0];
  }
  currentID[currentID.length - 1] += 1;
  for (let i = currentID.length - 1; i > 0; i--) {
    if (currentID[i] > maxIDindex) {
      currentID[i] = 0;
      if (currentID[i - 1] !== undefined) {
        currentID[i - 1]++;
      }
    }
  }
  if (currentID[0] > maxIDindex) {
    currentID[0] = 0;
    currentID.unshift(0);
  }
  return currentID;
};

/**
 * Get string from generated ID array.
 *
 * @type {(arr: Array<number>, prefix: string) => string}
 */
const getIDstring = (arr, prefix) => {
  return prefix + arr.map((i) => generateIDchars[i]).join('');
};

/**
 * Remove unused and minify used IDs
 * (only if there are no any <style> or <script>).
 *
 * @author Kir Belevich
 *
 * @type {import('../lib/types').Plugin<{
 *   remove?: boolean,
 *   minify?: boolean,
 *   prefix?: string,
 *   preserve?: Array<string>,
 *   preservePrefixes?: Array<string>,
 *   force?: boolean,
 * }>}
 */
exports.fn = (_root, params) => {
  const {
    remove = true,
    minify = true,
    prefix = '',
    preserve = [],
    preservePrefixes = [],
    force = false,
  } = params;
  const preserveIDs = new Set(
    Array.isArray(preserve) ? preserve : preserve ? [preserve] : []
  );
  const preserveIDPrefixes = Array.isArray(preservePrefixes)
    ? preservePrefixes
    : preservePrefixes
    ? [preservePrefixes]
    : [];
  /**
   * @type {Map<string, XastElement>}
   */
  const nodeById = new Map();
  /**
   * @type {Map<string, Array<{element: XastElement, name: string, value: string }>>}
   */
  const referencesById = new Map();
  let deoptimized = false;

  return {
    element: {
      enter: (node) => {
        if (force == false) {
          // deoptimize if style or script elements are present
          if (
            (node.name === 'style' || node.name === 'script') &&
            node.children.length !== 0
          ) {
            deoptimized = true;
            return;
          }

          // avoid removing IDs if the whole SVG consists only of defs
          if (node.name === 'svg') {
            let hasDefsOnly = true;
            for (const child of node.children) {
              if (child.type !== 'element' || child.name !== 'defs') {
                hasDefsOnly = false;
                break;
              }
            }
            if (hasDefsOnly) {
              return visitSkip;
            }
          }
        }

        for (const [name, value] of Object.entries(node.attributes)) {
          if (name === 'id') {
            // collect all ids
            const id = value;
            if (nodeById.has(id)) {
              delete node.attributes.id; // remove repeated id
            } else {
              nodeById.set(id, node);
            }
          } else {
            // collect all references
            /**
             * @type {null | string}
             */
            let id = null;
            if (referencesProps.includes(name)) {
              const match = value.match(regReferencesUrl);
              if (match != null) {
                id = match[2]; // url() reference
              }
            }
            if (name === 'href' || name.endsWith(':href')) {
              const match = value.match(regReferencesHref);
              if (match != null) {
                id = match[1]; // href reference
              }
            }
            if (name === 'begin') {
              const match = value.match(regReferencesBegin);
              if (match != null) {
                id = match[1]; // href reference
              }
            }
            if (id != null) {
              let refs = referencesById.get(id);
              if (refs == null) {
                refs = [];
                referencesById.set(id, refs);
              }
              refs.push({ element: node, name, value });
            }
          }
        }
      },
    },

    root: {
      exit: () => {
        if (deoptimized) {
          return;
        }
        /**
         * @type {(id: string) => boolean}
         **/
        const isIdPreserved = (id) =>
          preserveIDs.has(id) || hasStringPrefix(id, preserveIDPrefixes);
        /**
         * @type {null | Array<number>}
         */
        let currentID = null;
        for (const [id, refs] of referencesById) {
          const node = nodeById.get(id);
          if (node != null) {
            // replace referenced IDs with the minified ones
            if (minify && isIdPreserved(id) === false) {
              /**
               * @type {null | string}
               */
              let currentIDString = null;
              do {
                currentID = generateID(currentID);
                currentIDString = getIDstring(currentID, prefix);
              } while (isIdPreserved(currentIDString));
              node.attributes.id = currentIDString;
              for (const { element, name, value } of refs) {
                if (value.includes('#')) {
                  // replace id in href and url()
                  element.attributes[name] = value.replace(
                    `#${id}`,
                    `#${currentIDString}`
                  );
                } else {
                  // replace id in begin attribute
                  element.attributes[name] = value.replace(
                    `${id}.`,
                    `${currentIDString}.`
                  );
                }
              }
            }
            // keep referenced node
            nodeById.delete(id);
          }
        }
        // remove non-referenced IDs attributes from elements
        if (remove) {
          for (const [id, node] of nodeById) {
            if (isIdPreserved(id) === false) {
              delete node.attributes.id;
            }
          }
        }
      },
    },
  };
};


code:
'use strict';

const { removeLeadingZero } = require('../lib/svgo/tools.js');

exports.name = 'cleanupListOfValues';
exports.type = 'visitor';
exports.active = false;
exports.description = 'rounds list of values to the fixed precision';

const regNumericValues =
  /^([-+]?\d*\.?\d+([eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/;
const regSeparator = /\s+,?\s*|,\s*/;
const absoluteLengths = {
  // relative to px
  cm: 96 / 2.54,
  mm: 96 / 25.4,
  in: 96,
  pt: 4 / 3,
  pc: 16,
  px: 1,
};

/**
 * Round list of values to the fixed precision.
 *
 * @example
 * <svg viewBox="0 0 200.28423 200.28423" enable-background="new 0 0 200.28423 200.28423">
 *         ⬇
 * <svg viewBox="0 0 200.284 200.284" enable-background="new 0 0 200.284 200.284">
 *
 * <polygon points="208.250977 77.1308594 223.069336 ... "/>
 *         ⬇
 * <polygon points="208.251 77.131 223.069 ... "/>
 *
 * @author kiyopikko
 *
 * @type {import('../lib/types').Plugin<{
 *   floatPrecision?: number,
 *   leadingZero?: boolean,
 *   defaultPx?: boolean,
 *   convertToPx?: boolean
 * }>}
 */
exports.fn = (_root, params) => {
  const {
    floatPrecision = 3,
    leadingZero = true,
    defaultPx = true,
    convertToPx = true,
  } = params;

  /**
   * @type {(lists: string) => string}
   */
  const roundValues = (lists) => {
    const roundedList = [];

    for (const elem of lists.split(regSeparator)) {
      const match = elem.match(regNumericValues);
      const matchNew = elem.match(/new/);

      // if attribute value matches regNumericValues
      if (match) {
        // round it to the fixed precision
        let num = Number(Number(match[1]).toFixed(floatPrecision));
        /**
         * @type {any}
         */
        let matchedUnit = match[3] || '';
        /**
         * @type{'' | keyof typeof absoluteLengths}
         */
        let units = matchedUnit;

        // convert absolute values to pixels
        if (convertToPx && units && units in absoluteLengths) {
          const pxNum = Number(
            (absoluteLengths[units] * Number(match[1])).toFixed(floatPrecision)
          );

          if (pxNum.toString().length < match[0].length) {
            num = pxNum;
            units = 'px';
          }
        }

        // and remove leading zero
        let str;
        if (leadingZero) {
          str = removeLeadingZero(num);
        } else {
          str = num.toString();
        }

        // remove default 'px' units
        if (defaultPx && units === 'px') {
          units = '';
        }

        roundedList.push(str + units);
      }
      // if attribute value is "new"(only enable-background).
      else if (matchNew) {
        roundedList.push('new');
      } else if (elem) {
        roundedList.push(elem);
      }
    }

    return roundedList.join(' ');
  };

  return {
    element: {
      enter: (node) => {
        if (node.attributes.points != null) {
          node.attributes.points = roundValues(node.attributes.points);
        }

        if (node.attributes['enable-background'] != null) {
          node.attributes['enable-background'] = roundValues(
            node.attributes['enable-background']
          );
        }

        if (node.attributes.viewBox != null) {
          node.attributes.viewBox = roundValues(node.attributes.viewBox);
        }

        if (node.attributes['stroke-dasharray'] != null) {
          node.attributes['stroke-dasharray'] = roundValues(
            node.attributes['stroke-dasharray']
          );
        }

        if (node.attributes.dx != null) {
          node.attributes.dx = roundValues(node.attributes.dx);
        }

        if (node.attributes.dy != null) {
          node.attributes.dy = roundValues(node.attributes.dy);
        }

        if (node.attributes.x != null) {
          node.attributes.x = roundValues(node.attributes.x);
        }

        if (node.attributes.y != null) {
          node.attributes.y = roundValues(node.attributes.y);
        }
      },
    },
  };
};

license: mit


code:
'use strict';

const { removeLeadingZero } = require('../lib/svgo/tools');

exports.name = 'cleanupNumericValues';
exports.type = 'visitor';
exports.active = true;
exports.description =
  'rounds numeric values to the fixed precision, removes default ‘px’ units';

const regNumericValues =
  /^([-+]?\d*\.?\d+([eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/;

const absoluteLengths = {
  // relative to px
  cm: 96 / 2.54,
  mm: 96 / 25.4,
  in: 96,
  pt: 4 / 3,
  pc: 16,
  px: 1,
};

/**
 * Round numeric values to the fixed precision,
 * remove default 'px' units.
 *
 * @author Kir Belevich
 *
 * @type {import('../lib/types').Plugin<{
 *   floatPrecision?: number,
 *   leadingZero?: boolean,
 *   defaultPx?: boolean,
 *   convertToPx?: boolean
 * }>}
 */
exports.fn = (_root, params) => {
  const {
    floatPrecision = 3,
    leadingZero = true,
    defaultPx = true,
    convertToPx = true,
  } = params;

  return {
    element: {
      enter: (node) => {
        if (node.attributes.viewBox != null) {
          const nums = node.attributes.viewBox.split(/\s,?\s*|,\s*/g);
          node.attributes.viewBox = nums
            .map((value) => {
              const num = Number(value);
              return Number.isNaN(num)
                ? value
                : Number(num.toFixed(floatPrecision));
            })
            .join(' ');
        }

        for (const [name, value] of Object.entries(node.attributes)) {
          // The `version` attribute is a text string and cannot be rounded
          if (name === 'version') {
            continue;
          }

          const match = value.match(regNumericValues);

          // if attribute value matches regNumericValues
          if (match) {
            // round it to the fixed precision
            let num = Number(Number(match[1]).toFixed(floatPrecision));
            /**
             * @type {any}
             */
            let matchedUnit = match[3] || '';
            /**
             * @type{'' | keyof typeof absoluteLengths}
             */
            let units = matchedUnit;

            // convert absolute values to pixels
            if (convertToPx && units !== '' && units in absoluteLengths) {
              const pxNum = Number(
                (absoluteLengths[units] * Number(match[1])).toFixed(
                  floatPrecision
                )
              );
              if (pxNum.toString().length < match[0].length) {
                num = pxNum;
                units = 'px';
              }
            }

            // and remove leading zero
            let str;
            if (leadingZero) {
              str = removeLeadingZero(num);
            } else {
              str = num.toString();
            }

            // remove default 'px' units
            if (defaultPx && units === 'px') {
              units = '';
            }

            node.attributes[name] = str + units;
          }
        }
      },
    },
  };
};


code:
'use strict';

/**
 * @typedef {import('../lib/types').XastNode} XastNode
 */

const { inheritableAttrs, elemsGroups } = require('./_collections.js');

exports.type = 'visitor';
exports.name = 'collapseGroups';
exports.active = true;
exports.description = 'collapses useless groups';

/**
 * @type {(node: XastNode, name: string) => boolean}
 */
const hasAnimatedAttr = (node, name) => {
  if (node.type === 'element') {
    if (
      elemsGroups.animation.includes(node.name) &&
      node.attributes.attributeName === name
    ) {
      return true;
    }
    for (const child of node.children) {
      if (hasAnimatedAttr(child, name)) {
        return true;
      }
    }
  }
  return false;
};

/**
 * Collapse useless groups.
 *
 * @example
 * <g>
 *     <g attr1="val1">
 *         <path d="..."/>
 *     </g>
 * </g>
 *         ⬇
 * <g>
 *     <g>
 *         <path attr1="val1" d="..."/>
 *     </g>
 * </g>
 *         ⬇
 * <path attr1="val1" d="..."/>
 *
 * @author Kir Belevich
 *
 * @type {import('../lib/types').Plugin<void>}
 */
exports.fn = () => {
  return {
    element: {
      exit: (node, parentNode) => {
        if (parentNode.type === 'root' || parentNode.name === 'switch') {
          return;
        }
        // non-empty groups
        if (node.name !== 'g' || node.children.length === 0) {
          return;
        }

        // move group attibutes to the single child element
        if (
          Object.keys(node.attributes).length !== 0 &&
          node.children.length === 1
        ) {
          const firstChild = node.children[0];
          // TODO untangle this mess
          if (
            firstChild.type === 'element' &&
            firstChild.attributes.id == null &&
            node.attributes.filter == null &&
            (node.attributes.class == null ||
              firstChild.attributes.class == null) &&
            ((node.attributes['clip-path'] == null &&
              node.attributes.mask == null) ||
              (firstChild.name === 'g' &&
                node.attributes.transform == null &&
                firstChild.attributes.transform == null))
          ) {
            for (const [name, value] of Object.entries(node.attributes)) {
              // avoid copying to not conflict with animated attribute
              if (hasAnimatedAttr(firstChild, name)) {
                return;
              }
              if (firstChild.attributes[name] == null) {
                firstChild.attributes[name] = value;
              } else if (name === 'transform') {
                firstChild.attributes[name] =
                  value + ' ' + firstChild.attributes[name];
              } else if (firstChild.attributes[name] === 'inherit') {
                firstChild.attributes[name] = value;
              } else if (
                inheritableAttrs.includes(name) === false &&
                firstChild.attributes[name] !== value
              ) {
                return;
              }
              delete node.attributes[name];
            }
          }
        }

        // collapse groups without attributes
        if (Object.keys(node.attributes).length === 0) {
          // animation elements "add" attributes to group
          // group should be preserved
          for (const child of node.children) {
            if (
              child.type === 'element' &&
              elemsGroups.animation.includes(child.name)
            ) {
              return;
            }
          }
          // replace current node with all its children
          const index = parentNode.children.indexOf(node);
          parentNode.children.splice(index, 1, ...node.children);
          // TODO remove in v3
          for (const child of node.children) {
            // @ts-ignore parentNode is forbidden for public usage
            // and will be moved in v3
            child.parentNode = parentNode;
          }
        }
      },
    },
  };
};


code:
'use strict';

const collections = require('./_collections.js');

exports.type = 'visitor';
exports.name = 'convertColors';
exports.active = true;
exports.description = 'converts colors: rgb() to #rrggbb and #rrggbb to #rgb';

const rNumber = '([+-]?(?:\\d*\\.\\d+|\\d+\\.?)%?)';
const rComma = '\\s*,\\s*';
const regRGB = new RegExp(
  '^rgb\\(\\s*' + rNumber + rComma + rNumber + rComma + rNumber + '\\s*\\)$'
);
const regHEX = /^#(([a-fA-F0-9])\2){3}$/;

/**
 * Convert [r, g, b] to #rrggbb.
 *
 * @see https://gist.github.com/983535
 *
 * @example
 * rgb2hex([255, 255, 255]) // '#ffffff'
 *
 * @author Jed Schmidt
 *
 * @type {(rgb: Array<number>) => string}
 */
const convertRgbToHex = ([r, g, b]) => {
  // combine the octets into a 32-bit integer as: [1][r][g][b]
  const hexNumber =
    // operator precedence is (+) > (<<) > (|)
    ((((256 + // [1][0]
      r) << // [1][r]
      8) | // [1][r][0]
      g) << // [1][r][g]
      8) | // [1][r][g][0]
    b;
  // serialize [1][r][g][b] to a hex string, and
  // remove the 1 to get the number with 0s intact
  return '#' + hexNumber.toString(16).slice(1).toUpperCase();
};

/**
 * Convert different colors formats in element attributes to hex.
 *
 * @see https://www.w3.org/TR/SVG11/types.html#DataTypeColor
 * @see https://www.w3.org/TR/SVG11/single-page.html#types-ColorKeywords
 *
 * @example
 * Convert color name keyword to long hex:
 * fuchsia ➡ #ff00ff
 *
 * Convert rgb() to long hex:
 * rgb(255, 0, 255) ➡ #ff00ff
 * rgb(50%, 100, 100%) ➡ #7f64ff
 *
 * Convert long hex to short hex:
 * #aabbcc ➡ #abc
 *
 * Convert hex to short name
 * #000080 ➡ navy
 *
 * @author Kir Belevich
 *
 * @type {import('../lib/types').Plugin<{
 *   currentColor?: boolean | string | RegExp,
 *   names2hex?: boolean,
 *   rgb2hex?: boolean,
 *   shorthex?: boolean,
 *   shortname?: boolean,
 * }>}
 */
exports.fn = (_root, params) => {
  const {
    currentColor = false,
    names2hex = true,
    rgb2hex = true,
    shorthex = true,
    shortname = true,
  } = params;

  return {
    element: {
      enter: (node) => {
        for (const [name, value] of Object.entries(node.attributes)) {
          if (collections.colorsProps.includes(name)) {
            let val = value;

            // convert colors to currentColor
            if (currentColor) {
              let matched;
              if (typeof currentColor === 'string') {
                matched = val === currentColor;
              } else if (currentColor instanceof RegExp) {
                matched = currentColor.exec(val) != null;
              } else {
                matched = val !== 'none';
              }
              if (matched) {
                val = 'currentColor';
              }
            }

            // convert color name keyword to long hex
            if (names2hex) {
              const colorName = val.toLowerCase();
              if (collections.colorsNames[colorName] != null) {
                val = collections.colorsNames[colorName];
              }
            }

            // convert rgb() to long hex
            if (rgb2hex) {
              let match = val.match(regRGB);
              if (match != null) {
                let nums = match.slice(1, 4).map((m) => {
                  let n;
                  if (m.indexOf('%') > -1) {
                    n = Math.round(parseFloat(m) * 2.55);
                  } else {
                    n = Number(m);
                  }
                  return Math.max(0, Math.min(n, 255));
                });
                val = convertRgbToHex(nums);
              }
            }

            // convert long hex to short hex
            if (shorthex) {
              let match = val.match(regHEX);
              if (match != null) {
                val = '#' + match[0][1] + match[0][3] + match[0][5];
              }
            }

            // convert hex to short name
            if (shortname) {
              const colorName = val.toLowerCase();
              if (collections.colorsShortNames[colorName] != null) {
                val = collections.colorsShortNames[colorName];
              }
            }

            node.attributes[name] = val;
          }
        }
      },
    },
  };
};


code:
'use strict';

exports.name = 'convertEllipseToCircle';
exports.type = 'visitor';
exports.active = true;
exports.description = 'converts non-eccentric <ellipse>s to <circle>s';

/**
 * Converts non-eccentric <ellipse>s to <circle>s.
 *
 * @see https://www.w3.org/TR/SVG11/shapes.html
 *
 * @author Taylor Hunt
 *
 * @type {import('../lib/types').Plugin<void>}
 */
exports.fn = () => {
  return {
    element: {
      enter: (node) => {
        if (node.name === 'ellipse') {
          const rx = node.attributes.rx || '0';
          const ry = node.attributes.ry || '0';
          if (
            rx === ry ||
            rx === 'auto' ||
            ry === 'auto' // SVG2
          ) {
            node.name = 'circle';
            const radius = rx === 'auto' ? ry : rx;
            delete node.attributes.rx;
            delete node.attributes.ry;
            node.attributes.r = radius;
          }
        }
      },
    },
  };
};


code:
'use strict';

const { collectStylesheet, computeStyle } = require('../lib/style.js');
const { pathElems } = require('./_collections.js');
const { path2js, js2path } = require('./_path.js');
const { applyTransforms } = require('./_applyTransforms.js');
const { cleanupOutData } = require('../lib/svgo/tools');

exports.name = 'convertPathData';
exports.type = 'visitor';
exports.active = true;
exports.description =
  'optimizes path data: writes in shorter form, applies transformations';

exports.params = {
  applyTransforms: true,
  applyTransformsStroked: true,
  makeArcs: {
    threshold: 2.5, // coefficient of rounding error
    tolerance: 0.5, // percentage of radius
  },
  straightCurves: true,
  lineShorthands: true,
  curveSmoothShorthands: true,
  floatPrecision: 3,
  transformPrecision: 5,
  removeUseless: true,
  collapseRepeated: true,
  utilizeAbsolute: true,
  leadingZero: true,
  negativeExtraSpace: true,
  noSpaceAfterFlags: false, // a20 60 45 0 1 30 20 → a20 60 45 0130 20
  forceAbsolutePath: false,
};

let roundData;
let precision;
let error;
let arcThreshold;
let arcTolerance;

/**
 * Convert absolute Path to relative,
 * collapse repeated instructions,
 * detect and convert Lineto shorthands,
 * remove useless instructions like "l0,0",
 * trim useless delimiters and leading zeros,
 * decrease accuracy of floating-point numbers.
 *
 * @see https://www.w3.org/TR/SVG11/paths.html#PathData
 *
 * @param {Object} item current iteration item
 * @param {Object} params plugin params
 * @return {Boolean} if false, item will be filtered out
 *
 * @author Kir Belevich
 */
exports.fn = (root, params) => {
  const stylesheet = collectStylesheet(root);
  return {
    element: {
      enter: (node) => {
        if (pathElems.includes(node.name) && node.attributes.d != null) {
          const computedStyle = computeStyle(stylesheet, node);
          precision = params.floatPrecision;
          error =
            precision !== false
              ? +Math.pow(0.1, precision).toFixed(precision)
              : 1e-2;
          roundData = precision > 0 && precision < 20 ? strongRound : round;
          if (params.makeArcs) {
            arcThreshold = params.makeArcs.threshold;
            arcTolerance = params.makeArcs.tolerance;
          }
          const hasMarkerMid = computedStyle['marker-mid'] != null;

          const maybeHasStroke =
            computedStyle.stroke &&
            (computedStyle.stroke.type === 'dynamic' ||
              computedStyle.stroke.value !== 'none');
          const maybeHasLinecap =
            computedStyle['stroke-linecap'] &&
            (computedStyle['stroke-linecap'].type === 'dynamic' ||
              computedStyle['stroke-linecap'].value !== 'butt');
          const maybeHasStrokeAndLinecap = maybeHasStroke && maybeHasLinecap;

          var data = path2js(node);

          // TODO: get rid of functions returns
          if (data.length) {
            if (params.applyTransforms) {
              applyTransforms(node, data, params);
            }

            convertToRelative(data);

            data = filters(data, params, {
              maybeHasStrokeAndLinecap,
              hasMarkerMid,
            });

            if (params.utilizeAbsolute) {
              data = convertToMixed(data, params);
            }

            js2path(node, data, params);
          }
        }
      },
    },
  };
};

/**
 * Convert absolute path data coordinates to relative.
 *
 * @param {Array} path input path data
 * @param {Object} params plugin params
 * @return {Array} output path data
 */
const convertToRelative = (pathData) => {
  let start = [0, 0];
  let cursor = [0, 0];
  let prevCoords = [0, 0];

  for (let i = 0; i < pathData.length; i += 1) {
    const pathItem = pathData[i];
    let { command, args } = pathItem;

    // moveto (x y)
    if (command === 'm') {
      // update start and cursor
      cursor[0] += args[0];
      cursor[1] += args[1];
      start[0] = cursor[0];
      start[1] = cursor[1];
    }
    if (command === 'M') {
      // M → m
      // skip first moveto
      if (i !== 0) {
        command = 'm';
      }
      args[0] -= cursor[0];
      args[1] -= cursor[1];
      // update start and cursor
      cursor[0] += args[0];
      cursor[1] += args[1];
      start[0] = cursor[0];
      start[1] = cursor[1];
    }

    // lineto (x y)
    if (command === 'l') {
      cursor[0] += args[0];
      cursor[1] += args[1];
    }
    if (command === 'L') {
      // L → l
      command = 'l';
      args[0] -= cursor[0];
      args[1] -= cursor[1];
      cursor[0] += args[0];
      cursor[1] += args[1];
    }

    // horizontal lineto (x)
    if (command === 'h') {
      cursor[0] += args[0];
    }
    if (command === 'H') {
      // H → h
      command = 'h';
      args[0] -= cursor[0];
      cursor[0] += args[0];
    }

    // vertical lineto (y)
    if (command === 'v') {
      cursor[1] += args[0];
    }
    if (command === 'V') {
      // V → v
      command = 'v';
      args[0] -= cursor[1];
      cursor[1] += args[0];
    }

    // curveto (x1 y1 x2 y2 x y)
    if (command === 'c') {
      cursor[0] += args[4];
      cursor[1] += args[5];
    }
    if (command === 'C') {
      // C → c
      command = 'c';
      args[0] -= cursor[0];
      args[1] -= cursor[1];
      args[2] -= cursor[0];
      args[3] -= cursor[1];
      args[4] -= cursor[0];
      args[5] -= cursor[1];
      cursor[0] += args[4];
      cursor[1] += args[5];
    }

    // smooth curveto (x2 y2 x y)
    if (command === 's') {
      cursor[0] += args[2];
      cursor[1] += args[3];
    }
    if (command === 'S') {
      // S → s
      command = 's';
      args[0] -= cursor[0];
      args[1] -= cursor[1];
      args[2] -= cursor[0];
      args[3] -= cursor[1];
      cursor[0] += args[2];
      cursor[1] += args[3];
    }

    // quadratic Bézier curveto (x1 y1 x y)
    if (command === 'q') {
      cursor[0] += args[2];
      cursor[1] += args[3];
    }
    if (command === 'Q') {
      // Q → q
      command = 'q';
      args[0] -= cursor[0];
      args[1] -= cursor[1];
      args[2] -= cursor[0];
      args[3] -= cursor[1];
      cursor[0] += args[2];
      cursor[1] += args[3];
    }

    // smooth quadratic Bézier curveto (x y)
    if (command === 't') {
      cursor[0] += args[0];
      cursor[1] += args[1];
    }
    if (command === 'T') {
      // T → t
      command = 't';
      args[0] -= cursor[0];
      args[1] -= cursor[1];
      cursor[0] += args[0];
      cursor[1] += args[1];
    }

    // elliptical arc (rx ry x-axis-rotation large-arc-flag sweep-flag x y)
    if (command === 'a') {
      cursor[0] += args[5];
      cursor[1] += args[6];
    }
    if (command === 'A') {
      // A → a
      command = 'a';
      args[5] -= cursor[0];
      args[6] -= cursor[1];
      cursor[0] += args[5];
      cursor[1] += args[6];
    }

    // closepath
    if (command === 'Z' || command === 'z') {
      // reset cursor
      cursor[0] = start[0];
      cursor[1] = start[1];
    }

    pathItem.command = command;
    pathItem.args = args;
    // store absolute coordinates for later use
    // base should preserve reference from other element
    pathItem.base = prevCoords;
    pathItem.coords = [cursor[0], cursor[1]];
    prevCoords = pathItem.coords;
  }

  return pathData;
};

/**
 * Main filters loop.
 *
 * @param {Array} path input path data
 * @param {Object} params plugin params
 * @return {Array} output path data
 */
function filters(path, params, { maybeHasStrokeAndLinecap, hasMarkerMid }) {
  var stringify = data2Path.bind(null, params),
    relSubpoint = [0, 0],
    pathBase = [0, 0],
    prev = {};

  path = path.filter(function (item, index, path) {
    let command = item.command;
    let data = item.args;
    let next = path[index + 1];

    if (command !== 'Z' && command !== 'z') {
      var sdata = data,
        circle;

      if (command === 's') {
        sdata = [0, 0].concat(data);

        if (command === 'c' || command === 's') {
          var pdata = prev.args,
            n = pdata.length;

          // (-x, -y) of the prev tangent point relative to the current point
          sdata[0] = pdata[n - 2] - pdata[n - 4];
          sdata[1] = pdata[n - 1] - pdata[n - 3];
        }
      }

      // convert curves to arcs if possible
      if (
        params.makeArcs &&
        (command == 'c' || command == 's') &&
        isConvex(sdata) &&
        (circle = findCircle(sdata))
      ) {
        var r = roundData([circle.radius])[0],
          angle = findArcAngle(sdata, circle),
          sweep = sdata[5] * sdata[0] - sdata[4] * sdata[1] > 0 ? 1 : 0,
          arc = {
            command: 'a',
            args: [r, r, 0, 0, sweep, sdata[4], sdata[5]],
            coords: item.coords.slice(),
            base: item.base,
          },
          output = [arc],
          // relative coordinates to adjust the found circle
          relCenter = [
            circle.center[0] - sdata[4],
            circle.center[1] - sdata[5],
          ],
          relCircle = { center: relCenter, radius: circle.radius },
          arcCurves = [item],
          hasPrev = 0,
          suffix = '',
          nextLonghand;

        if (
          (prev.command == 'c' &&
            isConvex(prev.args) &&
            isArcPrev(prev.args, circle)) ||
          (prev.command == 'a' && prev.sdata && isArcPrev(prev.sdata, circle))
        ) {
          arcCurves.unshift(prev);
          arc.base = prev.base;
          arc.args[5] = arc.coords[0] - arc.base[0];
          arc.args[6] = arc.coords[1] - arc.base[1];
          var prevData = prev.command == 'a' ? prev.sdata : prev.args;
          var prevAngle = findArcAngle(prevData, {
            center: [
              prevData[4] + circle.center[0],
              prevData[5] + circle.center[1],
            ],
            radius: circle.radius,
          });
          angle += prevAngle;
          if (angle > Math.PI) arc.args[3] = 1;
          hasPrev = 1;
        }

        // check if next curves are fitting the arc
        for (
          var j = index;
          (next = path[++j]) && ~'cs'.indexOf(next.command);

        ) {
          var nextData = next.args;
          if (next.command == 's') {
            nextLonghand = makeLonghand(
              { command: 's', args: next.args.slice() },
              path[j - 1].args
            );
            nextData = nextLonghand.args;
            nextLonghand.args = nextData.slice(0, 2);
            suffix = stringify([nextLonghand]);
          }
          if (isConvex(nextData) && isArc(nextData, relCircle)) {
            angle += findArcAngle(nextData, relCircle);
            if (angle - 2 * Math.PI > 1e-3) break; // more than 360°
            if (angle > Math.PI) arc.args[3] = 1;
            arcCurves.push(next);
            if (2 * Math.PI - angle > 1e-3) {
              // less than 360°
              arc.coords = next.coords;
              arc.args[5] = arc.coords[0] - arc.base[0];
              arc.args[6] = arc.coords[1] - arc.base[1];
            } else {
              // full circle, make a half-circle arc and add a second one
              arc.args[5] = 2 * (relCircle.center[0] - nextData[4]);
              arc.args[6] = 2 * (relCircle.center[1] - nextData[5]);
              arc.coords = [
                arc.base[0] + arc.args[5],
                arc.base[1] + arc.args[6],
              ];
              arc = {
                command: 'a',
                args: [
                  r,
                  r,
                  0,
                  0,
                  sweep,
                  next.coords[0] - arc.coords[0],
                  next.coords[1] - arc.coords[1],
                ],
                coords: next.coords,
                base: arc.coords,
              };
              output.push(arc);
              j++;
              break;
            }
            relCenter[0] -= nextData[4];
            relCenter[1] -= nextData[5];
          } else break;
        }

        if ((stringify(output) + suffix).length < stringify(arcCurves).length) {
          if (path[j] && path[j].command == 's') {
            makeLonghand(path[j], path[j - 1].args);
          }
          if (hasPrev) {
            var prevArc = output.shift();
            roundData(prevArc.args);
            relSubpoint[0] += prevArc.args[5] - prev.args[prev.args.length - 2];
            relSubpoint[1] += prevArc.args[6] - prev.args[prev.args.length - 1];
            prev.command = 'a';
            prev.args = prevArc.args;
            item.base = prev.coords = prevArc.coords;
          }
          arc = output.shift();
          if (arcCurves.length == 1) {
            item.sdata = sdata.slice(); // preserve curve data for future checks
          } else if (arcCurves.length - 1 - hasPrev > 0) {
            // filter out consumed next items
            path.splice.apply(
              path,
              [index + 1, arcCurves.length - 1 - hasPrev].concat(output)
            );
          }
          if (!arc) return false;
          command = 'a';
          data = arc.args;
          item.coords = arc.coords;
        }
      }

      // Rounding relative coordinates, taking in account accummulating error
      // to get closer to absolute coordinates. Sum of rounded value remains same:
      // l .25 3 .25 2 .25 3 .25 2 -> l .3 3 .2 2 .3 3 .2 2
      if (precision !== false) {
        if (
          command === 'm' ||
          command === 'l' ||
          command === 't' ||
          command === 'q' ||
          command === 's' ||
          command === 'c'
        ) {
          for (var i = data.length; i--; ) {
            data[i] += item.base[i % 2] - relSubpoint[i % 2];
          }
        } else if (command == 'h') {
          data[0] += item.base[0] - relSubpoint[0];
        } else if (command == 'v') {
          data[0] += item.base[1] - relSubpoint[1];
        } else if (command == 'a') {
          data[5] += item.base[0] - relSubpoint[0];
          data[6] += item.base[1] - relSubpoint[1];
        }
        roundData(data);

        if (command == 'h') relSubpoint[0] += data[0];
        else if (command == 'v') relSubpoint[1] += data[0];
        else {
          relSubpoint[0] += data[data.length - 2];
          relSubpoint[1] += data[data.length - 1];
        }
        roundData(relSubpoint);

        if (command === 'M' || command === 'm') {
          pathBase[0] = relSubpoint[0];
          pathBase[1] = relSubpoint[1];
        }
      }

      // convert straight curves into lines segments
      if (params.straightCurves) {
        if (
          (command === 'c' && isCurveStraightLine(data)) ||
          (command === 's' && isCurveStraightLine(sdata))
        ) {
          if (next && next.command == 's') makeLonghand(next, data); // fix up next curve
          command = 'l';
          data = data.slice(-2);
        } else if (command === 'q' && isCurveStraightLine(data)) {
          if (next && next.command == 't') makeLonghand(next, data); // fix up next curve
          command = 'l';
          data = data.slice(-2);
        } else if (
          command === 't' &&
          prev.command !== 'q' &&
          prev.command !== 't'
        ) {
          command = 'l';
          data = data.slice(-2);
        } else if (command === 'a' && (data[0] === 0 || data[1] === 0)) {
          command = 'l';
          data = data.slice(-2);
        }
      }

      // horizontal and vertical line shorthands
      // l 50 0 → h 50
      // l 0 50 → v 50
      if (params.lineShorthands && command === 'l') {
        if (data[1] === 0) {
          command = 'h';
          data.pop();
        } else if (data[0] === 0) {
          command = 'v';
          data.shift();
        }
      }

      // collapse repeated commands
      // h 20 h 30 -> h 50
      if (
        params.collapseRepeated &&
        hasMarkerMid === false &&
        (command === 'm' || command === 'h' || command === 'v') &&
        prev.command &&
        command == prev.command.toLowerCase() &&
        ((command != 'h' && command != 'v') ||
          prev.args[0] >= 0 == data[0] >= 0)
      ) {
        prev.args[0] += data[0];
        if (command != 'h' && command != 'v') {
          prev.args[1] += data[1];
        }
        prev.coords = item.coords;
        path[index] = prev;
        return false;
      }

      // convert curves into smooth shorthands
      if (params.curveSmoothShorthands && prev.command) {
        // curveto
        if (command === 'c') {
          // c + c → c + s
          if (
            prev.command === 'c' &&
            data[0] === -(prev.args[2] - prev.args[4]) &&
            data[1] === -(prev.args[3] - prev.args[5])
          ) {
            command = 's';
            data = data.slice(2);
          }

          // s + c → s + s
          else if (
            prev.command === 's' &&
            data[0] === -(prev.args[0] - prev.args[2]) &&
            data[1] === -(prev.args[1] - prev.args[3])
          ) {
            command = 's';
            data = data.slice(2);
          }

          // [^cs] + c → [^cs] + s
          else if (
            prev.command !== 'c' &&
            prev.command !== 's' &&
            data[0] === 0 &&
            data[1] === 0
          ) {
            command = 's';
            data = data.slice(2);
          }
        }

        // quadratic Bézier curveto
        else if (command === 'q') {
          // q + q → q + t
          if (
            prev.command === 'q' &&
            data[0] === prev.args[2] - prev.args[0] &&
            data[1] === prev.args[3] - prev.args[1]
          ) {
            command = 't';
            data = data.slice(2);
          }

          // t + q → t + t
          else if (
            prev.command === 't' &&
            data[2] === prev.args[0] &&
            data[3] === prev.args[1]
          ) {
            command = 't';
            data = data.slice(2);
          }
        }
      }

      // remove useless non-first path segments
      if (params.removeUseless && !maybeHasStrokeAndLinecap) {
        // l 0,0 / h 0 / v 0 / q 0,0 0,0 / t 0,0 / c 0,0 0,0 0,0 / s 0,0 0,0
        if (
          (command === 'l' ||
            command === 'h' ||
            command === 'v' ||
            command === 'q' ||
            command === 't' ||
            command === 'c' ||
            command === 's') &&
          data.every(function (i) {
            return i === 0;
          })
        ) {
          path[index] = prev;
          return false;
        }

        // a 25,25 -30 0,1 0,0
        if (command === 'a' && data[5] === 0 && data[6] === 0) {
          path[index] = prev;
          return false;
        }
      }

      item.command = command;
      item.args = data;

      prev = item;
    } else {
      // z resets coordinates
      relSubpoint[0] = pathBase[0];
      relSubpoint[1] = pathBase[1];
      if (prev.command === 'Z' || prev.command === 'z') return false;
      prev = item;
    }

    return true;
  });

  return path;
}

/**
 * Writes data in shortest form using absolute or relative coordinates.
 *
 * @param {Array} data input path data
 * @return {Boolean} output
 */
function convertToMixed(path, params) {
  var prev = path[0];

  path = path.filter(function (item, index) {
    if (index == 0) return true;
    if (item.command === 'Z' || item.command === 'z') {
      prev = item;
      return true;
    }

    var command = item.command,
      data = item.args,
      adata = data.slice();

    if (
      command === 'm' ||
      command === 'l' ||
      command === 't' ||
      command === 'q' ||
      command === 's' ||
      command === 'c'
    ) {
      for (var i = adata.length; i--; ) {
        adata[i] += item.base[i % 2];
      }
    } else if (command == 'h') {
      adata[0] += item.base[0];
    } else if (command == 'v') {
      adata[0] += item.base[1];
    } else if (command == 'a') {
      adata[5] += item.base[0];
      adata[6] += item.base[1];
    }

    roundData(adata);

    var absoluteDataStr = cleanupOutData(adata, params),
      relativeDataStr = cleanupOutData(data, params);

    // Convert to absolute coordinates if it's shorter or forceAbsolutePath is true.
    // v-20 -> V0
    // Don't convert if it fits following previous command.
    // l20 30-10-50 instead of l20 30L20 30
    if (
      params.forceAbsolutePath ||
      (absoluteDataStr.length < relativeDataStr.length &&
        !(
          params.negativeExtraSpace &&
          command == prev.command &&
          prev.command.charCodeAt(0) > 96 &&
          absoluteDataStr.length == relativeDataStr.length - 1 &&
          (data[0] < 0 ||
            (/^0\./.test(data[0]) && prev.args[prev.args.length - 1] % 1))
        ))
    ) {
      item.command = command.toUpperCase();
      item.args = adata;
    }

    prev = item;

    return true;
  });

  return path;
}

/**
 * Checks if curve is convex. Control points of such a curve must form
 * a convex quadrilateral with diagonals crosspoint inside of it.
 *
 * @param {Array} data input path data
 * @return {Boolean} output
 */
function isConvex(data) {
  var center = getIntersection([
    0,
    0,
    data[2],
    data[3],
    data[0],
    data[1],
    data[4],
    data[5],
  ]);

  return (
    center &&
    data[2] < center[0] == center[0] < 0 &&
    data[3] < center[1] == center[1] < 0 &&
    data[4] < center[0] == center[0] < data[0] &&
    data[5] < center[1] == center[1] < data[1]
  );
}

/**
 * Computes lines equations by two points and returns their intersection point.
 *
 * @param {Array} coords 8 numbers for 4 pairs of coordinates (x,y)
 * @return {Array|undefined} output coordinate of lines' crosspoint
 */
function getIntersection(coords) {
  // Prev line equation parameters.
  var a1 = coords[1] - coords[3], // y1 - y2
    b1 = coords[2] - coords[0], // x2 - x1
    c1 = coords[0] * coords[3] - coords[2] * coords[1], // x1 * y2 - x2 * y1
    // Next line equation parameters
    a2 = coords[5] - coords[7], // y1 - y2
    b2 = coords[6] - coords[4], // x2 - x1
    c2 = coords[4] * coords[7] - coords[5] * coords[6], // x1 * y2 - x2 * y1
    denom = a1 * b2 - a2 * b1;

  if (!denom) return; // parallel lines havn't an intersection

  var cross = [(b1 * c2 - b2 * c1) / denom, (a1 * c2 - a2 * c1) / -denom];
  if (
    !isNaN(cross[0]) &&
    !isNaN(cross[1]) &&
    isFinite(cross[0]) &&
    isFinite(cross[1])
  ) {
    return cross;
  }
}

/**
 * Decrease accuracy of floating-point numbers
 * in path data keeping a specified number of decimals.
 * Smart rounds values like 2.3491 to 2.35 instead of 2.349.
 * Doesn't apply "smartness" if the number precision fits already.
 *
 * @param {Array} data input data array
 * @return {Array} output data array
 */
function strongRound(data) {
  for (var i = data.length; i-- > 0; ) {
    if (data[i].toFixed(precision) != data[i]) {
      var rounded = +data[i].toFixed(precision - 1);
      data[i] =
        +Math.abs(rounded - data[i]).toFixed(precision + 1) >= error
          ? +data[i].toFixed(precision)
          : rounded;
    }
  }
  return data;
}

/**
 * Simple rounding function if precision is 0.
 *
 * @param {Array} data input data array
 * @return {Array} output data array
 */
function round(data) {
  for (var i = data.length; i-- > 0; ) {
    data[i] = Math.round(data[i]);
  }
  return data;
}

/**
 * Checks if a curve is a straight line by measuring distance
 * from middle points to the line formed by end points.
 *
 * @param {Array} xs array of curve points x-coordinates
 * @param {Array} ys array of curve points y-coordinates
 * @return {Boolean}
 */

function isCurveStraightLine(data) {
  // Get line equation a·x + b·y + c = 0 coefficients a, b (c = 0) by start and end points.
  var i = data.length - 2,
    a = -data[i + 1], // y1 − y2 (y1 = 0)
    b = data[i], // x2 − x1 (x1 = 0)
    d = 1 / (a * a + b * b); // same part for all points

  if (i <= 1 || !isFinite(d)) return false; // curve that ends at start point isn't the case

  // Distance from point (x0, y0) to the line is sqrt((c − a·x0 − b·y0)² / (a² + b²))
  while ((i -= 2) >= 0) {
    if (Math.sqrt(Math.pow(a * data[i] + b * data[i + 1], 2) * d) > error)
      return false;
  }

  return true;
}

/**
 * Converts next curve from shorthand to full form using the current curve data.
 *
 * @param {Object} item curve to convert
 * @param {Array} data current curve data
 */

function makeLonghand(item, data) {
  switch (item.command) {
    case 's':
      item.command = 'c';
      break;
    case 't':
      item.command = 'q';
      break;
  }
  item.args.unshift(
    data[data.length - 2] - data[data.length - 4],
    data[data.length - 1] - data[data.length - 3]
  );
  return item;
}

/**
 * Returns distance between two points
 *
 * @param {Array} point1 first point coordinates
 * @param {Array} point2 second point coordinates
 * @return {Number} distance
 */

function getDistance(point1, point2) {
  return Math.hypot(point1[0] - point2[0], point1[1] - point2[1]);
}

/**
 * Returns coordinates of the curve point corresponding to the certain t
 * a·(1 - t)³·p1 + b·(1 - t)²·t·p2 + c·(1 - t)·t²·p3 + d·t³·p4,
 * where pN are control points and p1 is zero due to relative coordinates.
 *
 * @param {Array} curve array of curve points coordinates
 * @param {Number} t parametric position from 0 to 1
 * @return {Array} Point coordinates
 */

function getCubicBezierPoint(curve, t) {
  var sqrT = t * t,
    cubT = sqrT * t,
    mt = 1 - t,
    sqrMt = mt * mt;

  return [
    3 * sqrMt * t * curve[0] + 3 * mt * sqrT * curve[2] + cubT * curve[4],
    3 * sqrMt * t * curve[1] + 3 * mt * sqrT * curve[3] + cubT * curve[5],
  ];
}

/**
 * Finds circle by 3 points of the curve and checks if the curve fits the found circle.
 *
 * @param {Array} curve
 * @return {Object|undefined} circle
 */

function findCircle(curve) {
  var midPoint = getCubicBezierPoint(curve, 1 / 2),
    m1 = [midPoint[0] / 2, midPoint[1] / 2],
    m2 = [(midPoint[0] + curve[4]) / 2, (midPoint[1] + curve[5]) / 2],
    center = getIntersection([
      m1[0],
      m1[1],
      m1[0] + m1[1],
      m1[1] - m1[0],
      m2[0],
      m2[1],
      m2[0] + (m2[1] - midPoint[1]),
      m2[1] - (m2[0] - midPoint[0]),
    ]),
    radius = center && getDistance([0, 0], center),
    tolerance = Math.min(arcThreshold * error, (arcTolerance * radius) / 100);

  if (
    center &&
    radius < 1e15 &&
    [1 / 4, 3 / 4].every(function (point) {
      return (
        Math.abs(
          getDistance(getCubicBezierPoint(curve, point), center) - radius
        ) <= tolerance
      );
    })
  )
    return { center: center, radius: radius };
}

/**
 * Checks if a curve fits the given circle.
 *
 * @param {Object} circle
 * @param {Array} curve
 * @return {Boolean}
 */

function isArc(curve, circle) {
  var tolerance = Math.min(
    arcThreshold * error,
    (arcTolerance * circle.radius) / 100
  );

  return [0, 1 / 4, 1 / 2, 3 / 4, 1].every(function (point) {
    return (
      Math.abs(
        getDistance(getCubicBezierPoint(curve, point), circle.center) -
          circle.radius
      ) <= tolerance
    );
  });
}

/**
 * Checks if a previous curve fits the given circle.
 *
 * @param {Object} circle
 * @param {Array} curve
 * @return {Boolean}
 */

function isArcPrev(curve, circle) {
  return isArc(curve, {
    center: [circle.center[0] + curve[4], circle.center[1] + curve[5]],
    radius: circle.radius,
  });
}

/**
 * Finds angle of a curve fitting the given arc.

 * @param {Array} curve
 * @param {Object} relCircle
 * @return {Number} angle
 */

function findArcAngle(curve, relCircle) {
  var x1 = -relCircle.center[0],
    y1 = -relCircle.center[1],
    x2 = curve[4] - relCircle.center[0],
    y2 = curve[5] - relCircle.center[1];

  return Math.acos(
    (x1 * x2 + y1 * y2) / Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  );
}

/**
 * Converts given path data to string.
 *
 * @param {Object} params
 * @param {Array} pathData
 * @return {String}
 */

function data2Path(params, pathData) {
  return pathData.reduce(function (pathString, item) {
    var strData = '';
    if (item.args) {
      strData = cleanupOutData(roundData(item.args.slice()), params);
    }
    return pathString + item.command + strData;
  }, '');
}


code:
'use strict';

/**
 * @typedef {import('../lib/types').PathDataItem} PathDataItem
 */

const { stringifyPathData } = require('../lib/path.js');
const { detachNodeFromParent } = require('../lib/xast.js');

exports.name = 'convertShapeToPath';
exports.type = 'visitor';
exports.active = true;
exports.description = 'converts basic shapes to more compact path form';

const regNumber = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;

/**
 * Converts basic shape to more compact path.
 * It also allows further optimizations like
 * combining paths with similar attributes.
 *
 * @see https://www.w3.org/TR/SVG11/shapes.html
 *
 * @author Lev Solntsev
 *
 * @type {import('../lib/types').Plugin<{
 *   convertArcs?: boolean,
 *   floatPrecision?: number
 * }>}
 */
exports.fn = (root, params) => {
  const { convertArcs = false, floatPrecision: precision } = params;

  return {
    element: {
      enter: (node, parentNode) => {
        // convert rect to path
        if (
          node.name === 'rect' &&
          node.attributes.width != null &&
          node.attributes.height != null &&
          node.attributes.rx == null &&
          node.attributes.ry == null
        ) {
          const x = Number(node.attributes.x || '0');
          const y = Number(node.attributes.y || '0');
          const width = Number(node.attributes.width);
          const height = Number(node.attributes.height);
          // Values like '100%' compute to NaN, thus running after
          // cleanupNumericValues when 'px' units has already been removed.
          // TODO: Calculate sizes from % and non-px units if possible.
          if (Number.isNaN(x - y + width - height)) return;
          /**
           * @type {Array<PathDataItem>}
           */
          const pathData = [
            { command: 'M', args: [x, y] },
            { command: 'H', args: [x + width] },
            { command: 'V', args: [y + height] },
            { command: 'H', args: [x] },
            { command: 'z', args: [] },
          ];
          node.name = 'path';
          node.attributes.d = stringifyPathData({ pathData, precision });
          delete node.attributes.x;
          delete node.attributes.y;
          delete node.attributes.width;
          delete node.attributes.height;
        }

        // convert line to path
        if (node.name === 'line') {
          const x1 = Number(node.attributes.x1 || '0');
          const y1 = Number(node.attributes.y1 || '0');
          const x2 = Number(node.attributes.x2 || '0');
          const y2 = Number(node.attributes.y2 || '0');
          if (Number.isNaN(x1 - y1 + x2 - y2)) return;
          /**
           * @type {Array<PathDataItem>}
           */
          const pathData = [
            { command: 'M', args: [x1, y1] },
            { command: 'L', args: [x2, y2] },
          ];
          node.name = 'path';
          node.attributes.d = stringifyPathData({ pathData, precision });
          delete node.attributes.x1;
          delete node.attributes.y1;
          delete node.attributes.x2;
          delete node.attributes.y2;
        }

        // convert polyline and polygon to path
        if (
          (node.name === 'polyline' || node.name === 'polygon') &&
          node.attributes.points != null
        ) {
          const coords = (node.attributes.points.match(regNumber) || []).map(
            Number
          );
          if (coords.length < 4) {
            detachNodeFromParent(node, parentNode);
            return;
          }
          /**
           * @type {Array<PathDataItem>}
           */
          const pathData = [];
          for (let i = 0; i < coords.length; i += 2) {
            pathData.push({
              command: i === 0 ? 'M' : 'L',
              args: coords.slice(i, i + 2),
            });
          }
          if (node.name === 'polygon') {
            pathData.push({ command: 'z', args: [] });
          }
          node.name = 'path';
          node.attributes.d = stringifyPathData({ pathData, precision });
          delete node.attributes.points;
        }

        //  optionally convert circle
        if (node.name === 'circle' && convertArcs) {
          const cx = Number(node.attributes.cx || '0');
          const cy = Number(node.attributes.cy || '0');
          const r = Number(node.attributes.r || '0');
          if (Number.isNaN(cx - cy + r)) {
            return;
          }
          /**
           * @type {Array<PathDataItem>}
           */
          const pathData = [
            { command: 'M', args: [cx, cy - r] },
            { command: 'A', args: [r, r, 0, 1, 0, cx, cy + r] },
            { command: 'A', args: [r, r, 0, 1, 0, cx, cy - r] },
            { command: 'z', args: [] },
          ];
          node.name = 'path';
          node.attributes.d = stringifyPathData({ pathData, precision });
          delete node.attributes.cx;
          delete node.attributes.cy;
          delete node.attributes.r;
        }

        // optionally covert ellipse
        if (node.name === 'ellipse' && convertArcs) {
          const ecx = Number(node.attributes.cx || '0');
          const ecy = Number(node.attributes.cy || '0');
          const rx = Number(node.attributes.rx || '0');
          const ry = Number(node.attributes.ry || '0');
          if (Number.isNaN(ecx - ecy + rx - ry)) {
            return;
          }
          /**
           * @type {Array<PathDataItem>}
           */
          const pathData = [
            { command: 'M', args: [ecx, ecy - ry] },
            { command: 'A', args: [rx, ry, 0, 1, 0, ecx, ecy + ry] },
            { command: 'A', args: [rx, ry, 0, 1, 0, ecx, ecy - ry] },
            { command: 'z', args: [] },
          ];
          node.name = 'path';
          node.attributes.d = stringifyPathData({ pathData, precision });
          delete node.attributes.cx;
          delete node.attributes.cy;
          delete node.attributes.rx;
          delete node.attributes.ry;
        }
      },
    },
  };
};


code:
'use strict';

exports.name = 'convertStyleToAttrs';

exports.type = 'perItem';

exports.active = false;

exports.description = 'converts style to attributes';

exports.params = {
  keepImportant: false,
};

var stylingProps = require('./_collections').attrsGroups.presentation,
  rEscape = '\\\\(?:[0-9a-f]{1,6}\\s?|\\r\\n|.)', // Like \" or \2051. Code points consume one space.
  rAttr = '\\s*(' + g('[^:;\\\\]', rEscape) + '*?)\\s*', // attribute name like ‘fill’
  rSingleQuotes = "'(?:[^'\\n\\r\\\\]|" + rEscape + ")*?(?:'|$)", // string in single quotes: 'smth'
  rQuotes = '"(?:[^"\\n\\r\\\\]|' + rEscape + ')*?(?:"|$)', // string in double quotes: "smth"
  rQuotedString = new RegExp('^' + g(rSingleQuotes, rQuotes) + '$'),
  // Parentheses, E.g.: url(data:image/png;base64,iVBO...).
  // ':' and ';' inside of it should be threated as is. (Just like in strings.)
  rParenthesis =
    '\\(' + g('[^\'"()\\\\]+', rEscape, rSingleQuotes, rQuotes) + '*?' + '\\)',
  // The value. It can have strings and parentheses (see above). Fallbacks to anything in case of unexpected input.
  rValue =
    '\\s*(' +
    g(
      '[^!\'"();\\\\]+?',
      rEscape,
      rSingleQuotes,
      rQuotes,
      rParenthesis,
      '[^;]*?'
    ) +
    '*?' +
    ')',
  // End of declaration. Spaces outside of capturing groups help to do natural trimming.
  rDeclEnd = '\\s*(?:;\\s*|$)',
  // Important rule
  rImportant = '(\\s*!important(?![-(\\w]))?',
  // Final RegExp to parse CSS declarations.
  regDeclarationBlock = new RegExp(
    rAttr + ':' + rValue + rImportant + rDeclEnd,
    'ig'
  ),
  // Comments expression. Honors escape sequences and strings.
  regStripComments = new RegExp(
    g(rEscape, rSingleQuotes, rQuotes, '/\\*[^]*?\\*/'),
    'ig'
  );

/**
 * Convert style in attributes. Cleanups comments and illegal declarations (without colon) as a side effect.
 *
 * @example
 * <g style="fill:#000; color: #fff;">
 *             ⬇
 * <g fill="#000" color="#fff">
 *
 * @example
 * <g style="fill:#000; color: #fff; -webkit-blah: blah">
 *             ⬇
 * <g fill="#000" color="#fff" style="-webkit-blah: blah">
 *
 * @param {Object} item current iteration item
 * @return {Boolean} if false, item will be filtered out
 *
 * @author Kir Belevich
 */
exports.fn = function (item, params) {
  if (item.type === 'element' && item.attributes.style != null) {
    // ['opacity: 1', 'color: #000']
    let styles = [];
    const newAttributes = {};

    // Strip CSS comments preserving escape sequences and strings.
    const styleValue = item.attributes.style.replace(
      regStripComments,
      (match) => {
        return match[0] == '/'
          ? ''
          : match[0] == '\\' && /[-g-z]/i.test(match[1])
          ? match[1]
          : match;
      }
    );

    regDeclarationBlock.lastIndex = 0;
    // eslint-disable-next-line no-cond-assign
    for (var rule; (rule = regDeclarationBlock.exec(styleValue)); ) {
      if (!params.keepImportant || !rule[3]) {
        styles.push([rule[1], rule[2]]);
      }
    }

    if (styles.length) {
      styles = styles.filter(function (style) {
        if (style[0]) {
          var prop = style[0].toLowerCase(),
            val = style[1];

          if (rQuotedString.test(val)) {
            val = val.slice(1, -1);
          }

          if (stylingProps.includes(prop)) {
            newAttributes[prop] = val;

            return false;
          }
        }

        return true;
      });

      Object.assign(item.attributes, newAttributes);

      if (styles.length) {
        item.attributes.style = styles
          .map((declaration) => declaration.join(':'))
          .join(';');
      } else {
        delete item.attributes.style;
      }
    }
  }
};

function g() {
  return '(?:' + Array.prototype.join.call(arguments, '|') + ')';
}


code:
'use strict';

/**
 * @typedef {import('../lib/types').XastElement} XastElement
 */

const { cleanupOutData } = require('../lib/svgo/tools.js');
const {
  transform2js,
  transformsMultiply,
  matrixToTransform,
} = require('./_transforms.js');

exports.type = 'visitor';
exports.name = 'convertTransform';
exports.active = true;
exports.description = 'collapses multiple transformations and optimizes it';

/**
 * Convert matrices to the short aliases,
 * convert long translate, scale or rotate transform notations to the shorts ones,
 * convert transforms to the matrices and multiply them all into one,
 * remove useless transforms.
 *
 * @see https://www.w3.org/TR/SVG11/coords.html#TransformMatrixDefined
 *
 * @author Kir Belevich
 *
 * @type {import('../lib/types').Plugin<{
 *   convertToShorts?: boolean,
 *   degPrecision?: number,
 *   floatPrecision?: number,
 *   transformPrecision?: number,
 *   matrixToTransform?: boolean,
 *   shortTranslate?: boolean,
 *   shortScale?: boolean,
 *   shortRotate?: boolean,
 *   removeUseless?: boolean,
 *   collapseIntoOne?: boolean,
 *   leadingZero?: boolean,
 *   negativeExtraSpace?: boolean,
 * }>}
 */
exports.fn = (_root, params) => {
  const {
    convertToShorts = true,
    // degPrecision = 3, // transformPrecision (or matrix precision) - 2 by default
    degPrecision,
    floatPrecision = 3,
    transformPrecision = 5,
    matrixToTransform = true,
    shortTranslate = true,
    shortScale = true,
    shortRotate = true,
    removeUseless = true,
    collapseIntoOne = true,
    leadingZero = true,
    negativeExtraSpace = false,
  } = params;
  const newParams = {
    convertToShorts,
    degPrecision,
    floatPrecision,
    transformPrecision,
    matrixToTransform,
    shortTranslate,
    shortScale,
    shortRotate,
    removeUseless,
    collapseIntoOne,
    leadingZero,
    negativeExtraSpace,
  };
  return {
    element: {
      enter: (node) => {
        // transform
        if (node.attributes.transform != null) {
          convertTransform(node, 'transform', newParams);
        }
        // gradientTransform
        if (node.attributes.gradientTransform != null) {
          convertTransform(node, 'gradientTransform', newParams);
        }
        // patternTransform
        if (node.attributes.patternTransform != null) {
          convertTransform(node, 'patternTransform', newParams);
        }
      },
    },
  };
};

/**
 * @typedef {{
 *   convertToShorts: boolean,
 *   degPrecision?: number,
 *   floatPrecision: number,
 *   transformPrecision: number,
 *   matrixToTransform: boolean,
 *   shortTranslate: boolean,
 *   shortScale: boolean,
 *   shortRotate: boolean,
 *   removeUseless: boolean,
 *   collapseIntoOne: boolean,
 *   leadingZero: boolean,
 *   negativeExtraSpace: boolean,
 * }} TransformParams
 */

/**
 * @typedef {{ name: string, data: Array<number> }} TransformItem
 */

/**
 * Main function.
 *
 * @type {(item: XastElement, attrName: string, params: TransformParams) => void}
 */
const convertTransform = (item, attrName, params) => {
  let data = transform2js(item.attributes[attrName]);
  params = definePrecision(data, params);

  if (params.collapseIntoOne && data.length > 1) {
    data = [transformsMultiply(data)];
  }

  if (params.convertToShorts) {
    data = convertToShorts(data, params);
  } else {
    data.forEach((item) => roundTransform(item, params));
  }

  if (params.removeUseless) {
    data = removeUseless(data);
  }

  if (data.length) {
    item.attributes[attrName] = js2transform(data, params);
  } else {
    delete item.attributes[attrName];
  }
};

/**
 * Defines precision to work with certain parts.
 * transformPrecision - for scale and four first matrix parameters (needs a better precision due to multiplying),
 * floatPrecision - for translate including two last matrix and rotate parameters,
 * degPrecision - for rotate and skew. By default it's equal to (rougly)
 * transformPrecision - 2 or floatPrecision whichever is lower. Can be set in params.
 *
 * @type {(data: Array<TransformItem>, params: TransformParams) => TransformParams}
 *
 * clone params so it don't affect other elements transformations.
 */
const definePrecision = (data, { ...newParams }) => {
  const matrixData = [];
  for (const item of data) {
    if (item.name == 'matrix') {
      matrixData.push(...item.data.slice(0, 4));
    }
  }
  let significantDigits = newParams.transformPrecision;
  // Limit transform precision with matrix one. Calculating with larger precision doesn't add any value.
  if (matrixData.length) {
    newParams.transformPrecision = Math.min(
      newParams.transformPrecision,
      Math.max.apply(Math, matrixData.map(floatDigits)) ||
        newParams.transformPrecision
    );
    significantDigits = Math.max.apply(
      Math,
      matrixData.map(
        (n) => n.toString().replace(/\D+/g, '').length // Number of digits in a number. 123.45 → 5
      )
    );
  }
  // No sense in angle precision more then number of significant digits in matrix.
  if (newParams.degPrecision == null) {
    newParams.degPrecision = Math.max(
      0,
      Math.min(newParams.floatPrecision, significantDigits - 2)
    );
  }
  return newParams;
};

/**
 * @type {(data: Array<number>, params: TransformParams) => Array<number>}
 */
const degRound = (data, params) => {
  if (
    params.degPrecision != null &&
    params.degPrecision >= 1 &&
    params.floatPrecision < 20
  ) {
    return smartRound(params.degPrecision, data);
  } else {
    return round(data);
  }
};
/**
 * @type {(data: Array<number>, params: TransformParams) => Array<number>}
 */
const floatRound = (data, params) => {
  if (params.floatPrecision >= 1 && params.floatPrecision < 20) {
    return smartRound(params.floatPrecision, data);
  } else {
    return round(data);
  }
};

/**
 * @type {(data: Array<number>, params: TransformParams) => Array<number>}
 */
const transformRound = (data, params) => {
  if (params.transformPrecision >= 1 && params.floatPrecision < 20) {
    return smartRound(params.transformPrecision, data);
  } else {
    return round(data);
  }
};

/**
 * Returns number of digits after the point. 0.125 → 3
 *
 * @type {(n: number) => number}
 */
const floatDigits = (n) => {
  const str = n.toString();
  return str.slice(str.indexOf('.')).length - 1;
};

/**
 * Convert transforms to the shorthand alternatives.
 *
 * @type {(transforms: Array<TransformItem>, params: TransformParams) => Array<TransformItem>}
 */
const convertToShorts = (transforms, params) => {
  for (var i = 0; i < transforms.length; i++) {
    var transform = transforms[i];

    // convert matrix to the short aliases
    if (params.matrixToTransform && transform.name === 'matrix') {
      var decomposed = matrixToTransform(transform, params);
      if (
        js2transform(decomposed, params).length <=
        js2transform([transform], params).length
      ) {
        transforms.splice(i, 1, ...decomposed);
      }
      transform = transforms[i];
    }

    // fixed-point numbers
    // 12.754997 → 12.755
    roundTransform(transform, params);

    // convert long translate transform notation to the shorts one
    // translate(10 0) → translate(10)
    if (
      params.shortTranslate &&
      transform.name === 'translate' &&
      transform.data.length === 2 &&
      !transform.data[1]
    ) {
      transform.data.pop();
    }

    // convert long scale transform notation to the shorts one
    // scale(2 2) → scale(2)
    if (
      params.shortScale &&
      transform.name === 'scale' &&
      transform.data.length === 2 &&
      transform.data[0] === transform.data[1]
    ) {
      transform.data.pop();
    }

    // convert long rotate transform notation to the short one
    // translate(cx cy) rotate(a) translate(-cx -cy) → rotate(a cx cy)
    if (
      params.shortRotate &&
      transforms[i - 2] &&
      transforms[i - 2].name === 'translate' &&
      transforms[i - 1].name === 'rotate' &&
      transforms[i].name === 'translate' &&
      transforms[i - 2].data[0] === -transforms[i].data[0] &&
      transforms[i - 2].data[1] === -transforms[i].data[1]
    ) {
      transforms.splice(i - 2, 3, {
        name: 'rotate',
        data: [
          transforms[i - 1].data[0],
          transforms[i - 2].data[0],
          transforms[i - 2].data[1],
        ],
      });

      // splice compensation
      i -= 2;
    }
  }

  return transforms;
};

/**
 * Remove useless transforms.
 *
 * @type {(trasforms: Array<TransformItem>) => Array<TransformItem>}
 */
const removeUseless = (transforms) => {
  return transforms.filter((transform) => {
    // translate(0), rotate(0[, cx, cy]), skewX(0), skewY(0)
    if (
      (['translate', 'rotate', 'skewX', 'skewY'].indexOf(transform.name) > -1 &&
        (transform.data.length == 1 || transform.name == 'rotate') &&
        !transform.data[0]) ||
      // translate(0, 0)
      (transform.name == 'translate' &&
        !transform.data[0] &&
        !transform.data[1]) ||
      // scale(1)
      (transform.name == 'scale' &&
        transform.data[0] == 1 &&
        (transform.data.length < 2 || transform.data[1] == 1)) ||
      // matrix(1 0 0 1 0 0)
      (transform.name == 'matrix' &&
        transform.data[0] == 1 &&
        transform.data[3] == 1 &&
        !(
          transform.data[1] ||
          transform.data[2] ||
          transform.data[4] ||
          transform.data[5]
        ))
    ) {
      return false;
    }

    return true;
  });
};

/**
 * Convert transforms JS representation to string.
 *
 * @type {(transformJS: Array<TransformItem>, params: TransformParams) => string}
 */
const js2transform = (transformJS, params) => {
  var transformString = '';

  // collect output value string
  transformJS.forEach((transform) => {
    roundTransform(transform, params);
    transformString +=
      (transformString && ' ') +
      transform.name +
      '(' +
      cleanupOutData(transform.data, params) +
      ')';
  });

  return transformString;
};

/**
 * @type {(transform: TransformItem, params: TransformParams) => TransformItem}
 */
const roundTransform = (transform, params) => {
  switch (transform.name) {
    case 'translate':
      transform.data = floatRound(transform.data, params);
      break;
    case 'rotate':
      transform.data = [
        ...degRound(transform.data.slice(0, 1), params),
        ...floatRound(transform.data.slice(1), params),
      ];
      break;
    case 'skewX':
    case 'skewY':
      transform.data = degRound(transform.data, params);
      break;
    case 'scale':
      transform.data = transformRound(transform.data, params);
      break;
    case 'matrix':
      transform.data = [
        ...transformRound(transform.data.slice(0, 4), params),
        ...floatRound(transform.data.slice(4), params),
      ];
      break;
  }
  return transform;
};

/**
 * Rounds numbers in array.
 *
 * @type {(data: Array<number>) => Array<number>}
 */
const round = (data) => {
  return data.map(Math.round);
};

/**
 * Decrease accuracy of floating-point numbers
 * in transforms keeping a specified number of decimals.
 * Smart rounds values like 2.349 to 2.35.
 *
 * @type {(precision: number, data: Array<number>) => Array<number>}
 */
const smartRound = (precision, data) => {
  for (
    var i = data.length,
      tolerance = +Math.pow(0.1, precision).toFixed(precision);
    i--;

  ) {
    if (Number(data[i].toFixed(precision)) !== data[i]) {
      var rounded = +data[i].toFixed(precision - 1);
      data[i] =
        +Math.abs(rounded - data[i]).toFixed(precision + 1) >= tolerance
          ? +data[i].toFixed(precision)
          : rounded;
    }
  }
  return data;
};


code:
'use strict';

/**
 * @typedef {import('../lib/types').Specificity} Specificity
 * @typedef {import('../lib/types').XastElement} XastElement
 * @typedef {import('../lib/types').XastParent} XastParent
 */

const csstree = require('css-tree');
// @ts-ignore not defined in @types/csso
const specificity = require('csso/lib/restructure/prepare/specificity');
const stable = require('stable');
const {
  visitSkip,
  querySelectorAll,
  detachNodeFromParent,
} = require('../lib/xast.js');

exports.type = 'visitor';
exports.name = 'inlineStyles';
exports.active = true;
exports.description = 'inline styles (additional options)';

/**
 * Compares two selector specificities.
 * extracted from https://github.com/keeganstreet/specificity/blob/master/specificity.js#L211
 *
 * @type {(a: Specificity, b: Specificity) => number}
 */
const compareSpecificity = (a, b) => {
  for (var i = 0; i < 4; i += 1) {
    if (a[i] < b[i]) {
      return -1;
    } else if (a[i] > b[i]) {
      return 1;
    }
  }
  return 0;
};

/**
 * Moves + merges styles from style elements to element styles
 *
 * Options
 *   onlyMatchedOnce (default: true)
 *     inline only selectors that match once
 *
 *   removeMatchedSelectors (default: true)
 *     clean up matched selectors,
 *     leave selectors that hadn't matched
 *
 *   useMqs (default: ['', 'screen'])
 *     what media queries to be used
 *     empty string element for styles outside media queries
 *
 *   usePseudos (default: [''])
 *     what pseudo-classes/-elements to be used
 *     empty string element for all non-pseudo-classes and/or -elements
 *
 * @author strarsis <strarsis@gmail.com>
 *
 * @type {import('../lib/types').Plugin<{
 *   onlyMatchedOnce?: boolean,
 *   removeMatchedSelectors?: boolean,
 *   useMqs?: Array<string>,
 *   usePseudos?: Array<string>
 * }>}
 */
exports.fn = (root, params) => {
  const {
    onlyMatchedOnce = true,
    removeMatchedSelectors = true,
    useMqs = ['', 'screen'],
    usePseudos = [''],
  } = params;

  /**
   * @type {Array<{ node: XastElement, parentNode: XastParent, cssAst: csstree.StyleSheet }>}
   */
  const styles = [];
  /**
   * @type {Array<{
   *   node: csstree.Selector,
   *   item: csstree.ListItem<csstree.CssNode>,
   *   rule: csstree.Rule,
   *   matchedElements?: Array<XastElement>
   * }>}
   */
  let selectors = [];

  return {
    element: {
      enter: (node, parentNode) => {
        // skip <foreignObject /> content
        if (node.name === 'foreignObject') {
          return visitSkip;
        }
        // collect only non-empty <style /> elements
        if (node.name !== 'style' || node.children.length === 0) {
          return;
        }
        // values other than the empty string or text/css are not used
        if (
          node.attributes.type != null &&
          node.attributes.type !== '' &&
          node.attributes.type !== 'text/css'
        ) {
          return;
        }
        // parse css in style element
        let cssText = '';
        for (const child of node.children) {
          if (child.type === 'text' || child.type === 'cdata') {
            cssText += child.value;
          }
        }
        /**
         * @type {null | csstree.CssNode}
         */
        let cssAst = null;
        try {
          cssAst = csstree.parse(cssText, {
            parseValue: false,
            parseCustomProperty: false,
          });
        } catch {
          return;
        }
        if (cssAst.type === 'StyleSheet') {
          styles.push({ node, parentNode, cssAst });
        }

        // collect selectors
        csstree.walk(cssAst, {
          visit: 'Selector',
          enter(node, item) {
            const atrule = this.atrule;
            const rule = this.rule;
            if (rule == null) {
              return;
            }

            // skip media queries not included into useMqs param
            let mq = '';
            if (atrule != null) {
              mq = atrule.name;
              if (atrule.prelude != null) {
                mq += ` ${csstree.generate(atrule.prelude)}`;
              }
            }
            if (useMqs.includes(mq) === false) {
              return;
            }

            /**
             * @type {Array<{
             *   item: csstree.ListItem<csstree.CssNode>,
             *   list: csstree.List<csstree.CssNode>
             * }>}
             */
            const pseudos = [];
            if (node.type === 'Selector') {
              node.children.each((childNode, childItem, childList) => {
                if (
                  childNode.type === 'PseudoClassSelector' ||
                  childNode.type === 'PseudoElementSelector'
                ) {
                  pseudos.push({ item: childItem, list: childList });
                }
              });
            }

            // skip pseudo classes and pseudo elements not includes into usePseudos param
            const pseudoSelectors = csstree.generate({
              type: 'Selector',
              children: new csstree.List().fromArray(
                pseudos.map((pseudo) => pseudo.item.data)
              ),
            });
            if (usePseudos.includes(pseudoSelectors) === false) {
              return;
            }

            // remove pseudo classes and elements to allow querySelector match elements
            // TODO this is not very accurate since some pseudo classes like first-child
            // are used for selection
            for (const pseudo of pseudos) {
              pseudo.list.remove(pseudo.item);
            }

            selectors.push({ node, item, rule });
          },
        });
      },
    },

    root: {
      exit: () => {
        if (styles.length === 0) {
          return;
        }
        // stable sort selectors
        const sortedSelectors = stable(selectors, (a, b) => {
          const aSpecificity = specificity(a.item.data);
          const bSpecificity = specificity(b.item.data);
          return compareSpecificity(aSpecificity, bSpecificity);
        }).reverse();

        for (const selector of sortedSelectors) {
          // match selectors
          const selectorText = csstree.generate(selector.item.data);
          /**
           * @type {Array<XastElement>}
           */
          const matchedElements = [];
          try {
            for (const node of querySelectorAll(root, selectorText)) {
              if (node.type === 'element') {
                matchedElements.push(node);
              }
            }
          } catch (selectError) {
            continue;
          }
          // nothing selected
          if (matchedElements.length === 0) {
            continue;
          }

          // apply styles to matched elements
          // skip selectors that match more than once if option onlyMatchedOnce is enabled
          if (onlyMatchedOnce && matchedElements.length > 1) {
            continue;
          }

          // apply <style/> to matched elements
          for (const selectedEl of matchedElements) {
            const styleDeclarationList = csstree.parse(
              selectedEl.attributes.style == null
                ? ''
                : selectedEl.attributes.style,
              {
                context: 'declarationList',
                parseValue: false,
              }
            );
            if (styleDeclarationList.type !== 'DeclarationList') {
              continue;
            }
            const styleDeclarationItems = new Map();
            csstree.walk(styleDeclarationList, {
              visit: 'Declaration',
              enter(node, item) {
                styleDeclarationItems.set(node.property, item);
              },
            });
            // merge declarations
            csstree.walk(selector.rule, {
              visit: 'Declaration',
              enter(ruleDeclaration) {
                // existing inline styles have higher priority
                // no inline styles, external styles,                                    external styles used
                // inline styles,    external styles same   priority as inline styles,   inline   styles used
                // inline styles,    external styles higher priority than inline styles, external styles used
                const matchedItem = styleDeclarationItems.get(
                  ruleDeclaration.property
                );
                const ruleDeclarationItem =
                  styleDeclarationList.children.createItem(ruleDeclaration);
                if (matchedItem == null) {
                  styleDeclarationList.children.append(ruleDeclarationItem);
                } else if (
                  matchedItem.data.important !== true &&
                  ruleDeclaration.important === true
                ) {
                  styleDeclarationList.children.replace(
                    matchedItem,
                    ruleDeclarationItem
                  );
                  styleDeclarationItems.set(
                    ruleDeclaration.property,
                    ruleDeclarationItem
                  );
                }
              },
            });
            selectedEl.attributes.style =
              csstree.generate(styleDeclarationList);
          }

          if (
            removeMatchedSelectors &&
            matchedElements.length !== 0 &&
            selector.rule.prelude.type === 'SelectorList'
          ) {
            // clean up matching simple selectors if option removeMatchedSelectors is enabled
            selector.rule.prelude.children.remove(selector.item);
          }
          selector.matchedElements = matchedElements;
        }

        // no further processing required
        if (removeMatchedSelectors === false) {
          return;
        }

        // clean up matched class + ID attribute values
        for (const selector of sortedSelectors) {
          if (selector.matchedElements == null) {
            continue;
          }

          if (onlyMatchedOnce && selector.matchedElements.length > 1) {
            // skip selectors that match more than once if option onlyMatchedOnce is enabled
            continue;
          }

          for (const selectedEl of selector.matchedElements) {
            // class
            const classList = new Set(
              selectedEl.attributes.class == null
                ? null
                : selectedEl.attributes.class.split(' ')
            );
            const firstSubSelector = selector.node.children.first();
            if (
              firstSubSelector != null &&
              firstSubSelector.type === 'ClassSelector'
            ) {
              classList.delete(firstSubSelector.name);
            }
            if (classList.size === 0) {
              delete selectedEl.attributes.class;
            } else {
              selectedEl.attributes.class = Array.from(classList).join(' ');
            }

            // ID
            if (
              firstSubSelector != null &&
              firstSubSelector.type === 'IdSelector'
            ) {
              if (selectedEl.attributes.id === firstSubSelector.name) {
                delete selectedEl.attributes.id;
              }
            }
          }
        }

        for (const style of styles) {
          csstree.walk(style.cssAst, {
            visit: 'Rule',
            enter: function (node, item, list) {
              // clean up <style/> rulesets without any css selectors left
              if (
                node.type === 'Rule' &&
                node.prelude.type === 'SelectorList' &&
                node.prelude.children.isEmpty()
              ) {
                list.remove(item);
              }
            },
          });

          if (style.cssAst.children.isEmpty()) {
            // remove emtpy style element
            detachNodeFromParent(style.node, style.parentNode);
          } else {
            // update style element if any styles left
            const firstChild = style.node.children[0];
            if (firstChild.type === 'text' || firstChild.type === 'cdata') {
              firstChild.value = csstree.generate(style.cssAst);
            }
          }
        }
      },
    },
  };
};


code:
'use strict';

const { detachNodeFromParent } = require('../lib/xast.js');
const { collectStylesheet, computeStyle } = require('../lib/style.js');
const { path2js, js2path, intersects } = require('./_path.js');

exports.type = 'visitor';
exports.name = 'mergePaths';
exports.active = true;
exports.description = 'merges multiple paths in one if possible';

/**
 * Merge multiple Paths into one.
 *
 * @author Kir Belevich, Lev Solntsev
 *
 * @type {import('../lib/types').Plugin<{
 *   force?: boolean,
 *   floatPrecision?: number,
 *   noSpaceAfterFlags?: boolean
 * }>}
 */
exports.fn = (root, params) => {
  const {
    force = false,
    floatPrecision,
    noSpaceAfterFlags = false, // a20 60 45 0 1 30 20 → a20 60 45 0130 20
  } = params;
  const stylesheet = collectStylesheet(root);

  return {
    element: {
      enter: (node) => {
        let prevChild = null;

        for (const child of node.children) {
          // skip if previous element is not path or contains animation elements
          if (
            prevChild == null ||
            prevChild.type !== 'element' ||
            prevChild.name !== 'path' ||
            prevChild.children.length !== 0 ||
            prevChild.attributes.d == null
          ) {
            prevChild = child;
            continue;
          }

          // skip if element is not path or contains animation elements
          if (
            child.type !== 'element' ||
            child.name !== 'path' ||
            child.children.length !== 0 ||
            child.attributes.d == null
          ) {
            prevChild = child;
            continue;
          }

          // preserve paths with markers
          const computedStyle = computeStyle(stylesheet, child);
          if (
            computedStyle['marker-start'] ||
            computedStyle['marker-mid'] ||
            computedStyle['marker-end']
          ) {
            prevChild = child;
            continue;
          }

          const prevChildAttrs = Object.keys(prevChild.attributes);
          const childAttrs = Object.keys(child.attributes);
          let attributesAreEqual = prevChildAttrs.length === childAttrs.length;
          for (const name of childAttrs) {
            if (name !== 'd') {
              if (
                prevChild.attributes[name] == null ||
                prevChild.attributes[name] !== child.attributes[name]
              ) {
                attributesAreEqual = false;
              }
            }
          }
          const prevPathJS = path2js(prevChild);
          const curPathJS = path2js(child);

          if (
            attributesAreEqual &&
            (force || !intersects(prevPathJS, curPathJS))
          ) {
            js2path(prevChild, prevPathJS.concat(curPathJS), {
              floatPrecision,
              noSpaceAfterFlags,
            });
            detachNodeFromParent(child, node);
            continue;
          }

          prevChild = child;
        }
      },
    },
  };
};


code:
'use strict';

/**
 * @typedef {import('../lib/types').XastElement} XastElement
 */

const { visitSkip, detachNodeFromParent } = require('../lib/xast.js');
const JSAPI = require('../lib/svgo/jsAPI.js');

exports.name = 'mergeStyles';
exports.type = 'visitor';
exports.active = true;
exports.description = 'merge multiple style elements into one';

/**
 * Merge multiple style elements into one.
 *
 * @author strarsis <strarsis@gmail.com>
 *
 * @type {import('../lib/types').Plugin<void>}
 */
exports.fn = () => {
  /**
   * @type {null | XastElement}
   */
  let firstStyleElement = null;
  let collectedStyles = '';
  let styleContentType = 'text';

  return {
    element: {
      enter: (node, parentNode) => {
        // skip <foreignObject> content
        if (node.name === 'foreignObject') {
          return visitSkip;
        }

        // collect style elements
        if (node.name !== 'style') {
          return;
        }

        // skip <style> with invalid type attribute
        if (
          node.attributes.type != null &&
          node.attributes.type !== '' &&
          node.attributes.type !== 'text/css'
        ) {
          return;
        }

        // extract style element content
        let css = '';
        for (const child of node.children) {
          if (child.type === 'text') {
            css += child.value;
          }
          if (child.type === 'cdata') {
            styleContentType = 'cdata';
            css += child.value;
          }
        }

        // remove empty style elements
        if (css.trim().length === 0) {
          detachNodeFromParent(node, parentNode);
          return;
        }

        // collect css and wrap with media query if present in attribute
        if (node.attributes.media == null) {
          collectedStyles += css;
        } else {
          collectedStyles += `@media ${node.attributes.media}{${css}}`;
          delete node.attributes.media;
        }

        // combine collected styles in the first style element
        if (firstStyleElement == null) {
          firstStyleElement = node;
        } else {
          detachNodeFromParent(node, parentNode);
          firstStyleElement.children = [
            new JSAPI(
              { type: styleContentType, value: collectedStyles },
              firstStyleElement
            ),
          ];
        }
      },
    },
  };
};


code:
'use strict';

/**
 * @typedef {import('../lib/types').XastElement} XastElement
 */

const csso = require('csso');

exports.type = 'visitor';
exports.name = 'minifyStyles';
exports.active = true;
exports.description =
  'minifies styles and removes unused styles based on usage data';

/**
 * Minifies styles (<style> element + style attribute) using CSSO
 *
 * @author strarsis <strarsis@gmail.com>
 *
 * @type {import('../lib/types').Plugin<csso.MinifyOptions & Omit<csso.CompressOptions, 'usage'> & {
 *   usage?: boolean | {
 *     force?: boolean,
 *     ids?: boolean,
 *     classes?: boolean,
 *     tags?: boolean
 *   }
 * }>}
 */
exports.fn = (_root, { usage, ...params }) => {
  let enableTagsUsage = true;
  let enableIdsUsage = true;
  let enableClassesUsage = true;
  // force to use usage data even if it unsafe (document contains <script> or on* attributes)
  let forceUsageDeoptimized = false;
  if (typeof usage === 'boolean') {
    enableTagsUsage = usage;
    enableIdsUsage = usage;
    enableClassesUsage = usage;
  } else if (usage) {
    enableTagsUsage = usage.tags == null ? true : usage.tags;
    enableIdsUsage = usage.ids == null ? true : usage.ids;
    enableClassesUsage = usage.classes == null ? true : usage.classes;
    forceUsageDeoptimized = usage.force == null ? false : usage.force;
  }
  /**
   * @type {Array<XastElement>}
   */
  const styleElements = [];
  /**
   * @type {Array<XastElement>}
   */
  const elementsWithStyleAttributes = [];
  let deoptimized = false;
  /**
   * @type {Set<string>}
   */
  const tagsUsage = new Set();
  /**
   * @type {Set<string>}
   */
  const idsUsage = new Set();
  /**
   * @type {Set<string>}
   */
  const classesUsage = new Set();

  return {
    element: {
      enter: (node) => {
        // detect deoptimisations
        if (node.name === 'script') {
          deoptimized = true;
        }
        for (const name of Object.keys(node.attributes)) {
          if (name.startsWith('on')) {
            deoptimized = true;
          }
        }
        // collect tags, ids and classes usage
        tagsUsage.add(node.name);
        if (node.attributes.id != null) {
          idsUsage.add(node.attributes.id);
        }
        if (node.attributes.class != null) {
          for (const className of node.attributes.class.split(/\s+/)) {
            classesUsage.add(className);
          }
        }
        // collect style elements or elements with style attribute
        if (node.name === 'style' && node.children.length !== 0) {
          styleElements.push(node);
        } else if (node.attributes.style != null) {
          elementsWithStyleAttributes.push(node);
        }
      },
    },

    root: {
      exit: () => {
        /**
         * @type {csso.Usage}
         */
        const cssoUsage = {};
        if (deoptimized === false || forceUsageDeoptimized === true) {
          if (enableTagsUsage && tagsUsage.size !== 0) {
            cssoUsage.tags = Array.from(tagsUsage);
          }
          if (enableIdsUsage && idsUsage.size !== 0) {
            cssoUsage.ids = Array.from(idsUsage);
          }
          if (enableClassesUsage && classesUsage.size !== 0) {
            cssoUsage.classes = Array.from(classesUsage);
          }
        }
        // minify style elements
        for (const node of styleElements) {
          if (
            node.children[0].type === 'text' ||
            node.children[0].type === 'cdata'
          ) {
            const cssText = node.children[0].value;
            const minified = csso.minify(cssText, {
              ...params,
              usage: cssoUsage,
            }).css;
            // preserve cdata if necessary
            // TODO split cdata -> text optimisation into separate plugin
            if (cssText.indexOf('>') >= 0 || cssText.indexOf('<') >= 0) {
              node.children[0].type = 'cdata';
              node.children[0].value = minified;
            } else {
              node.children[0].type = 'text';
              node.children[0].value = minified;
            }
          }
        }
        // minify style attributes
        for (const node of elementsWithStyleAttributes) {
          // style attribute
          const elemStyle = node.attributes.style;
          node.attributes.style = csso.minifyBlock(elemStyle, {
            ...params,
          }).css;
        }
      },
    },
  };
};


code:
'use strict';

const { visit } = require('../lib/xast.js');
const { inheritableAttrs, pathElems } = require('./_collections.js');

exports.type = 'visitor';
exports.name = 'moveElemsAttrsToGroup';
exports.active = true;
exports.description = 'Move common attributes of group children to the group';

/**
 * Move common attributes of group children to the group
 *
 * @example
 * <g attr1="val1">
 *     <g attr2="val2">
 *         text
 *     </g>
 *     <circle attr2="val2" attr3="val3"/>
 * </g>
 *              ⬇
 * <g attr1="val1" attr2="val2">
 *     <g>
 *         text
 *     </g>
 *    <circle attr3="val3"/>
 * </g>
 *
 * @author Kir Belevich
 *
 * @type {import('../lib/types').Plugin<void>}
 */
exports.fn = (root) => {
  // find if any style element is present
  let deoptimizedWithStyles = false;
  visit(root, {
    element: {
      enter: (node) => {
        if (node.name === 'style') {
          deoptimizedWithStyles = true;
        }
      },
    },
  });

  return {
    element: {
      exit: (node) => {
        // process only groups with more than 1 children
        if (node.name !== 'g' || node.children.length <= 1) {
          return;
        }

        // deoptimize the plugin when style elements are present
        // selectors may rely on id, classes or tag names
        if (deoptimizedWithStyles) {
          return;
        }

        /**
         * find common attributes in group children
         * @type {Map<string, string>}
         */
        const commonAttributes = new Map();
        let initial = true;
        let everyChildIsPath = true;
        for (const child of node.children) {
          if (child.type === 'element') {
            if (pathElems.includes(child.name) === false) {
              everyChildIsPath = false;
            }
            if (initial) {
              initial = false;
              // collect all inheritable attributes from first child element
              for (const [name, value] of Object.entries(child.attributes)) {
                // consider only inheritable attributes
                if (inheritableAttrs.includes(name)) {
                  commonAttributes.set(name, value);
                }
              }
            } else {
              // exclude uncommon attributes from initial list
              for (const [name, value] of commonAttributes) {
                if (child.attributes[name] !== value) {
                  commonAttributes.delete(name);
                }
              }
            }
          }
        }

        // preserve transform on children when group has clip-path or mask
        if (
          node.attributes['clip-path'] != null ||
          node.attributes.mask != null
        ) {
          commonAttributes.delete('transform');
        }

        // preserve transform when all children are paths
        // so the transform could be applied to path data by other plugins
        if (everyChildIsPath) {
          commonAttributes.delete('transform');
        }

        // add common children attributes to group
        for (const [name, value] of commonAttributes) {
          if (name === 'transform') {
            if (node.attributes.transform != null) {
              node.attributes.transform = `${node.attributes.transform} ${value}`;
            } else {
              node.attributes.transform = value;
            }
          } else {
            node.attributes[name] = value;
          }
        }

        // delete common attributes from children
        for (const child of node.children) {
          if (child.type === 'element') {
            for (const [name] of commonAttributes) {
              delete child.attributes[name];
            }
          }
        }
      },
    },
  };
};