This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

21
node_modules/svgo/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Kir Belevich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

294
node_modules/svgo/README.md generated vendored Normal file
View File

@@ -0,0 +1,294 @@
<div align="center">
<img src="./logo/logo-web.svg" width="348.61" height="100" alt="SVGO logo"/>
</div>
## SVGO [![npm version](https://img.shields.io/npm/v/svgo)](https://npmjs.org/package/svgo) [![Discord](https://img.shields.io/discord/815166721315831868)](https://discord.gg/z8jX8NYxrE)
**SVG O**ptimizer is a Node.js-based tool for optimizing SVG vector graphics files.
## Why?
SVG files, especially those exported from various editors, usually contain a lot of redundant and useless information. This can include editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting the SVG rendering result.
## Installation
```sh
npm -g install svgo
```
or
```sh
yarn global add svgo
```
## CLI usage
```sh
svgo one.svg two.svg -o one.min.svg two.min.svg
```
Or use the `--folder`/`-f` flag to optimize a whole folder of SVG icons
```sh
svgo -f ./path/to/folder/with/svg/files -o ./path/to/folder/with/svg/output
```
See help for advanced usage
```sh
svgo --help
```
## Configuration
Some options can be configured with CLI though it may be easier to have the configuration in a separate file.
SVGO automatically loads configuration from `svgo.config.js` or module specified with `--config` flag.
```js
module.exports = {
multipass: true, // boolean. false by default
datauri: 'enc', // 'base64', 'enc' or 'unenc'. 'base64' by default
js2svg: {
indent: 2, // string with spaces or number of spaces. 4 by default
pretty: true, // boolean, false by default
},
};
```
SVGO has a plugin-based architecture, so almost every optimization is a separate plugin.
There is a set of [built-in plugins](#built-in-plugins). See how to configure them:
```js
module.exports = {
plugins: [
// enable a built-in plugin by name
'prefixIds',
// or by expanded version
{
name: 'prefixIds',
},
// some plugins allow/require to pass options
{
name: 'prefixIds',
params: {
prefix: 'my-prefix',
},
},
],
};
```
The default preset of plugins is fully overridden if the `plugins` field is specified.
Use `preset-default` plugin to customize plugins options.
```js
module.exports = {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
// customize options for plugins included in preset
inlineStyles: {
onlyMatchedOnce: false,
},
// or disable plugins
removeDoctype: false,
},
},
},
// enable builtin plugin not included in default preset
'prefixIds',
// enable and configure builtin plugin not included in preset
{
name: 'sortAttrs',
params: {
xmlnsOrder: 'alphabetical',
},
},
],
};
```
Default preset includes the following list of plugins:
- removeDoctype
- removeXMLProcInst
- removeComments
- removeMetadata
- removeEditorsNSData
- cleanupAttrs
- mergeStyles
- inlineStyles
- minifyStyles
- cleanupIDs
- removeUselessDefs
- cleanupNumericValues
- convertColors
- removeUnknownsAndDefaults
- removeNonInheritableGroupAttrs
- removeUselessStrokeAndFill
- removeViewBox
- cleanupEnableBackground
- removeHiddenElems
- removeEmptyText
- convertShapeToPath
- convertEllipseToCircle
- moveElemsAttrsToGroup
- moveGroupAttrsToElems
- collapseGroups
- convertPathData
- convertTransform
- removeEmptyAttrs
- removeEmptyContainers
- mergePaths
- removeUnusedNS
- sortDefsChildren
- removeTitle
- removeDesc
It's also possible to specify a custom plugin:
```js
const anotherCustomPlugin = require('./another-custom-plugin.js');
module.exports = {
plugins: [
{
name: 'customPluginName',
type: 'perItem', // 'perItem', 'perItemReverse' or 'full'
params: {
optionName: 'optionValue',
},
fn: (ast, params, info) => {},
},
anotherCustomPlugin,
],
};
```
## API usage
SVGO provides a few low level utilities.
### optimize
The core of SVGO is `optimize` function.
```js
const { optimize } = require('svgo');
const result = optimize(svgString, {
// optional but recommended field
path: 'path-to.svg',
// all config fields are also available here
multipass: true,
});
const optimizedSvgString = result.data;
```
### loadConfig
If you write a tool on top of SVGO you might need a way to load SVGO config.
```js
const { loadConfig } = require('svgo');
const config = await loadConfig();
// you can also specify a relative or absolute path and customize the current working directory
const config = await loadConfig(configFile, cwd);
```
## Built-in plugins
| Plugin | Description | Default |
| ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| [cleanupAttrs](https://github.com/svg/svgo/blob/master/plugins/cleanupAttrs.js) | cleanup attributes from newlines, trailing, and repeating spaces | `enabled` |
| [mergeStyles](https://github.com/svg/svgo/blob/master/plugins/mergeStyles.js) | merge multiple style elements into one | `enabled` |
| [inlineStyles](https://github.com/svg/svgo/blob/master/plugins/inlineStyles.js) | move and merge styles from `<style>` elements to element `style` attributes | `enabled` |
| [removeDoctype](https://github.com/svg/svgo/blob/master/plugins/removeDoctype.js) | remove `doctype` declaration | `enabled` |
| [removeXMLProcInst](https://github.com/svg/svgo/blob/master/plugins/removeXMLProcInst.js) | remove XML processing instructions | `enabled` |
| [removeComments](https://github.com/svg/svgo/blob/master/plugins/removeComments.js) | remove comments | `enabled` |
| [removeMetadata](https://github.com/svg/svgo/blob/master/plugins/removeMetadata.js) | remove `<metadata>` | `enabled` |
| [removeTitle](https://github.com/svg/svgo/blob/master/plugins/removeTitle.js) | remove `<title>` | `enabled` |
| [removeDesc](https://github.com/svg/svgo/blob/master/plugins/removeDesc.js) | remove `<desc>` | `enabled` |
| [removeUselessDefs](https://github.com/svg/svgo/blob/master/plugins/removeUselessDefs.js) | remove elements of `<defs>` without `id` | `enabled` |
| [removeXMLNS](https://github.com/svg/svgo/blob/master/plugins/removeXMLNS.js) | removes the `xmlns` attribute (for inline SVG) | `disabled` |
| [removeEditorsNSData](https://github.com/svg/svgo/blob/master/plugins/removeEditorsNSData.js) | remove editors namespaces, elements, and attributes | `enabled` |
| [removeEmptyAttrs](https://github.com/svg/svgo/blob/master/plugins/removeEmptyAttrs.js) | remove empty attributes | `enabled` |
| [removeHiddenElems](https://github.com/svg/svgo/blob/master/plugins/removeHiddenElems.js) | remove hidden elements | `enabled` |
| [removeEmptyText](https://github.com/svg/svgo/blob/master/plugins/removeEmptyText.js) | remove empty Text elements | `enabled` |
| [removeEmptyContainers](https://github.com/svg/svgo/blob/master/plugins/removeEmptyContainers.js) | remove empty Container elements | `enabled` |
| [removeViewBox](https://github.com/svg/svgo/blob/master/plugins/removeViewBox.js) | remove `viewBox` attribute when possible | `enabled` |
| [cleanupEnableBackground](https://github.com/svg/svgo/blob/master/plugins/cleanupEnableBackground.js) | remove or cleanup `enable-background` attribute when possible | `enabled` |
| [minifyStyles](https://github.com/svg/svgo/blob/master/plugins/minifyStyles.js) | minify `<style>` elements content with [CSSO](https://github.com/css/csso) | `enabled` |
| [convertStyleToAttrs](https://github.com/svg/svgo/blob/master/plugins/convertStyleToAttrs.js) | convert styles into attributes | `disabled` |
| [convertColors](https://github.com/svg/svgo/blob/master/plugins/convertColors.js) | convert colors (from `rgb()` to `#rrggbb`, from `#rrggbb` to `#rgb`) | `enabled` |
| [convertPathData](https://github.com/svg/svgo/blob/master/plugins/convertPathData.js) | convert Path data to relative or absolute (whichever is shorter), convert one segment to another, trim useless delimiters, smart rounding, and much more | `enabled` |
| [convertTransform](https://github.com/svg/svgo/blob/master/plugins/convertTransform.js) | collapse multiple transforms into one, convert matrices to the short aliases, and much more | `enabled` |
| [removeUnknownsAndDefaults](https://github.com/svg/svgo/blob/master/plugins/removeUnknownsAndDefaults.js) | remove unknown elements content and attributes, remove attributes with default values | `enabled` |
| [removeNonInheritableGroupAttrs](https://github.com/svg/svgo/blob/master/plugins/removeNonInheritableGroupAttrs.js) | remove non-inheritable group's "presentation" attributes | `enabled` |
| [removeUselessStrokeAndFill](https://github.com/svg/svgo/blob/master/plugins/removeUselessStrokeAndFill.js) | remove useless `stroke` and `fill` attributes | `enabled` |
| [removeUnusedNS](https://github.com/svg/svgo/blob/master/plugins/removeUnusedNS.js) | remove unused namespaces declaration | `enabled` |
| [prefixIds](https://github.com/svg/svgo/blob/master/plugins/prefixIds.js) | prefix IDs and classes with the SVG filename or an arbitrary string | `disabled` |
| [cleanupIDs](https://github.com/svg/svgo/blob/master/plugins/cleanupIDs.js) | remove unused and minify used IDs | `enabled` |
| [cleanupNumericValues](https://github.com/svg/svgo/blob/master/plugins/cleanupNumericValues.js) | round numeric values to the fixed precision, remove default `px` units | `enabled` |
| [cleanupListOfValues](https://github.com/svg/svgo/blob/master/plugins/cleanupListOfValues.js) | round numeric values in attributes that take a list of numbers (like `viewBox` or `enable-background`) | `disabled` |
| [moveElemsAttrsToGroup](https://github.com/svg/svgo/blob/master/plugins/moveElemsAttrsToGroup.js) | move elements' attributes to their enclosing group | `enabled` |
| [moveGroupAttrsToElems](https://github.com/svg/svgo/blob/master/plugins/moveGroupAttrsToElems.js) | move some group attributes to the contained elements | `enabled` |
| [collapseGroups](https://github.com/svg/svgo/blob/master/plugins/collapseGroups.js) | collapse useless groups | `enabled` |
| [removeRasterImages](https://github.com/svg/svgo/blob/master/plugins/removeRasterImages.js) | remove raster images | `disabled` |
| [mergePaths](https://github.com/svg/svgo/blob/master/plugins/mergePaths.js) | merge multiple Paths into one | `enabled` |
| [convertShapeToPath](https://github.com/svg/svgo/blob/master/plugins/convertShapeToPath.js) | convert some basic shapes to `<path>` | `enabled` |
| [convertEllipseToCircle](https://github.com/svg/svgo/blob/master/plugins/convertEllipseToCircle.js) | convert non-eccentric `<ellipse>` to `<circle>` | `enabled` |
| [sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) | sort element attributes for epic readability | `disabled` |
| [sortDefsChildren](https://github.com/svg/svgo/blob/master/plugins/sortDefsChildren.js) | sort children of `<defs>` in order to improve compression | `enabled` |
| [removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) | remove `width`/`height` and add `viewBox` if it's missing (opposite to removeViewBox, disable it first) | `disabled` |
| [removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) | remove attributes by pattern | `disabled` |
| [removeAttributesBySelector](https://github.com/svg/svgo/blob/master/plugins/removeAttributesBySelector.js) | removes attributes of elements that match a CSS selector | `disabled` |
| [removeElementsByAttr](https://github.com/svg/svgo/blob/master/plugins/removeElementsByAttr.js) | remove arbitrary elements by `ID` or `className` | `disabled` |
| [addClassesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addClassesToSVGElement.js) | add classnames to an outer `<svg>` element | `disabled` |
| [addAttributesToSVGElement](https://github.com/svg/svgo/blob/master/plugins/addAttributesToSVGElement.js) | adds attributes to an outer `<svg>` element | `disabled` |
| [removeOffCanvasPaths](https://github.com/svg/svgo/blob/master/plugins/removeOffCanvasPaths.js) | removes elements that are drawn outside of the viewbox | `disabled` |
| [removeStyleElement](https://github.com/svg/svgo/blob/master/plugins/removeStyleElement.js) | remove `<style>` elements | `disabled` |
| [removeScriptElement](https://github.com/svg/svgo/blob/master/plugins/removeScriptElement.js) | remove `<script>` elements | `disabled` |
| [reusePaths](https://github.com/svg/svgo/blob/master/plugins/reusePaths.js) | Find duplicated <path> elements and replace them with <use> links | `disabled` |
## Other Ways to Use SVGO
- as a web app [SVGOMG](https://jakearchibald.github.io/svgomg/)
- as a GitHub Action [SVGO Action](https://github.com/marketplace/actions/svgo-action)
- as a Grunt task [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin)
- as a Gulp task [gulp-svgmin](https://github.com/ben-eb/gulp-svgmin)
- as a Mimosa module [mimosa-minify-svg](https://github.com/dbashford/mimosa-minify-svg)
- as an OSX Folder Action [svgo-osx-folder-action](https://github.com/svg/svgo-osx-folder-action)
- as a webpack loader [image-webpack-loader](https://github.com/tcoopman/image-webpack-loader)
- as a Telegram Bot [svgo_bot](https://github.com/maksugr/svgo_bot)
- as a PostCSS plugin [postcss-svgo](https://github.com/ben-eb/postcss-svgo)
- as an Inkscape plugin [inkscape-svgo](https://github.com/konsumer/inkscape-svgo)
- as a Sketch plugin - [svgo-compressor](https://github.com/BohemianCoding/svgo-compressor)
- as a macOS app - [Image Shrinker](https://image-shrinker.com)
- as a Rollup plugin - [rollup-plugin-svgo](https://github.com/porsager/rollup-plugin-svgo)
- as a VS Code plugin - [vscode-svgo](https://github.com/1000ch/vscode-svgo)
- as a Atom plugin - [atom-svgo](https://github.com/1000ch/atom-svgo)
- as a Sublime plugin - [Sublime-svgo](https://github.com/1000ch/Sublime-svgo)
- as a Figma plugin - [Advanced SVG Export](https://www.figma.com/c/plugin/782713260363070260/Advanced-SVG-Export)
- as a Linux app - [Oh My SVG](https://github.com/sonnyp/OhMySVG)
- as a Browser extension - [SVG Gobbler](https://github.com/rossmoody/svg-gobbler)
- as an API - [Vector Express](https://github.com/smidyo/vectorexpress-api#convertor-svgo)
## Donators
| [<img src="https://sheetjs.com/sketch128.png" width="80">](https://sheetjs.com/) | [<img src="https://raw.githubusercontent.com/fontello/fontello/master/fontello-image.svg" width="80">](https://fontello.com/) |
| :------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------: |
| [SheetJS LLC](https://sheetjs.com/) | [Fontello](https://fontello.com/) |
## License and Copyright
This software is released under the terms of the [MIT license](https://github.com/svg/svgo/blob/master/LICENSE).
Logo by [André Castillo](https://github.com/DerianAndre).

10
node_modules/svgo/bin/svgo generated vendored Executable file
View File

@@ -0,0 +1,10 @@
#!/usr/bin/env node
const colors = require('picocolors');
const { program } = require('commander');
const makeProgram = require('../lib/svgo/coa');
makeProgram(program);
program.parseAsync(process.argv).catch(error => {
console.error(colors.red(error.stack));
process.exit(1);
});

1
node_modules/svgo/dist/svgo.browser.js generated vendored Normal file

File diff suppressed because one or more lines are too long

239
node_modules/svgo/lib/css-tools.js generated vendored Normal file
View File

@@ -0,0 +1,239 @@
'use strict';
var csstree = require('css-tree'),
List = csstree.List,
stable = require('stable'),
specificity = require('csso/lib/restructure/prepare/specificity');
/**
* Flatten a CSS AST to a selectors list.
*
* @param {import('css-tree').CssNode} cssAst css-tree AST to flatten
* @return {Array} selectors
*/
function flattenToSelectors(cssAst) {
var selectors = [];
csstree.walk(cssAst, {
visit: 'Rule',
enter: function (node) {
if (node.type !== 'Rule') {
return;
}
var atrule = this.atrule;
var rule = node;
node.prelude.children.each(function (selectorNode, selectorItem) {
var selector = {
item: selectorItem,
atrule: atrule,
rule: rule,
pseudos: /** @type {{item: any; list: any[]}[]} */ ([]),
};
selectorNode.children.each(function (
selectorChildNode,
selectorChildItem,
selectorChildList
) {
if (
selectorChildNode.type === 'PseudoClassSelector' ||
selectorChildNode.type === 'PseudoElementSelector'
) {
selector.pseudos.push({
item: selectorChildItem,
list: selectorChildList,
});
}
});
selectors.push(selector);
});
},
});
return selectors;
}
/**
* Filter selectors by Media Query.
*
* @param {Array} selectors to filter
* @param {Array} useMqs Array with strings of media queries that should pass (<name> <expression>)
* @return {Array} Filtered selectors that match the passed media queries
*/
function filterByMqs(selectors, useMqs) {
return selectors.filter(function (selector) {
if (selector.atrule === null) {
return ~useMqs.indexOf('');
}
var mqName = selector.atrule.name;
var mqStr = mqName;
if (
selector.atrule.expression &&
selector.atrule.expression.children.first().type === 'MediaQueryList'
) {
var mqExpr = csstree.generate(selector.atrule.expression);
mqStr = [mqName, mqExpr].join(' ');
}
return ~useMqs.indexOf(mqStr);
});
}
/**
* Filter selectors by the pseudo-elements and/or -classes they contain.
*
* @param {Array} selectors to filter
* @param {Array} usePseudos Array with strings of single or sequence of pseudo-elements and/or -classes that should pass
* @return {Array} Filtered selectors that match the passed pseudo-elements and/or -classes
*/
function filterByPseudos(selectors, usePseudos) {
return selectors.filter(function (selector) {
var pseudoSelectorsStr = csstree.generate({
type: 'Selector',
children: new List().fromArray(
selector.pseudos.map(function (pseudo) {
return pseudo.item.data;
})
),
});
return ~usePseudos.indexOf(pseudoSelectorsStr);
});
}
/**
* Remove pseudo-elements and/or -classes from the selectors for proper matching.
*
* @param {Array} selectors to clean
* @return {void}
*/
function cleanPseudos(selectors) {
selectors.forEach(function (selector) {
selector.pseudos.forEach(function (pseudo) {
pseudo.list.remove(pseudo.item);
});
});
}
/**
* Compares two selector specificities.
* extracted from https://github.com/keeganstreet/specificity/blob/master/specificity.js#L211
*
* @param {Array} aSpecificity Specificity of selector A
* @param {Array} bSpecificity Specificity of selector B
* @return {number} Score of selector specificity A compared to selector specificity B
*/
function compareSpecificity(aSpecificity, bSpecificity) {
for (var i = 0; i < 4; i += 1) {
if (aSpecificity[i] < bSpecificity[i]) {
return -1;
} else if (aSpecificity[i] > bSpecificity[i]) {
return 1;
}
}
return 0;
}
/**
* Compare two simple selectors.
*
* @param {Object} aSimpleSelectorNode Simple selector A
* @param {Object} bSimpleSelectorNode Simple selector B
* @return {number} Score of selector A compared to selector B
*/
function compareSimpleSelectorNode(aSimpleSelectorNode, bSimpleSelectorNode) {
var aSpecificity = specificity(aSimpleSelectorNode),
bSpecificity = specificity(bSimpleSelectorNode);
return compareSpecificity(aSpecificity, bSpecificity);
}
function _bySelectorSpecificity(selectorA, selectorB) {
return compareSimpleSelectorNode(selectorA.item.data, selectorB.item.data);
}
/**
* Sort selectors stably by their specificity.
*
* @param {Array} selectors to be sorted
* @return {Array} Stable sorted selectors
*/
function sortSelectors(selectors) {
return stable(selectors, _bySelectorSpecificity);
}
/**
* Convert a css-tree AST style declaration to CSSStyleDeclaration property.
*
* @param {import('css-tree').CssNode} declaration css-tree style declaration
* @return {Object} CSSStyleDeclaration property
*/
function csstreeToStyleDeclaration(declaration) {
var propertyName = declaration.property,
propertyValue = csstree.generate(declaration.value),
propertyPriority = declaration.important ? 'important' : '';
return {
name: propertyName,
value: propertyValue,
priority: propertyPriority,
};
}
/**
* Gets the CSS string of a style element
*
* @param {Object} elem style element
* @return {string} CSS string or empty array if no styles are set
*/
function getCssStr(elem) {
if (
elem.children.length > 0 &&
(elem.children[0].type === 'text' || elem.children[0].type === 'cdata')
) {
return elem.children[0].value;
}
return '';
}
/**
* Sets the CSS string of a style element
*
* @param {Object} elem style element
* @param {string} css string to be set
* @return {string} reference to field with CSS
*/
function setCssStr(elem, css) {
if (elem.children.length === 0) {
elem.children.push({
type: 'text',
value: '',
});
}
if (elem.children[0].type !== 'text' && elem.children[0].type !== 'cdata') {
return css;
}
elem.children[0].value = css;
return css;
}
module.exports.flattenToSelectors = flattenToSelectors;
module.exports.filterByMqs = filterByMqs;
module.exports.filterByPseudos = filterByPseudos;
module.exports.cleanPseudos = cleanPseudos;
module.exports.compareSpecificity = compareSpecificity;
module.exports.compareSimpleSelectorNode = compareSimpleSelectorNode;
module.exports.sortSelectors = sortSelectors;
module.exports.csstreeToStyleDeclaration = csstreeToStyleDeclaration;
module.exports.getCssStr = getCssStr;
module.exports.setCssStr = setCssStr;

259
node_modules/svgo/lib/parser.js generated vendored Normal file
View File

@@ -0,0 +1,259 @@
'use strict';
/**
* @typedef {import('./types').XastNode} XastNode
* @typedef {import('./types').XastInstruction} XastInstruction
* @typedef {import('./types').XastDoctype} XastDoctype
* @typedef {import('./types').XastComment} XastComment
* @typedef {import('./types').XastRoot} XastRoot
* @typedef {import('./types').XastElement} XastElement
* @typedef {import('./types').XastCdata} XastCdata
* @typedef {import('./types').XastText} XastText
* @typedef {import('./types').XastParent} XastParent
*/
// @ts-ignore sax will be replaced with something else later
const SAX = require('@trysound/sax');
const JSAPI = require('./svgo/jsAPI.js');
const { textElems } = require('../plugins/_collections.js');
class SvgoParserError extends Error {
/**
* @param message {string}
* @param line {number}
* @param column {number}
* @param source {string}
* @param file {void | string}
*/
constructor(message, line, column, source, file) {
super(message);
this.name = 'SvgoParserError';
this.message = `${file || '<input>'}:${line}:${column}: ${message}`;
this.reason = message;
this.line = line;
this.column = column;
this.source = source;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, SvgoParserError);
}
}
toString() {
const lines = this.source.split(/\r?\n/);
const startLine = Math.max(this.line - 3, 0);
const endLine = Math.min(this.line + 2, lines.length);
const lineNumberWidth = String(endLine).length;
const startColumn = Math.max(this.column - 54, 0);
const endColumn = Math.max(this.column + 20, 80);
const code = lines
.slice(startLine, endLine)
.map((line, index) => {
const lineSlice = line.slice(startColumn, endColumn);
let ellipsisPrefix = '';
let ellipsisSuffix = '';
if (startColumn !== 0) {
ellipsisPrefix = startColumn > line.length - 1 ? ' ' : '…';
}
if (endColumn < line.length - 1) {
ellipsisSuffix = '…';
}
const number = startLine + 1 + index;
const gutter = ` ${number.toString().padStart(lineNumberWidth)} | `;
if (number === this.line) {
const gutterSpacing = gutter.replace(/[^|]/g, ' ');
const lineSpacing = (
ellipsisPrefix + line.slice(startColumn, this.column - 1)
).replace(/[^\t]/g, ' ');
const spacing = gutterSpacing + lineSpacing;
return `>${gutter}${ellipsisPrefix}${lineSlice}${ellipsisSuffix}\n ${spacing}^`;
}
return ` ${gutter}${ellipsisPrefix}${lineSlice}${ellipsisSuffix}`;
})
.join('\n');
return `${this.name}: ${this.message}\n\n${code}\n`;
}
}
const entityDeclaration = /<!ENTITY\s+(\S+)\s+(?:'([^']+)'|"([^"]+)")\s*>/g;
const config = {
strict: true,
trim: false,
normalize: false,
lowercase: true,
xmlns: true,
position: true,
};
/**
* Convert SVG (XML) string to SVG-as-JS object.
*
* @type {(data: string, from?: string) => XastRoot}
*/
const parseSvg = (data, from) => {
const sax = SAX.parser(config.strict, config);
/**
* @type {XastRoot}
*/
const root = new JSAPI({ type: 'root', children: [] });
/**
* @type {XastParent}
*/
let current = root;
/**
* @type {Array<XastParent>}
*/
const stack = [root];
/**
* @type {<T extends XastNode>(node: T) => T}
*/
const pushToContent = (node) => {
const wrapped = new JSAPI(node, current);
current.children.push(wrapped);
return wrapped;
};
/**
* @type {(doctype: string) => void}
*/
sax.ondoctype = (doctype) => {
/**
* @type {XastDoctype}
*/
const node = {
type: 'doctype',
// TODO parse doctype for name, public and system to match xast
name: 'svg',
data: {
doctype,
},
};
pushToContent(node);
const subsetStart = doctype.indexOf('[');
if (subsetStart >= 0) {
entityDeclaration.lastIndex = subsetStart;
let entityMatch = entityDeclaration.exec(data);
while (entityMatch != null) {
sax.ENTITIES[entityMatch[1]] = entityMatch[2] || entityMatch[3];
entityMatch = entityDeclaration.exec(data);
}
}
};
/**
* @type {(data: { name: string, body: string }) => void}
*/
sax.onprocessinginstruction = (data) => {
/**
* @type {XastInstruction}
*/
const node = {
type: 'instruction',
name: data.name,
value: data.body,
};
pushToContent(node);
};
/**
* @type {(comment: string) => void}
*/
sax.oncomment = (comment) => {
/**
* @type {XastComment}
*/
const node = {
type: 'comment',
value: comment.trim(),
};
pushToContent(node);
};
/**
* @type {(cdata: string) => void}
*/
sax.oncdata = (cdata) => {
/**
* @type {XastCdata}
*/
const node = {
type: 'cdata',
value: cdata,
};
pushToContent(node);
};
/**
* @type {(data: { name: string, attributes: Record<string, { value: string }>}) => void}
*/
sax.onopentag = (data) => {
/**
* @type {XastElement}
*/
let element = {
type: 'element',
name: data.name,
attributes: {},
children: [],
};
for (const [name, attr] of Object.entries(data.attributes)) {
element.attributes[name] = attr.value;
}
element = pushToContent(element);
current = element;
stack.push(element);
};
/**
* @type {(text: string) => void}
*/
sax.ontext = (text) => {
if (current.type === 'element') {
// prevent trimming of meaningful whitespace inside textual tags
if (textElems.includes(current.name)) {
/**
* @type {XastText}
*/
const node = {
type: 'text',
value: text,
};
pushToContent(node);
} else if (/\S/.test(text)) {
/**
* @type {XastText}
*/
const node = {
type: 'text',
value: text.trim(),
};
pushToContent(node);
}
}
};
sax.onclosetag = () => {
stack.pop();
current = stack[stack.length - 1];
};
/**
* @type {(e: any) => void}
*/
sax.onerror = (e) => {
const error = new SvgoParserError(
e.reason,
e.line + 1,
e.column,
data,
from
);
if (e.message.indexOf('Unexpected end') === -1) {
throw error;
}
};
sax.write(data).close();
return root;
};
exports.parseSvg = parseSvg;

347
node_modules/svgo/lib/path.js generated vendored Normal file
View File

@@ -0,0 +1,347 @@
'use strict';
/**
* @typedef {import('./types').PathDataItem} PathDataItem
* @typedef {import('./types').PathDataCommand} PathDataCommand
*/
// Based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF
const argsCountPerCommand = {
M: 2,
m: 2,
Z: 0,
z: 0,
L: 2,
l: 2,
H: 1,
h: 1,
V: 1,
v: 1,
C: 6,
c: 6,
S: 4,
s: 4,
Q: 4,
q: 4,
T: 2,
t: 2,
A: 7,
a: 7,
};
/**
* @type {(c: string) => c is PathDataCommand}
*/
const isCommand = (c) => {
return c in argsCountPerCommand;
};
/**
* @type {(c: string) => boolean}
*/
const isWsp = (c) => {
const codePoint = c.codePointAt(0);
return (
codePoint === 0x20 ||
codePoint === 0x9 ||
codePoint === 0xd ||
codePoint === 0xa
);
};
/**
* @type {(c: string) => boolean}
*/
const isDigit = (c) => {
const codePoint = c.codePointAt(0);
if (codePoint == null) {
return false;
}
return 48 <= codePoint && codePoint <= 57;
};
/**
* @typedef {'none' | 'sign' | 'whole' | 'decimal_point' | 'decimal' | 'e' | 'exponent_sign' | 'exponent'} ReadNumberState
*/
/**
* @type {(string: string, cursor: number) => [number, number | null]}
*/
const readNumber = (string, cursor) => {
let i = cursor;
let value = '';
let state = /** @type {ReadNumberState} */ ('none');
for (; i < string.length; i += 1) {
const c = string[i];
if (c === '+' || c === '-') {
if (state === 'none') {
state = 'sign';
value += c;
continue;
}
if (state === 'e') {
state = 'exponent_sign';
value += c;
continue;
}
}
if (isDigit(c)) {
if (state === 'none' || state === 'sign' || state === 'whole') {
state = 'whole';
value += c;
continue;
}
if (state === 'decimal_point' || state === 'decimal') {
state = 'decimal';
value += c;
continue;
}
if (state === 'e' || state === 'exponent_sign' || state === 'exponent') {
state = 'exponent';
value += c;
continue;
}
}
if (c === '.') {
if (state === 'none' || state === 'sign' || state === 'whole') {
state = 'decimal_point';
value += c;
continue;
}
}
if (c === 'E' || c == 'e') {
if (
state === 'whole' ||
state === 'decimal_point' ||
state === 'decimal'
) {
state = 'e';
value += c;
continue;
}
}
break;
}
const number = Number.parseFloat(value);
if (Number.isNaN(number)) {
return [cursor, null];
} else {
// step back to delegate iteration to parent loop
return [i - 1, number];
}
};
/**
* @type {(string: string) => Array<PathDataItem>}
*/
const parsePathData = (string) => {
/**
* @type {Array<PathDataItem>}
*/
const pathData = [];
/**
* @type {null | PathDataCommand}
*/
let command = null;
let args = /** @type {number[]} */ ([]);
let argsCount = 0;
let canHaveComma = false;
let hadComma = false;
for (let i = 0; i < string.length; i += 1) {
const c = string.charAt(i);
if (isWsp(c)) {
continue;
}
// allow comma only between arguments
if (canHaveComma && c === ',') {
if (hadComma) {
break;
}
hadComma = true;
continue;
}
if (isCommand(c)) {
if (hadComma) {
return pathData;
}
if (command == null) {
// moveto should be leading command
if (c !== 'M' && c !== 'm') {
return pathData;
}
} else {
// stop if previous command arguments are not flushed
if (args.length !== 0) {
return pathData;
}
}
command = c;
args = [];
argsCount = argsCountPerCommand[command];
canHaveComma = false;
// flush command without arguments
if (argsCount === 0) {
pathData.push({ command, args });
}
continue;
}
// avoid parsing arguments if no command detected
if (command == null) {
return pathData;
}
// read next argument
let newCursor = i;
let number = null;
if (command === 'A' || command === 'a') {
const position = args.length;
if (position === 0 || position === 1) {
// allow only positive number without sign as first two arguments
if (c !== '+' && c !== '-') {
[newCursor, number] = readNumber(string, i);
}
}
if (position === 2 || position === 5 || position === 6) {
[newCursor, number] = readNumber(string, i);
}
if (position === 3 || position === 4) {
// read flags
if (c === '0') {
number = 0;
}
if (c === '1') {
number = 1;
}
}
} else {
[newCursor, number] = readNumber(string, i);
}
if (number == null) {
return pathData;
}
args.push(number);
canHaveComma = true;
hadComma = false;
i = newCursor;
// flush arguments when necessary count is reached
if (args.length === argsCount) {
pathData.push({ command, args });
// subsequent moveto coordinates are threated as implicit lineto commands
if (command === 'M') {
command = 'L';
}
if (command === 'm') {
command = 'l';
}
args = [];
}
}
return pathData;
};
exports.parsePathData = parsePathData;
/**
* @type {(number: number, precision?: number) => string}
*/
const stringifyNumber = (number, precision) => {
if (precision != null) {
const ratio = 10 ** precision;
number = Math.round(number * ratio) / ratio;
}
// remove zero whole from decimal number
return number.toString().replace(/^0\./, '.').replace(/^-0\./, '-.');
};
/**
* Elliptical arc large-arc and sweep flags are rendered with spaces
* because many non-browser environments are not able to parse such paths
*
* @type {(
* command: string,
* args: number[],
* precision?: number,
* disableSpaceAfterFlags?: boolean
* ) => string}
*/
const stringifyArgs = (command, args, precision, disableSpaceAfterFlags) => {
let result = '';
let prev = '';
for (let i = 0; i < args.length; i += 1) {
const number = args[i];
const numberString = stringifyNumber(number, precision);
if (
disableSpaceAfterFlags &&
(command === 'A' || command === 'a') &&
// consider combined arcs
(i % 7 === 4 || i % 7 === 5)
) {
result += numberString;
} else if (i === 0 || numberString.startsWith('-')) {
// avoid space before first and negative numbers
result += numberString;
} else if (prev.includes('.') && numberString.startsWith('.')) {
// remove space before decimal with zero whole
// only when previous number is also decimal
result += numberString;
} else {
result += ` ${numberString}`;
}
prev = numberString;
}
return result;
};
/**
* @typedef {{
* pathData: Array<PathDataItem>;
* precision?: number;
* disableSpaceAfterFlags?: boolean;
* }} StringifyPathDataOptions
*/
/**
* @type {(options: StringifyPathDataOptions) => string}
*/
const stringifyPathData = ({ pathData, precision, disableSpaceAfterFlags }) => {
// combine sequence of the same commands
let combined = [];
for (let i = 0; i < pathData.length; i += 1) {
const { command, args } = pathData[i];
if (i === 0) {
combined.push({ command, args });
} else {
/**
* @type {PathDataItem}
*/
const last = combined[combined.length - 1];
// match leading moveto with following lineto
if (i === 1) {
if (command === 'L') {
last.command = 'M';
}
if (command === 'l') {
last.command = 'm';
}
}
if (
(last.command === command &&
last.command !== 'M' &&
last.command !== 'm') ||
// combine matching moveto and lineto sequences
(last.command === 'M' && command === 'L') ||
(last.command === 'm' && command === 'l')
) {
last.args = [...last.args, ...args];
} else {
combined.push({ command, args });
}
}
}
let result = '';
for (const { command, args } of combined) {
result +=
command + stringifyArgs(command, args, precision, disableSpaceAfterFlags);
}
return result;
};
exports.stringifyPathData = stringifyPathData;

326
node_modules/svgo/lib/stringifier.js generated vendored Normal file
View File

@@ -0,0 +1,326 @@
'use strict';
/**
* @typedef {import('./types').XastParent} XastParent
* @typedef {import('./types').XastRoot} XastRoot
* @typedef {import('./types').XastElement} XastElement
* @typedef {import('./types').XastInstruction} XastInstruction
* @typedef {import('./types').XastDoctype} XastDoctype
* @typedef {import('./types').XastText} XastText
* @typedef {import('./types').XastCdata} XastCdata
* @typedef {import('./types').XastComment} XastComment
* @typedef {import('./types').StringifyOptions} StringifyOptions
*/
const { textElems } = require('../plugins/_collections.js');
/**
* @typedef {{
* width: void | string,
* height: void | string,
* indent: string,
* textContext: null | XastElement,
* indentLevel: number,
* }} State
*/
/**
* @typedef {Required<StringifyOptions>} Options
*/
/**
* @type {(char: string) => string}
*/
const encodeEntity = (char) => {
return entities[char];
};
/**
* @type {Options}
*/
const defaults = {
doctypeStart: '<!DOCTYPE',
doctypeEnd: '>',
procInstStart: '<?',
procInstEnd: '?>',
tagOpenStart: '<',
tagOpenEnd: '>',
tagCloseStart: '</',
tagCloseEnd: '>',
tagShortStart: '<',
tagShortEnd: '/>',
attrStart: '="',
attrEnd: '"',
commentStart: '<!--',
commentEnd: '-->',
cdataStart: '<![CDATA[',
cdataEnd: ']]>',
textStart: '',
textEnd: '',
indent: 4,
regEntities: /[&'"<>]/g,
regValEntities: /[&"<>]/g,
encodeEntity: encodeEntity,
pretty: false,
useShortTags: true,
eol: 'lf',
finalNewline: false,
};
/**
* @type {Record<string, string>}
*/
const entities = {
'&': '&amp;',
"'": '&apos;',
'"': '&quot;',
'>': '&gt;',
'<': '&lt;',
};
/**
* convert XAST to SVG string
*
* @type {(data: XastRoot, config: StringifyOptions) => {
* data: string,
* info: {
* width: void | string,
* height: void | string
* }
* }}
*/
const stringifySvg = (data, userOptions = {}) => {
/**
* @type {Options}
*/
const config = { ...defaults, ...userOptions };
const indent = config.indent;
let newIndent = ' ';
if (typeof indent === 'number' && Number.isNaN(indent) === false) {
newIndent = indent < 0 ? '\t' : ' '.repeat(indent);
} else if (typeof indent === 'string') {
newIndent = indent;
}
/**
* @type {State}
*/
const state = {
// TODO remove width and height in v3
width: undefined,
height: undefined,
indent: newIndent,
textContext: null,
indentLevel: 0,
};
const eol = config.eol === 'crlf' ? '\r\n' : '\n';
if (config.pretty) {
config.doctypeEnd += eol;
config.procInstEnd += eol;
config.commentEnd += eol;
config.cdataEnd += eol;
config.tagShortEnd += eol;
config.tagOpenEnd += eol;
config.tagCloseEnd += eol;
config.textEnd += eol;
}
let svg = stringifyNode(data, config, state);
if (config.finalNewline && svg.length > 0 && svg[svg.length - 1] !== '\n') {
svg += eol;
}
return {
data: svg,
info: {
width: state.width,
height: state.height,
},
};
};
exports.stringifySvg = stringifySvg;
/**
* @type {(node: XastParent, config: Options, state: State) => string}
*/
const stringifyNode = (data, config, state) => {
let svg = '';
state.indentLevel += 1;
for (const item of data.children) {
if (item.type === 'element') {
svg += stringifyElement(item, config, state);
}
if (item.type === 'text') {
svg += stringifyText(item, config, state);
}
if (item.type === 'doctype') {
svg += stringifyDoctype(item, config);
}
if (item.type === 'instruction') {
svg += stringifyInstruction(item, config);
}
if (item.type === 'comment') {
svg += stringifyComment(item, config);
}
if (item.type === 'cdata') {
svg += stringifyCdata(item, config, state);
}
}
state.indentLevel -= 1;
return svg;
};
/**
* create indent string in accordance with the current node level.
*
* @type {(config: Options, state: State) => string}
*/
const createIndent = (config, state) => {
let indent = '';
if (config.pretty && state.textContext == null) {
indent = state.indent.repeat(state.indentLevel - 1);
}
return indent;
};
/**
* @type {(node: XastDoctype, config: Options) => string}
*/
const stringifyDoctype = (node, config) => {
return config.doctypeStart + node.data.doctype + config.doctypeEnd;
};
/**
* @type {(node: XastInstruction, config: Options) => string}
*/
const stringifyInstruction = (node, config) => {
return (
config.procInstStart + node.name + ' ' + node.value + config.procInstEnd
);
};
/**
* @type {(node: XastComment, config: Options) => string}
*/
const stringifyComment = (node, config) => {
return config.commentStart + node.value + config.commentEnd;
};
/**
* @type {(node: XastCdata, config: Options, state: State) => string}
*/
const stringifyCdata = (node, config, state) => {
return (
createIndent(config, state) +
config.cdataStart +
node.value +
config.cdataEnd
);
};
/**
* @type {(node: XastElement, config: Options, state: State) => string}
*/
const stringifyElement = (node, config, state) => {
// beautiful injection for obtaining SVG information :)
if (
node.name === 'svg' &&
node.attributes.width != null &&
node.attributes.height != null
) {
state.width = node.attributes.width;
state.height = node.attributes.height;
}
// empty element and short tag
if (node.children.length === 0) {
if (config.useShortTags) {
return (
createIndent(config, state) +
config.tagShortStart +
node.name +
stringifyAttributes(node, config) +
config.tagShortEnd
);
} else {
return (
createIndent(config, state) +
config.tagShortStart +
node.name +
stringifyAttributes(node, config) +
config.tagOpenEnd +
config.tagCloseStart +
node.name +
config.tagCloseEnd
);
}
// non-empty element
} else {
let tagOpenStart = config.tagOpenStart;
let tagOpenEnd = config.tagOpenEnd;
let tagCloseStart = config.tagCloseStart;
let tagCloseEnd = config.tagCloseEnd;
let openIndent = createIndent(config, state);
let closeIndent = createIndent(config, state);
if (state.textContext) {
tagOpenStart = defaults.tagOpenStart;
tagOpenEnd = defaults.tagOpenEnd;
tagCloseStart = defaults.tagCloseStart;
tagCloseEnd = defaults.tagCloseEnd;
openIndent = '';
} else if (textElems.includes(node.name)) {
tagOpenEnd = defaults.tagOpenEnd;
tagCloseStart = defaults.tagCloseStart;
closeIndent = '';
state.textContext = node;
}
const children = stringifyNode(node, config, state);
if (state.textContext === node) {
state.textContext = null;
}
return (
openIndent +
tagOpenStart +
node.name +
stringifyAttributes(node, config) +
tagOpenEnd +
children +
closeIndent +
tagCloseStart +
node.name +
tagCloseEnd
);
}
};
/**
* @type {(node: XastElement, config: Options) => string}
*/
const stringifyAttributes = (node, config) => {
let attrs = '';
for (const [name, value] of Object.entries(node.attributes)) {
// TODO remove attributes without values support in v3
if (value !== undefined) {
const encodedValue = value
.toString()
.replace(config.regValEntities, config.encodeEntity);
attrs += ' ' + name + config.attrStart + encodedValue + config.attrEnd;
} else {
attrs += ' ' + name;
}
}
return attrs;
};
/**
* @type {(node: XastText, config: Options, state: State) => string}
*/
const stringifyText = (node, config, state) => {
return (
createIndent(config, state) +
config.textStart +
node.value.replace(config.regEntities, config.encodeEntity) +
(state.textContext ? '' : config.textEnd)
);
};

283
node_modules/svgo/lib/style.js generated vendored Normal file
View File

@@ -0,0 +1,283 @@
'use strict';
/**
* @typedef {import('css-tree').Rule} CsstreeRule
* @typedef {import('./types').Specificity} Specificity
* @typedef {import('./types').Stylesheet} Stylesheet
* @typedef {import('./types').StylesheetRule} StylesheetRule
* @typedef {import('./types').StylesheetDeclaration} StylesheetDeclaration
* @typedef {import('./types').ComputedStyles} ComputedStyles
* @typedef {import('./types').XastRoot} XastRoot
* @typedef {import('./types').XastElement} XastElement
* @typedef {import('./types').XastParent} XastParent
* @typedef {import('./types').XastChild} XastChild
*/
const stable = require('stable');
const csstree = require('css-tree');
// @ts-ignore not defined in @types/csso
const specificity = require('csso/lib/restructure/prepare/specificity');
const { visit, matches } = require('./xast.js');
const {
attrsGroups,
inheritableAttrs,
presentationNonInheritableGroupAttrs,
} = require('../plugins/_collections.js');
// @ts-ignore not defined in @types/csstree
const csstreeWalkSkip = csstree.walk.skip;
/**
* @type {(ruleNode: CsstreeRule, dynamic: boolean) => StylesheetRule}
*/
const parseRule = (ruleNode, dynamic) => {
let selectors;
let selectorsSpecificity;
/**
* @type {Array<StylesheetDeclaration>}
*/
const declarations = [];
csstree.walk(ruleNode, (cssNode) => {
if (cssNode.type === 'SelectorList') {
// compute specificity from original node to consider pseudo classes
selectorsSpecificity = specificity(cssNode);
const newSelectorsNode = csstree.clone(cssNode);
csstree.walk(newSelectorsNode, (pseudoClassNode, item, list) => {
if (pseudoClassNode.type === 'PseudoClassSelector') {
dynamic = true;
list.remove(item);
}
});
selectors = csstree.generate(newSelectorsNode);
return csstreeWalkSkip;
}
if (cssNode.type === 'Declaration') {
declarations.push({
name: cssNode.property,
value: csstree.generate(cssNode.value),
important: cssNode.important === true,
});
return csstreeWalkSkip;
}
});
if (selectors == null || selectorsSpecificity == null) {
throw Error('assert');
}
return {
dynamic,
selectors,
specificity: selectorsSpecificity,
declarations,
};
};
/**
* @type {(css: string, dynamic: boolean) => Array<StylesheetRule>}
*/
const parseStylesheet = (css, dynamic) => {
/**
* @type {Array<StylesheetRule>}
*/
const rules = [];
const ast = csstree.parse(css, {
parseValue: false,
parseAtrulePrelude: false,
});
csstree.walk(ast, (cssNode) => {
if (cssNode.type === 'Rule') {
rules.push(parseRule(cssNode, dynamic || false));
return csstreeWalkSkip;
}
if (cssNode.type === 'Atrule') {
if (cssNode.name === 'keyframes') {
return csstreeWalkSkip;
}
csstree.walk(cssNode, (ruleNode) => {
if (ruleNode.type === 'Rule') {
rules.push(parseRule(ruleNode, dynamic || true));
return csstreeWalkSkip;
}
});
return csstreeWalkSkip;
}
});
return rules;
};
/**
* @type {(css: string) => Array<StylesheetDeclaration>}
*/
const parseStyleDeclarations = (css) => {
/**
* @type {Array<StylesheetDeclaration>}
*/
const declarations = [];
const ast = csstree.parse(css, {
context: 'declarationList',
parseValue: false,
});
csstree.walk(ast, (cssNode) => {
if (cssNode.type === 'Declaration') {
declarations.push({
name: cssNode.property,
value: csstree.generate(cssNode.value),
important: cssNode.important === true,
});
}
});
return declarations;
};
/**
* @type {(stylesheet: Stylesheet, node: XastElement) => ComputedStyles}
*/
const computeOwnStyle = (stylesheet, node) => {
/**
* @type {ComputedStyles}
*/
const computedStyle = {};
const importantStyles = new Map();
// collect attributes
for (const [name, value] of Object.entries(node.attributes)) {
if (attrsGroups.presentation.includes(name)) {
computedStyle[name] = { type: 'static', inherited: false, value };
importantStyles.set(name, false);
}
}
// collect matching rules
for (const { selectors, declarations, dynamic } of stylesheet.rules) {
if (matches(node, selectors)) {
for (const { name, value, important } of declarations) {
const computed = computedStyle[name];
if (computed && computed.type === 'dynamic') {
continue;
}
if (dynamic) {
computedStyle[name] = { type: 'dynamic', inherited: false };
continue;
}
if (
computed == null ||
important === true ||
importantStyles.get(name) === false
) {
computedStyle[name] = { type: 'static', inherited: false, value };
importantStyles.set(name, important);
}
}
}
}
// collect inline styles
const styleDeclarations =
node.attributes.style == null
? []
: parseStyleDeclarations(node.attributes.style);
for (const { name, value, important } of styleDeclarations) {
const computed = computedStyle[name];
if (computed && computed.type === 'dynamic') {
continue;
}
if (
computed == null ||
important === true ||
importantStyles.get(name) === false
) {
computedStyle[name] = { type: 'static', inherited: false, value };
importantStyles.set(name, important);
}
}
return computedStyle;
};
/**
* 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;
};
/**
* @type {(root: XastRoot) => Stylesheet}
*/
const collectStylesheet = (root) => {
/**
* @type {Array<StylesheetRule>}
*/
const rules = [];
/**
* @type {Map<XastElement, XastParent>}
*/
const parents = new Map();
visit(root, {
element: {
enter: (node, parentNode) => {
// store parents
parents.set(node, parentNode);
// find and parse all styles
if (node.name === 'style') {
const dynamic =
node.attributes.media != null && node.attributes.media !== 'all';
if (
node.attributes.type == null ||
node.attributes.type === '' ||
node.attributes.type === 'text/css'
) {
const children = node.children;
for (const child of children) {
if (child.type === 'text' || child.type === 'cdata') {
rules.push(...parseStylesheet(child.value, dynamic));
}
}
}
}
},
},
});
// sort by selectors specificity
stable.inplace(rules, (a, b) =>
compareSpecificity(a.specificity, b.specificity)
);
return { rules, parents };
};
exports.collectStylesheet = collectStylesheet;
/**
* @type {(stylesheet: Stylesheet, node: XastElement) => ComputedStyles}
*/
const computeStyle = (stylesheet, node) => {
const { parents } = stylesheet;
// collect inherited styles
const computedStyles = computeOwnStyle(stylesheet, node);
let parent = parents.get(node);
while (parent != null && parent.type !== 'root') {
const inheritedStyles = computeOwnStyle(stylesheet, parent);
for (const [name, computed] of Object.entries(inheritedStyles)) {
if (
computedStyles[name] == null &&
// ignore not inheritable styles
inheritableAttrs.includes(name) === true &&
presentationNonInheritableGroupAttrs.includes(name) === false
) {
computedStyles[name] = { ...computed, inherited: true };
}
}
parent = parents.get(parent);
}
return computedStyles;
};
exports.computeStyle = computeStyle;

106
node_modules/svgo/lib/svgo-node.js generated vendored Normal file
View File

@@ -0,0 +1,106 @@
'use strict';
const os = require('os');
const fs = require('fs');
const { pathToFileURL } = require('url');
const path = require('path');
const {
extendDefaultPlugins,
optimize: optimizeAgnostic,
createContentItem,
} = require('./svgo.js');
exports.extendDefaultPlugins = extendDefaultPlugins;
exports.createContentItem = createContentItem;
const importConfig = async (configFile) => {
let config;
// at the moment dynamic import may randomly fail with segfault
// to workaround this for some users .cjs extension is loaded
// exclusively with require
if (configFile.endsWith('.cjs')) {
config = require(configFile);
} else {
try {
// dynamic import expects file url instead of path and may fail
// when windows path is provided
const { default: imported } = await import(pathToFileURL(configFile));
config = imported;
} catch (importError) {
// TODO remove require in v3
try {
config = require(configFile);
} catch (requireError) {
// throw original error if es module is detected
if (requireError.code === 'ERR_REQUIRE_ESM') {
throw importError;
} else {
throw requireError;
}
}
}
}
if (config == null || typeof config !== 'object' || Array.isArray(config)) {
throw Error(`Invalid config file "${configFile}"`);
}
return config;
};
const isFile = async (file) => {
try {
const stats = await fs.promises.stat(file);
return stats.isFile();
} catch {
return false;
}
};
const loadConfig = async (configFile, cwd = process.cwd()) => {
if (configFile != null) {
if (path.isAbsolute(configFile)) {
return await importConfig(configFile);
} else {
return await importConfig(path.join(cwd, configFile));
}
}
let dir = cwd;
// eslint-disable-next-line no-constant-condition
while (true) {
const js = path.join(dir, 'svgo.config.js');
if (await isFile(js)) {
return await importConfig(js);
}
const mjs = path.join(dir, 'svgo.config.mjs');
if (await isFile(mjs)) {
return await importConfig(mjs);
}
const cjs = path.join(dir, 'svgo.config.cjs');
if (await isFile(cjs)) {
return await importConfig(cjs);
}
const parent = path.dirname(dir);
if (dir === parent) {
return null;
}
dir = parent;
}
};
exports.loadConfig = loadConfig;
const optimize = (input, config) => {
if (config == null) {
config = {};
}
if (typeof config !== 'object') {
throw Error('Config should be an object');
}
return optimizeAgnostic(input, {
...config,
js2svg: {
// platform specific default for end of line
eol: os.EOL === '\r\n' ? 'crlf' : 'lf',
...config.js2svg,
},
});
};
exports.optimize = optimize;

83
node_modules/svgo/lib/svgo.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
'use strict';
const {
defaultPlugins,
resolvePluginConfig,
extendDefaultPlugins,
} = require('./svgo/config.js');
const { parseSvg } = require('./parser.js');
const { stringifySvg } = require('./stringifier.js');
const { invokePlugins } = require('./svgo/plugins.js');
const JSAPI = require('./svgo/jsAPI.js');
const { encodeSVGDatauri } = require('./svgo/tools.js');
exports.extendDefaultPlugins = extendDefaultPlugins;
const optimize = (input, config) => {
if (config == null) {
config = {};
}
if (typeof config !== 'object') {
throw Error('Config should be an object');
}
const maxPassCount = config.multipass ? 10 : 1;
let prevResultSize = Number.POSITIVE_INFINITY;
let svgjs = null;
const info = {};
if (config.path != null) {
info.path = config.path;
}
for (let i = 0; i < maxPassCount; i += 1) {
info.multipassCount = i;
// TODO throw this error in v3
try {
svgjs = parseSvg(input, config.path);
} catch (error) {
return { error: error.toString(), modernError: error };
}
if (svgjs.error != null) {
if (config.path != null) {
svgjs.path = config.path;
}
return svgjs;
}
const plugins = config.plugins || defaultPlugins;
if (Array.isArray(plugins) === false) {
throw Error(
"Invalid plugins list. Provided 'plugins' in config should be an array."
);
}
const resolvedPlugins = plugins.map(resolvePluginConfig);
const globalOverrides = {};
if (config.floatPrecision != null) {
globalOverrides.floatPrecision = config.floatPrecision;
}
svgjs = invokePlugins(svgjs, info, resolvedPlugins, null, globalOverrides);
svgjs = stringifySvg(svgjs, config.js2svg);
if (svgjs.data.length < prevResultSize) {
input = svgjs.data;
prevResultSize = svgjs.data.length;
} else {
if (config.datauri) {
svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
}
if (config.path != null) {
svgjs.path = config.path;
}
return svgjs;
}
}
return svgjs;
};
exports.optimize = optimize;
/**
* The factory that creates a content item with the helper methods.
*
* @param {Object} data which is passed to jsAPI constructor
* @returns {JSAPI} content item
*/
const createContentItem = (data) => {
return new JSAPI(data);
};
exports.createContentItem = createContentItem;

517
node_modules/svgo/lib/svgo/coa.js generated vendored Normal file
View File

@@ -0,0 +1,517 @@
'use strict';
const fs = require('fs');
const path = require('path');
const colors = require('picocolors');
const { loadConfig, optimize } = require('../svgo-node.js');
const pluginsMap = require('../../plugins/plugins.js');
const PKG = require('../../package.json');
const { encodeSVGDatauri, decodeSVGDatauri } = require('./tools.js');
const regSVGFile = /\.svg$/i;
/**
* Synchronously check if path is a directory. Tolerant to errors like ENOENT.
* @param {string} path
*/
function checkIsDir(path) {
try {
return fs.lstatSync(path).isDirectory();
} catch (e) {
return false;
}
}
module.exports = function makeProgram(program) {
program
.name(PKG.name)
.description(PKG.description, {
INPUT: 'Alias to --input',
})
.version(PKG.version, '-v, --version')
.arguments('[INPUT...]')
.option('-i, --input <INPUT...>', 'Input files, "-" for STDIN')
.option('-s, --string <STRING>', 'Input SVG data string')
.option(
'-f, --folder <FOLDER>',
'Input folder, optimize and rewrite all *.svg files'
)
.option(
'-o, --output <OUTPUT...>',
'Output file or folder (by default the same as the input), "-" for STDOUT'
)
.option(
'-p, --precision <INTEGER>',
'Set number of digits in the fractional part, overrides plugins params'
)
.option('--config <CONFIG>', 'Custom config file, only .js is supported')
.option(
'--datauri <FORMAT>',
'Output as Data URI string (base64), URI encoded (enc) or unencoded (unenc)'
)
.option(
'--multipass',
'Pass over SVGs multiple times to ensure all optimizations are applied'
)
.option('--pretty', 'Make SVG pretty printed')
.option('--indent <INTEGER>', 'Indent number when pretty printing SVGs')
.option(
'--eol <EOL>',
'Line break to use when outputting SVG: lf, crlf. If unspecified, uses platform default.'
)
.option('--final-newline', 'Ensure SVG ends with a line break')
.option(
'-r, --recursive',
"Use with '--folder'. Optimizes *.svg files in folders recursively."
)
.option(
'--exclude <PATTERN...>',
"Use with '--folder'. Exclude files matching regular expression pattern."
)
.option(
'-q, --quiet',
'Only output error messages, not regular status messages'
)
.option('--show-plugins', 'Show available plugins and exit')
// used by picocolors internally
.option('--no-color', 'Output plain text without color')
.action(action);
};
async function action(args, opts, command) {
var input = opts.input || args;
var output = opts.output;
var config = {};
if (opts.precision != null) {
const number = Number.parseInt(opts.precision, 10);
if (Number.isNaN(number)) {
console.error(
"error: option '-p, --precision' argument must be an integer number"
);
process.exit(1);
} else {
opts.precision = number;
}
}
if (opts.datauri != null) {
if (
opts.datauri !== 'base64' &&
opts.datauri !== 'enc' &&
opts.datauri !== 'unenc'
) {
console.error(
"error: option '--datauri' must have one of the following values: 'base64', 'enc' or 'unenc'"
);
process.exit(1);
}
}
if (opts.indent != null) {
const number = Number.parseInt(opts.indent, 10);
if (Number.isNaN(number)) {
console.error(
"error: option '--indent' argument must be an integer number"
);
process.exit(1);
} else {
opts.indent = number;
}
}
if (opts.eol != null && opts.eol !== 'lf' && opts.eol !== 'crlf') {
console.error(
"error: option '--eol' must have one of the following values: 'lf' or 'crlf'"
);
process.exit(1);
}
// --show-plugins
if (opts.showPlugins) {
showAvailablePlugins();
return;
}
// w/o anything
if (
(input.length === 0 || input[0] === '-') &&
!opts.string &&
!opts.stdin &&
!opts.folder &&
process.stdin.isTTY === true
) {
return command.help();
}
if (
typeof process == 'object' &&
process.versions &&
process.versions.node &&
PKG &&
PKG.engines.node
) {
var nodeVersion = String(PKG.engines.node).match(/\d*(\.\d+)*/)[0];
if (parseFloat(process.versions.node) < parseFloat(nodeVersion)) {
throw Error(
`${PKG.name} requires Node.js version ${nodeVersion} or higher.`
);
}
}
// --config
const loadedConfig = await loadConfig(opts.config);
if (loadedConfig != null) {
config = loadedConfig;
}
// --quiet
if (opts.quiet) {
config.quiet = opts.quiet;
}
// --recursive
if (opts.recursive) {
config.recursive = opts.recursive;
}
// --exclude
config.exclude = opts.exclude
? opts.exclude.map((pattern) => RegExp(pattern))
: [];
// --precision
if (opts.precision != null) {
var precision = Math.min(Math.max(0, opts.precision), 20);
config.floatPrecision = precision;
}
// --multipass
if (opts.multipass) {
config.multipass = true;
}
// --pretty
if (opts.pretty) {
config.js2svg = config.js2svg || {};
config.js2svg.pretty = true;
if (opts.indent != null) {
config.js2svg.indent = opts.indent;
}
}
// --eol
if (opts.eol) {
config.js2svg = config.js2svg || {};
config.js2svg.eol = opts.eol;
}
// --final-newline
if (opts.finalNewline) {
config.js2svg = config.js2svg || {};
config.js2svg.finalNewline = true;
}
// --output
if (output) {
if (input.length && input[0] != '-') {
if (output.length == 1 && checkIsDir(output[0])) {
var dir = output[0];
for (var i = 0; i < input.length; i++) {
output[i] = checkIsDir(input[i])
? input[i]
: path.resolve(dir, path.basename(input[i]));
}
} else if (output.length < input.length) {
output = output.concat(input.slice(output.length));
}
}
} else if (input.length) {
output = input;
} else if (opts.string) {
output = '-';
}
if (opts.datauri) {
config.datauri = opts.datauri;
}
// --folder
if (opts.folder) {
var ouputFolder = (output && output[0]) || opts.folder;
await optimizeFolder(config, opts.folder, ouputFolder);
}
// --input
if (input.length !== 0) {
// STDIN
if (input[0] === '-') {
return new Promise((resolve, reject) => {
var data = '',
file = output[0];
process.stdin
.on('data', (chunk) => (data += chunk))
.once('end', () =>
processSVGData(config, { input: 'string' }, data, file).then(
resolve,
reject
)
);
});
// file
} else {
await Promise.all(
input.map((file, n) => optimizeFile(config, file, output[n]))
);
}
// --string
} else if (opts.string) {
var data = decodeSVGDatauri(opts.string);
return processSVGData(config, { input: 'string' }, data, output[0]);
}
}
/**
* Optimize SVG files in a directory.
* @param {Object} config options
* @param {string} dir input directory
* @param {string} output output directory
* @return {Promise}
*/
function optimizeFolder(config, dir, output) {
if (!config.quiet) {
console.log(`Processing directory '${dir}':\n`);
}
return fs.promises
.readdir(dir)
.then((files) => processDirectory(config, dir, files, output));
}
/**
* Process given files, take only SVG.
* @param {Object} config options
* @param {string} dir input directory
* @param {Array} files list of file names in the directory
* @param {string} output output directory
* @return {Promise}
*/
function processDirectory(config, dir, files, output) {
// take only *.svg files, recursively if necessary
var svgFilesDescriptions = getFilesDescriptions(config, dir, files, output);
return svgFilesDescriptions.length
? Promise.all(
svgFilesDescriptions.map((fileDescription) =>
optimizeFile(
config,
fileDescription.inputPath,
fileDescription.outputPath
)
)
)
: Promise.reject(
new Error(`No SVG files have been found in '${dir}' directory.`)
);
}
/**
* Get svg files descriptions
* @param {Object} config options
* @param {string} dir input directory
* @param {Array} files list of file names in the directory
* @param {string} output output directory
* @return {Array}
*/
function getFilesDescriptions(config, dir, files, output) {
const filesInThisFolder = files
.filter(
(name) =>
regSVGFile.test(name) &&
!config.exclude.some((regExclude) => regExclude.test(name))
)
.map((name) => ({
inputPath: path.resolve(dir, name),
outputPath: path.resolve(output, name),
}));
return config.recursive
? [].concat(
filesInThisFolder,
files
.filter((name) => checkIsDir(path.resolve(dir, name)))
.map((subFolderName) => {
const subFolderPath = path.resolve(dir, subFolderName);
const subFolderFiles = fs.readdirSync(subFolderPath);
const subFolderOutput = path.resolve(output, subFolderName);
return getFilesDescriptions(
config,
subFolderPath,
subFolderFiles,
subFolderOutput
);
})
.reduce((a, b) => [].concat(a, b), [])
)
: filesInThisFolder;
}
/**
* Read SVG file and pass to processing.
* @param {Object} config options
* @param {string} file
* @param {string} output
* @return {Promise}
*/
function optimizeFile(config, file, output) {
return fs.promises.readFile(file, 'utf8').then(
(data) =>
processSVGData(config, { input: 'file', path: file }, data, output, file),
(error) => checkOptimizeFileError(config, file, output, error)
);
}
/**
* Optimize SVG data.
* @param {Object} config options
* @param {string} data SVG content to optimize
* @param {string} output where to write optimized file
* @param {string} [input] input file name (being used if output is a directory)
* @return {Promise}
*/
function processSVGData(config, info, data, output, input) {
var startTime = Date.now(),
prevFileSize = Buffer.byteLength(data, 'utf8');
const result = optimize(data, { ...config, ...info });
if (result.modernError) {
console.error(colors.red(result.modernError.toString()));
process.exit(1);
}
if (config.datauri) {
result.data = encodeSVGDatauri(result.data, config.datauri);
}
var resultFileSize = Buffer.byteLength(result.data, 'utf8'),
processingTime = Date.now() - startTime;
return writeOutput(input, output, result.data).then(
function () {
if (!config.quiet && output != '-') {
if (input) {
console.log(`\n${path.basename(input)}:`);
}
printTimeInfo(processingTime);
printProfitInfo(prevFileSize, resultFileSize);
}
},
(error) =>
Promise.reject(
new Error(
error.code === 'ENOTDIR'
? `Error: output '${output}' is not a directory.`
: error
)
)
);
}
/**
* Write result of an optimization.
* @param {string} input
* @param {string} output output file name. '-' for stdout
* @param {string} data data to write
* @return {Promise}
*/
function writeOutput(input, output, data) {
if (output == '-') {
console.log(data);
return Promise.resolve();
}
fs.mkdirSync(path.dirname(output), { recursive: true });
return fs.promises
.writeFile(output, data, 'utf8')
.catch((error) => checkWriteFileError(input, output, data, error));
}
/**
* Write a time taken by optimization.
* @param {number} time time in milliseconds.
*/
function printTimeInfo(time) {
console.log(`Done in ${time} ms!`);
}
/**
* Write optimizing information in human readable format.
* @param {number} inBytes size before optimization.
* @param {number} outBytes size after optimization.
*/
function printProfitInfo(inBytes, outBytes) {
var profitPercents = 100 - (outBytes * 100) / inBytes;
console.log(
Math.round((inBytes / 1024) * 1000) / 1000 +
' KiB' +
(profitPercents < 0 ? ' + ' : ' - ') +
colors.green(Math.abs(Math.round(profitPercents * 10) / 10) + '%') +
' = ' +
Math.round((outBytes / 1024) * 1000) / 1000 +
' KiB'
);
}
/**
* Check for errors, if it's a dir optimize the dir.
* @param {Object} config
* @param {string} input
* @param {string} output
* @param {Error} error
* @return {Promise}
*/
function checkOptimizeFileError(config, input, output, error) {
if (error.code == 'EISDIR') {
return optimizeFolder(config, input, output);
} else if (error.code == 'ENOENT') {
return Promise.reject(
new Error(`Error: no such file or directory '${error.path}'.`)
);
}
return Promise.reject(error);
}
/**
* Check for saving file error. If the output is a dir, then write file there.
* @param {string} input
* @param {string} output
* @param {string} data
* @param {Error} error
* @return {Promise}
*/
function checkWriteFileError(input, output, data, error) {
if (error.code == 'EISDIR' && input) {
return fs.promises.writeFile(
path.resolve(output, path.basename(input)),
data,
'utf8'
);
} else {
return Promise.reject(error);
}
}
/**
* Show list of available plugins with short description.
*/
function showAvailablePlugins() {
const list = Object.entries(pluginsMap)
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, plugin]) => ` [ ${colors.green(name)} ] ${plugin.description}`)
.join('\n');
console.log('Currently available plugins:\n' + list);
}
module.exports.checkIsDir = checkIsDir;

138
node_modules/svgo/lib/svgo/config.js generated vendored Normal file
View File

@@ -0,0 +1,138 @@
'use strict';
const pluginsMap = require('../../plugins/plugins.js');
const pluginsOrder = [
'removeDoctype',
'removeXMLProcInst',
'removeComments',
'removeMetadata',
'removeXMLNS',
'removeEditorsNSData',
'cleanupAttrs',
'mergeStyles',
'inlineStyles',
'minifyStyles',
'convertStyleToAttrs',
'cleanupIDs',
'prefixIds',
'removeRasterImages',
'removeUselessDefs',
'cleanupNumericValues',
'cleanupListOfValues',
'convertColors',
'removeUnknownsAndDefaults',
'removeNonInheritableGroupAttrs',
'removeUselessStrokeAndFill',
'removeViewBox',
'cleanupEnableBackground',
'removeHiddenElems',
'removeEmptyText',
'convertShapeToPath',
'convertEllipseToCircle',
'moveElemsAttrsToGroup',
'moveGroupAttrsToElems',
'collapseGroups',
'convertPathData',
'convertTransform',
'removeEmptyAttrs',
'removeEmptyContainers',
'mergePaths',
'removeUnusedNS',
'sortAttrs',
'sortDefsChildren',
'removeTitle',
'removeDesc',
'removeDimensions',
'removeAttrs',
'removeAttributesBySelector',
'removeElementsByAttr',
'addClassesToSVGElement',
'removeStyleElement',
'removeScriptElement',
'addAttributesToSVGElement',
'removeOffCanvasPaths',
'reusePaths',
];
const defaultPlugins = pluginsOrder.filter((name) => pluginsMap[name].active);
exports.defaultPlugins = defaultPlugins;
const extendDefaultPlugins = (plugins) => {
console.warn(
'\n"extendDefaultPlugins" utility is deprecated.\n' +
'Use "preset-default" plugin with overrides instead.\n' +
'For example:\n' +
`{\n` +
` name: 'preset-default',\n` +
` params: {\n` +
` overrides: {\n` +
` // customize plugin options\n` +
` convertShapeToPath: {\n` +
` convertArcs: true\n` +
` },\n` +
` // disable plugins\n` +
` convertPathData: false\n` +
` }\n` +
` }\n` +
`}\n`
);
const extendedPlugins = pluginsOrder.map((name) => ({
name,
active: pluginsMap[name].active,
}));
for (const plugin of plugins) {
const resolvedPlugin = resolvePluginConfig(plugin);
const index = pluginsOrder.indexOf(resolvedPlugin.name);
if (index === -1) {
extendedPlugins.push(plugin);
} else {
extendedPlugins[index] = plugin;
}
}
return extendedPlugins;
};
exports.extendDefaultPlugins = extendDefaultPlugins;
const resolvePluginConfig = (plugin) => {
let configParams = {};
if (typeof plugin === 'string') {
// resolve builtin plugin specified as string
const pluginConfig = pluginsMap[plugin];
if (pluginConfig == null) {
throw Error(`Unknown builtin plugin "${plugin}" specified.`);
}
return {
...pluginConfig,
name: plugin,
active: true,
params: { ...pluginConfig.params, ...configParams },
};
}
if (typeof plugin === 'object' && plugin != null) {
if (plugin.name == null) {
throw Error(`Plugin name should be specified`);
}
if (plugin.fn) {
// resolve custom plugin with implementation
return {
active: true,
...plugin,
params: { ...configParams, ...plugin.params },
};
} else {
// resolve builtin plugin specified as object without implementation
const pluginConfig = pluginsMap[plugin.name];
if (pluginConfig == null) {
throw Error(`Unknown builtin plugin "${plugin.name}" specified.`);
}
return {
...pluginConfig,
active: true,
...plugin,
params: { ...pluginConfig.params, ...configParams, ...plugin.params },
};
}
}
return null;
};
exports.resolvePluginConfig = resolvePluginConfig;

72
node_modules/svgo/lib/svgo/css-class-list.js generated vendored Normal file
View File

@@ -0,0 +1,72 @@
'use strict';
var CSSClassList = function (node) {
this.parentNode = node;
this.classNames = new Set();
const value = node.attributes.class;
if (value != null) {
this.addClassValueHandler();
this.setClassValue(value);
}
};
// attr.class.value
CSSClassList.prototype.addClassValueHandler = function () {
Object.defineProperty(this.parentNode.attributes, 'class', {
get: this.getClassValue.bind(this),
set: this.setClassValue.bind(this),
enumerable: true,
configurable: true,
});
};
CSSClassList.prototype.getClassValue = function () {
var arrClassNames = Array.from(this.classNames);
return arrClassNames.join(' ');
};
CSSClassList.prototype.setClassValue = function (newValue) {
if (typeof newValue === 'undefined') {
this.classNames.clear();
return;
}
var arrClassNames = newValue.split(' ');
this.classNames = new Set(arrClassNames);
};
CSSClassList.prototype.add = function (/* variadic */) {
this.addClassValueHandler();
Object.values(arguments).forEach(this._addSingle.bind(this));
};
CSSClassList.prototype._addSingle = function (className) {
this.classNames.add(className);
};
CSSClassList.prototype.remove = function (/* variadic */) {
this.addClassValueHandler();
Object.values(arguments).forEach(this._removeSingle.bind(this));
};
CSSClassList.prototype._removeSingle = function (className) {
this.classNames.delete(className);
};
CSSClassList.prototype.item = function (index) {
var arrClassNames = Array.from(this.classNames);
return arrClassNames[index];
};
CSSClassList.prototype.toggle = function (className, force) {
if (this.contains(className) || force === false) {
this.classNames.delete(className);
}
this.classNames.add(className);
};
CSSClassList.prototype.contains = function (className) {
return this.classNames.has(className);
};
module.exports = CSSClassList;

2
node_modules/svgo/lib/svgo/css-select-adapter.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
declare let obj: any;
export = obj;

120
node_modules/svgo/lib/svgo/css-select-adapter.js generated vendored Normal file
View File

@@ -0,0 +1,120 @@
'use strict';
const isTag = (node) => {
return node.type === 'element';
};
const existsOne = (test, elems) => {
return elems.some((elem) => {
if (isTag(elem)) {
return test(elem) || existsOne(test, getChildren(elem));
} else {
return false;
}
});
};
const getAttributeValue = (elem, name) => {
return elem.attributes[name];
};
const getChildren = (node) => {
return node.children || [];
};
const getName = (elemAst) => {
return elemAst.name;
};
const getParent = (node) => {
return node.parentNode || null;
};
const getSiblings = (elem) => {
var parent = getParent(elem);
return parent ? getChildren(parent) : [];
};
const getText = (node) => {
if (node.children[0].type === 'text' && node.children[0].type === 'cdata') {
return node.children[0].value;
}
return '';
};
const hasAttrib = (elem, name) => {
return elem.attributes[name] !== undefined;
};
const removeSubsets = (nodes) => {
let idx = nodes.length;
let node;
let ancestor;
let replace;
// Check if each node (or one of its ancestors) is already contained in the
// array.
while (--idx > -1) {
node = ancestor = nodes[idx];
// Temporarily remove the node under consideration
nodes[idx] = null;
replace = true;
while (ancestor) {
if (nodes.includes(ancestor)) {
replace = false;
nodes.splice(idx, 1);
break;
}
ancestor = getParent(ancestor);
}
// If the node has been found to be unique, re-insert it.
if (replace) {
nodes[idx] = node;
}
}
return nodes;
};
const findAll = (test, elems) => {
const result = [];
for (const elem of elems) {
if (isTag(elem)) {
if (test(elem)) {
result.push(elem);
}
result.push(...findAll(test, getChildren(elem)));
}
}
return result;
};
const findOne = (test, elems) => {
for (const elem of elems) {
if (isTag(elem)) {
if (test(elem)) {
return elem;
}
const result = findOne(test, getChildren(elem));
if (result) {
return result;
}
}
}
return null;
};
const svgoCssSelectAdapter = {
isTag,
existsOne,
getAttributeValue,
getChildren,
getName,
getParent,
getSiblings,
getText,
hasAttrib,
removeSubsets,
findAll,
findOne,
};
module.exports = svgoCssSelectAdapter;

232
node_modules/svgo/lib/svgo/css-style-declaration.js generated vendored Normal file
View File

@@ -0,0 +1,232 @@
'use strict';
var csstree = require('css-tree'),
csstools = require('../css-tools');
var CSSStyleDeclaration = function (node) {
this.parentNode = node;
this.properties = new Map();
this.hasSynced = false;
this.styleValue = null;
this.parseError = false;
const value = node.attributes.style;
if (value != null) {
this.addStyleValueHandler();
this.setStyleValue(value);
}
};
// attr.style.value
CSSStyleDeclaration.prototype.addStyleValueHandler = function () {
Object.defineProperty(this.parentNode.attributes, 'style', {
get: this.getStyleValue.bind(this),
set: this.setStyleValue.bind(this),
enumerable: true,
configurable: true,
});
};
CSSStyleDeclaration.prototype.getStyleValue = function () {
return this.getCssText();
};
CSSStyleDeclaration.prototype.setStyleValue = function (newValue) {
this.properties.clear(); // reset all existing properties
this.styleValue = newValue;
this.hasSynced = false; // raw css changed
};
CSSStyleDeclaration.prototype._loadCssText = function () {
if (this.hasSynced) {
return;
}
this.hasSynced = true; // must be set here to prevent loop in setProperty(...)
if (!this.styleValue || this.styleValue.length === 0) {
return;
}
var inlineCssStr = this.styleValue;
var declarations = {};
try {
declarations = csstree.parse(inlineCssStr, {
context: 'declarationList',
parseValue: false,
});
} catch (parseError) {
this.parseError = parseError;
return;
}
this.parseError = false;
var self = this;
declarations.children.each(function (declaration) {
try {
var styleDeclaration = csstools.csstreeToStyleDeclaration(declaration);
self.setProperty(
styleDeclaration.name,
styleDeclaration.value,
styleDeclaration.priority
);
} catch (styleError) {
if (styleError.message !== 'Unknown node type: undefined') {
self.parseError = styleError;
}
}
});
};
// only reads from properties
/**
* Get the textual representation of the declaration block (equivalent to .cssText attribute).
*
* @return {string} Textual representation of the declaration block (empty string for no properties)
*/
CSSStyleDeclaration.prototype.getCssText = function () {
var properties = this.getProperties();
if (this.parseError) {
// in case of a parse error, pass through original styles
return this.styleValue;
}
var cssText = [];
properties.forEach(function (property, propertyName) {
var strImportant = property.priority === 'important' ? '!important' : '';
cssText.push(
propertyName.trim() + ':' + property.value.trim() + strImportant
);
});
return cssText.join(';');
};
CSSStyleDeclaration.prototype._handleParseError = function () {
if (this.parseError) {
console.warn(
"Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " +
this.parseError
);
}
};
CSSStyleDeclaration.prototype._getProperty = function (propertyName) {
if (typeof propertyName === 'undefined') {
throw Error('1 argument required, but only 0 present.');
}
var properties = this.getProperties();
this._handleParseError();
var property = properties.get(propertyName.trim());
return property;
};
/**
* Return the optional priority, "important".
*
* @param {string} propertyName representing the property name to be checked.
* @return {string} priority that represents the priority (e.g. "important") if one exists. If none exists, returns the empty string.
*/
CSSStyleDeclaration.prototype.getPropertyPriority = function (propertyName) {
var property = this._getProperty(propertyName);
return property ? property.priority : '';
};
/**
* Return the property value given a property name.
*
* @param {string} propertyName representing the property name to be checked.
* @return {string} value containing the value of the property. If not set, returns the empty string.
*/
CSSStyleDeclaration.prototype.getPropertyValue = function (propertyName) {
var property = this._getProperty(propertyName);
return property ? property.value : null;
};
/**
* Return a property name.
*
* @param {number} index of the node to be fetched. The index is zero-based.
* @return {string} propertyName that is the name of the CSS property at the specified index.
*/
CSSStyleDeclaration.prototype.item = function (index) {
if (typeof index === 'undefined') {
throw Error('1 argument required, but only 0 present.');
}
var properties = this.getProperties();
this._handleParseError();
return Array.from(properties.keys())[index];
};
/**
* Return all properties of the node.
*
* @return {Map} properties that is a Map with propertyName as key and property (propertyValue + propertyPriority) as value.
*/
CSSStyleDeclaration.prototype.getProperties = function () {
this._loadCssText();
return this.properties;
};
// writes to properties
/**
* Remove a property from the CSS declaration block.
*
* @param {string} propertyName representing the property name to be removed.
* @return {string} oldValue equal to the value of the CSS property before it was removed.
*/
CSSStyleDeclaration.prototype.removeProperty = function (propertyName) {
if (typeof propertyName === 'undefined') {
throw Error('1 argument required, but only 0 present.');
}
this.addStyleValueHandler();
var properties = this.getProperties();
this._handleParseError();
var oldValue = this.getPropertyValue(propertyName);
properties.delete(propertyName.trim());
return oldValue;
};
/**
* Modify an existing CSS property or creates a new CSS property in the declaration block.
*
* @param {string} propertyName representing the CSS property name to be modified.
* @param {string} value containing the new property value. If not specified, treated as the empty string. value must not contain "!important" -- that should be set using the priority parameter.
* @param {string} priority allowing the "important" CSS priority to be set. If not specified, treated as the empty string.
* @return {{value: string, priority: string}}
*/
CSSStyleDeclaration.prototype.setProperty = function (
propertyName,
value,
priority
) {
if (typeof propertyName === 'undefined') {
throw Error('propertyName argument required, but only not present.');
}
this.addStyleValueHandler();
var properties = this.getProperties();
this._handleParseError();
var property = {
value: value.trim(),
priority: priority.trim(),
};
properties.set(propertyName.trim(), property);
return property;
};
module.exports = CSSStyleDeclaration;

2
node_modules/svgo/lib/svgo/jsAPI.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
declare let obj: any;
export = obj;

443
node_modules/svgo/lib/svgo/jsAPI.js generated vendored Normal file
View File

@@ -0,0 +1,443 @@
'use strict';
const { selectAll, selectOne, is } = require('css-select');
const svgoCssSelectAdapter = require('./css-select-adapter');
const CSSClassList = require('./css-class-list');
const CSSStyleDeclaration = require('./css-style-declaration');
/**
* @type {(name: string) => { prefix: string, local: string }}
*/
const parseName = (name) => {
if (name == null) {
return {
prefix: '',
local: '',
};
}
if (name === 'xmlns') {
return {
prefix: 'xmlns',
local: '',
};
}
const chunks = name.split(':');
if (chunks.length === 1) {
return {
prefix: '',
local: chunks[0],
};
}
return {
prefix: chunks[0],
local: chunks[1],
};
};
var cssSelectOpts = {
xmlMode: true,
adapter: svgoCssSelectAdapter,
};
const attrsHandler = {
get: (attributes, name) => {
// eslint-disable-next-line no-prototype-builtins
if (attributes.hasOwnProperty(name)) {
return {
name,
get value() {
return attributes[name];
},
set value(value) {
attributes[name] = value;
},
};
}
},
set: (attributes, name, attr) => {
attributes[name] = attr.value;
return true;
},
};
var JSAPI = function (data, parentNode) {
Object.assign(this, data);
if (this.type === 'element') {
if (this.attributes == null) {
this.attributes = {};
}
if (this.children == null) {
this.children = [];
}
Object.defineProperty(this, 'class', {
writable: true,
configurable: true,
value: new CSSClassList(this),
});
Object.defineProperty(this, 'style', {
writable: true,
configurable: true,
value: new CSSStyleDeclaration(this),
});
Object.defineProperty(this, 'parentNode', {
writable: true,
value: parentNode,
});
// temporary attrs polyfill
// TODO remove after migration
const element = this;
Object.defineProperty(this, 'attrs', {
configurable: true,
get() {
return new Proxy(element.attributes, attrsHandler);
},
set(value) {
const newAttributes = {};
for (const attr of Object.values(value)) {
newAttributes[attr.name] = attr.value;
}
element.attributes = newAttributes;
},
});
}
};
module.exports = JSAPI;
/**
* Perform a deep clone of this node.
*
* @return {Object} element
*/
JSAPI.prototype.clone = function () {
const { children, ...nodeData } = this;
// Deep-clone node data.
const clonedNode = new JSAPI(JSON.parse(JSON.stringify(nodeData)), null);
if (children) {
clonedNode.children = children.map((child) => {
const clonedChild = child.clone();
clonedChild.parentNode = clonedNode;
return clonedChild;
});
}
return clonedNode;
};
/**
* Determine if item is an element
* (any, with a specific name or in a names array).
*
* @param {String|Array} [param] element name or names arrays
* @return {Boolean}
*/
JSAPI.prototype.isElem = function (param) {
if (this.type !== 'element') {
return false;
}
if (param == null) {
return true;
}
if (Array.isArray(param)) {
return param.includes(this.name);
}
return this.name === param;
};
/**
* Renames an element
*
* @param {String} name new element name
* @return {Object} element
*/
JSAPI.prototype.renameElem = function (name) {
if (name && typeof name === 'string') this.name = name;
return this;
};
/**
* Determine if element is empty.
*
* @return {Boolean}
*/
JSAPI.prototype.isEmpty = function () {
return !this.children || !this.children.length;
};
/**
* Find the closest ancestor of the current element.
* @param elemName
*
* @return {?Object}
*/
JSAPI.prototype.closestElem = function (elemName) {
var elem = this;
while ((elem = elem.parentNode) && !elem.isElem(elemName));
return elem;
};
/**
* Changes children by removing elements and/or adding new elements.
*
* @param {Number} start Index at which to start changing the children.
* @param {Number} n Number of elements to remove.
* @param {Array|Object} [insertion] Elements to add to the children.
* @return {Array} Removed elements.
*/
JSAPI.prototype.spliceContent = function (start, n, insertion) {
if (arguments.length < 2) return [];
if (!Array.isArray(insertion))
insertion = Array.apply(null, arguments).slice(2);
insertion.forEach(function (inner) {
inner.parentNode = this;
}, this);
return this.children.splice.apply(
this.children,
[start, n].concat(insertion)
);
};
/**
* Determine if element has an attribute
* (any, or by name or by name + value).
*
* @param {String} [name] attribute name
* @param {String} [val] attribute value (will be toString()'ed)
* @return {Boolean}
*/
JSAPI.prototype.hasAttr = function (name, val) {
if (this.type !== 'element') {
return false;
}
if (Object.keys(this.attributes).length === 0) {
return false;
}
if (name == null) {
return true;
}
// eslint-disable-next-line no-prototype-builtins
if (this.attributes.hasOwnProperty(name) === false) {
return false;
}
if (val !== undefined) {
return this.attributes[name] === val.toString();
}
return true;
};
/**
* Determine if element has an attribute by local name
* (any, or by name or by name + value).
*
* @param {String} [localName] local attribute name
* @param {Number|String|RegExp|Function} [val] attribute value (will be toString()'ed or executed, otherwise ignored)
* @return {Boolean}
*/
JSAPI.prototype.hasAttrLocal = function (localName, val) {
if (!this.attrs || !Object.keys(this.attrs).length) return false;
if (!arguments.length) return !!this.attrs;
var callback;
switch (val != null && val.constructor && val.constructor.name) {
case 'Number': // same as String
case 'String':
callback = stringValueTest;
break;
case 'RegExp':
callback = regexpValueTest;
break;
case 'Function':
callback = funcValueTest;
break;
default:
callback = nameTest;
}
return this.someAttr(callback);
function nameTest(attr) {
const { local } = parseName(attr.name);
return local === localName;
}
function stringValueTest(attr) {
const { local } = parseName(attr.name);
return local === localName && val == attr.value;
}
function regexpValueTest(attr) {
const { local } = parseName(attr.name);
return local === localName && val.test(attr.value);
}
function funcValueTest(attr) {
const { local } = parseName(attr.name);
return local === localName && val(attr.value);
}
};
/**
* Get a specific attribute from an element
* (by name or name + value).
*
* @param {String} name attribute name
* @param {String} [val] attribute value (will be toString()'ed)
* @return {Object|Undefined}
*/
JSAPI.prototype.attr = function (name, val) {
if (this.hasAttr(name, val)) {
return this.attrs[name];
}
};
/**
* Get computed attribute value from an element
*
* @param {String} name attribute name
* @return {Object|Undefined}
*/
JSAPI.prototype.computedAttr = function (name, val) {
if (!arguments.length) return;
for (
var elem = this;
elem && (!elem.hasAttr(name) || !elem.attributes[name]);
elem = elem.parentNode
);
if (val != null) {
return elem ? elem.hasAttr(name, val) : false;
} else if (elem && elem.hasAttr(name)) {
return elem.attributes[name];
}
};
/**
* Remove a specific attribute.
*
* @param {String|Array} name attribute name
* @param {String} [val] attribute value
* @return {Boolean}
*/
JSAPI.prototype.removeAttr = function (name, val) {
if (this.type !== 'element') {
return false;
}
if (arguments.length === 0) {
return false;
}
if (Array.isArray(name)) {
for (const nameItem of name) {
this.removeAttr(nameItem, val);
}
return false;
}
if (this.hasAttr(name, val) === false) {
return false;
}
delete this.attributes[name];
return true;
};
/**
* Add attribute.
*
* @param {Object} [attr={}] attribute object
* @return {Object|Boolean} created attribute or false if no attr was passed in
*/
JSAPI.prototype.addAttr = function (attr) {
attr = attr || {};
if (attr.name === undefined) return false;
this.attributes[attr.name] = attr.value;
if (attr.name === 'class') {
// newly added class attribute
this.class.addClassValueHandler();
}
if (attr.name === 'style') {
// newly added style attribute
this.style.addStyleValueHandler();
}
return this.attrs[attr.name];
};
/**
* Iterates over all attributes.
*
* @param {Function} callback callback
* @param {Object} [context] callback context
* @return {Boolean} false if there are no any attributes
*/
JSAPI.prototype.eachAttr = function (callback, context) {
if (this.type !== 'element') {
return false;
}
if (callback == null) {
return false;
}
for (const attr of Object.values(this.attrs)) {
callback.call(context, attr);
}
return true;
};
/**
* Tests whether some attribute passes the test.
*
* @param {Function} callback callback
* @param {Object} [context] callback context
* @return {Boolean} false if there are no any attributes
*/
JSAPI.prototype.someAttr = function (callback, context) {
if (this.type !== 'element') {
return false;
}
for (const attr of Object.values(this.attrs)) {
if (callback.call(context, attr)) return true;
}
return false;
};
/**
* Evaluate a string of CSS selectors against the element and returns matched elements.
*
* @param {String} selectors CSS selector(s) string
* @return {Array} null if no elements matched
*/
JSAPI.prototype.querySelectorAll = function (selectors) {
var matchedEls = selectAll(selectors, this, cssSelectOpts);
return matchedEls.length > 0 ? matchedEls : null;
};
/**
* Evaluate a string of CSS selectors against the element and returns only the first matched element.
*
* @param {String} selectors CSS selector(s) string
* @return {Array} null if no element matched
*/
JSAPI.prototype.querySelector = function (selectors) {
return selectOne(selectors, this, cssSelectOpts);
};
/**
* Test if a selector matches a given element.
*
* @param {String} selector CSS selector string
* @return {Boolean} true if element would be selected by selector string, false if it does not
*/
JSAPI.prototype.matches = function (selector) {
return is(this, selector, cssSelectOpts);
};

109
node_modules/svgo/lib/svgo/plugins.js generated vendored Normal file
View File

@@ -0,0 +1,109 @@
'use strict';
const { visit } = require('../xast.js');
/**
* Plugins engine.
*
* @module plugins
*
* @param {Object} ast input ast
* @param {Object} info extra information
* @param {Array} plugins plugins object from config
* @return {Object} output ast
*/
const invokePlugins = (ast, info, plugins, overrides, globalOverrides) => {
for (const plugin of plugins) {
const override = overrides == null ? null : overrides[plugin.name];
if (override === false) {
continue;
}
const params = { ...plugin.params, ...globalOverrides, ...override };
if (plugin.type === 'perItem') {
ast = perItem(ast, info, plugin, params);
}
if (plugin.type === 'perItemReverse') {
ast = perItem(ast, info, plugin, params, true);
}
if (plugin.type === 'full') {
if (plugin.active) {
ast = plugin.fn(ast, params, info);
}
}
if (plugin.type === 'visitor') {
if (plugin.active) {
const visitor = plugin.fn(ast, params, info);
if (visitor != null) {
visit(ast, visitor);
}
}
}
}
return ast;
};
exports.invokePlugins = invokePlugins;
/**
* Direct or reverse per-item loop.
*
* @param {Object} data input data
* @param {Object} info extra information
* @param {Array} plugins plugins list to process
* @param {boolean} [reverse] reverse pass?
* @return {Object} output data
*/
function perItem(data, info, plugin, params, reverse) {
function monkeys(items) {
items.children = items.children.filter(function (item) {
// reverse pass
if (reverse && item.children) {
monkeys(item);
}
// main filter
let kept = true;
if (plugin.active) {
kept = plugin.fn(item, params, info) !== false;
}
// direct pass
if (!reverse && item.children) {
monkeys(item);
}
return kept;
});
return items;
}
return monkeys(data);
}
const createPreset = ({ name, plugins }) => {
return {
name,
type: 'full',
fn: (ast, params, info) => {
const { floatPrecision, overrides } = params;
const globalOverrides = {};
if (floatPrecision != null) {
globalOverrides.floatPrecision = floatPrecision;
}
if (overrides) {
for (const [pluginName, override] of Object.entries(overrides)) {
if (override === true) {
console.warn(
`You are trying to enable ${pluginName} which is not part of preset.\n` +
`Try to put it before or after preset, for example\n\n` +
`plugins: [\n` +
` {\n` +
` name: 'preset-default',\n` +
` },\n` +
` 'cleanupListOfValues'\n` +
`]\n`
);
}
}
}
return invokePlugins(ast, info, plugins, overrides, globalOverrides);
},
};
};
exports.createPreset = createPreset;

137
node_modules/svgo/lib/svgo/tools.js generated vendored Normal file
View File

@@ -0,0 +1,137 @@
'use strict';
/**
* @typedef {import('../types').PathDataCommand} PathDataCommand
*/
/**
* Encode plain SVG data string into Data URI string.
*
* @type {(str: string, type?: 'base64' | 'enc' | 'unenc') => string}
*/
exports.encodeSVGDatauri = (str, type) => {
var prefix = 'data:image/svg+xml';
if (!type || type === 'base64') {
// base64
prefix += ';base64,';
str = prefix + Buffer.from(str).toString('base64');
} else if (type === 'enc') {
// URI encoded
str = prefix + ',' + encodeURIComponent(str);
} else if (type === 'unenc') {
// unencoded
str = prefix + ',' + str;
}
return str;
};
/**
* Decode SVG Data URI string into plain SVG string.
*
* @type {(str: string) => string}
*/
exports.decodeSVGDatauri = (str) => {
var regexp = /data:image\/svg\+xml(;charset=[^;,]*)?(;base64)?,(.*)/;
var match = regexp.exec(str);
// plain string
if (!match) return str;
var data = match[3];
if (match[2]) {
// base64
str = Buffer.from(data, 'base64').toString('utf8');
} else if (data.charAt(0) === '%') {
// URI encoded
str = decodeURIComponent(data);
} else if (data.charAt(0) === '<') {
// unencoded
str = data;
}
return str;
};
/**
* @typedef {{
* noSpaceAfterFlags?: boolean,
* leadingZero?: boolean,
* negativeExtraSpace?: boolean
* }} CleanupOutDataParams
*/
/**
* Convert a row of numbers to an optimized string view.
*
* @example
* [0, -1, .5, .5] → "0-1 .5.5"
*
* @type {(data: Array<number>, params: CleanupOutDataParams, command?: PathDataCommand) => string}
*/
exports.cleanupOutData = (data, params, command) => {
let str = '';
let delimiter;
/**
* @type {number}
*/
let prev;
data.forEach((item, i) => {
// space delimiter by default
delimiter = ' ';
// no extra space in front of first number
if (i == 0) delimiter = '';
// no extra space after 'arcto' command flags(large-arc and sweep flags)
// a20 60 45 0 1 30 20 → a20 60 45 0130 20
if (params.noSpaceAfterFlags && (command == 'A' || command == 'a')) {
var pos = i % 7;
if (pos == 4 || pos == 5) delimiter = '';
}
// remove floating-point numbers leading zeros
// 0.5 → .5
// -0.5 → -.5
const itemStr = params.leadingZero
? removeLeadingZero(item)
: item.toString();
// no extra space in front of negative number or
// in front of a floating number if a previous number is floating too
if (
params.negativeExtraSpace &&
delimiter != '' &&
(item < 0 || (itemStr.charAt(0) === '.' && prev % 1 !== 0))
) {
delimiter = '';
}
// save prev item value
prev = item;
str += delimiter + itemStr;
});
return str;
};
/**
* Remove floating-point numbers leading zero.
*
* @example
* 0.5 → .5
*
* @example
* -0.5 → -.5
*
* @type {(num: number) => string}
*/
const removeLeadingZero = (num) => {
var strNum = num.toString();
if (0 < num && num < 1 && strNum.charAt(0) === '0') {
strNum = strNum.slice(1);
} else if (-1 < num && num < 0 && strNum.charAt(1) === '0') {
strNum = strNum.charAt(0) + strNum.slice(2);
}
return strNum;
};
exports.removeLeadingZero = removeLeadingZero;

172
node_modules/svgo/lib/types.ts generated vendored Normal file
View File

@@ -0,0 +1,172 @@
export type XastDoctype = {
type: 'doctype';
name: string;
data: {
doctype: string;
};
};
export type XastInstruction = {
type: 'instruction';
name: string;
value: string;
};
export type XastComment = {
type: 'comment';
value: string;
};
export type XastCdata = {
type: 'cdata';
value: string;
};
export type XastText = {
type: 'text';
value: string;
};
export type XastElement = {
type: 'element';
name: string;
attributes: Record<string, string>;
children: Array<XastChild>;
};
export type XastChild =
| XastDoctype
| XastInstruction
| XastComment
| XastCdata
| XastText
| XastElement;
export type XastRoot = {
type: 'root';
children: Array<XastChild>;
};
export type XastParent = XastRoot | XastElement;
export type XastNode = XastRoot | XastChild;
export type StringifyOptions = {
doctypeStart?: string;
doctypeEnd?: string;
procInstStart?: string;
procInstEnd?: string;
tagOpenStart?: string;
tagOpenEnd?: string;
tagCloseStart?: string;
tagCloseEnd?: string;
tagShortStart?: string;
tagShortEnd?: string;
attrStart?: string;
attrEnd?: string;
commentStart?: string;
commentEnd?: string;
cdataStart?: string;
cdataEnd?: string;
textStart?: string;
textEnd?: string;
indent?: number | string;
regEntities?: RegExp;
regValEntities?: RegExp;
encodeEntity?: (char: string) => string;
pretty?: boolean;
useShortTags?: boolean;
eol?: 'lf' | 'crlf';
finalNewline?: boolean;
};
type VisitorNode<Node> = {
enter?: (node: Node, parentNode: XastParent) => void | symbol;
exit?: (node: Node, parentNode: XastParent) => void;
};
type VisitorRoot = {
enter?: (node: XastRoot, parentNode: null) => void;
exit?: (node: XastRoot, parentNode: null) => void;
};
export type Visitor = {
doctype?: VisitorNode<XastDoctype>;
instruction?: VisitorNode<XastInstruction>;
comment?: VisitorNode<XastComment>;
cdata?: VisitorNode<XastCdata>;
text?: VisitorNode<XastText>;
element?: VisitorNode<XastElement>;
root?: VisitorRoot;
};
export type PluginInfo = {
path?: string;
multipassCount: number;
};
export type Plugin<Params> = (
root: XastRoot,
params: Params,
info: PluginInfo
) => null | Visitor;
export type Specificity = [number, number, number, number];
export type StylesheetDeclaration = {
name: string;
value: string;
important: boolean;
};
export type StylesheetRule = {
dynamic: boolean;
selectors: string;
specificity: Specificity;
declarations: Array<StylesheetDeclaration>;
};
export type Stylesheet = {
rules: Array<StylesheetRule>;
parents: Map<XastElement, XastParent>;
};
type StaticStyle = {
type: 'static';
inherited: boolean;
value: string;
};
type DynamicStyle = {
type: 'dynamic';
inherited: boolean;
};
export type ComputedStyles = Record<string, StaticStyle | DynamicStyle>;
export type PathDataCommand =
| 'M'
| 'm'
| 'Z'
| 'z'
| 'L'
| 'l'
| 'H'
| 'h'
| 'V'
| 'v'
| 'C'
| 'c'
| 'S'
| 's'
| 'Q'
| 'q'
| 'T'
| 't'
| 'A'
| 'a';
export type PathDataItem = {
command: PathDataCommand;
args: Array<number>;
};

102
node_modules/svgo/lib/xast.js generated vendored Normal file
View File

@@ -0,0 +1,102 @@
'use strict';
/**
* @typedef {import('./types').XastNode} XastNode
* @typedef {import('./types').XastChild} XastChild
* @typedef {import('./types').XastParent} XastParent
* @typedef {import('./types').Visitor} Visitor
*/
const { selectAll, selectOne, is } = require('css-select');
const xastAdaptor = require('./svgo/css-select-adapter.js');
const cssSelectOptions = {
xmlMode: true,
adapter: xastAdaptor,
};
/**
* @type {(node: XastNode, selector: string) => Array<XastChild>}
*/
const querySelectorAll = (node, selector) => {
return selectAll(selector, node, cssSelectOptions);
};
exports.querySelectorAll = querySelectorAll;
/**
* @type {(node: XastNode, selector: string) => null | XastChild}
*/
const querySelector = (node, selector) => {
return selectOne(selector, node, cssSelectOptions);
};
exports.querySelector = querySelector;
/**
* @type {(node: XastChild, selector: string) => boolean}
*/
const matches = (node, selector) => {
return is(node, selector, cssSelectOptions);
};
exports.matches = matches;
/**
* @type {(node: XastChild, name: string) => null | XastChild}
*/
const closestByName = (node, name) => {
let currentNode = node;
while (currentNode) {
if (currentNode.type === 'element' && currentNode.name === name) {
return currentNode;
}
// @ts-ignore parentNode is hidden from public usage
currentNode = currentNode.parentNode;
}
return null;
};
exports.closestByName = closestByName;
const visitSkip = Symbol();
exports.visitSkip = visitSkip;
/**
* @type {(node: XastNode, visitor: Visitor, parentNode?: any) => void}
*/
const visit = (node, visitor, parentNode) => {
const callbacks = visitor[node.type];
if (callbacks && callbacks.enter) {
// @ts-ignore hard to infer
const symbol = callbacks.enter(node, parentNode);
if (symbol === visitSkip) {
return;
}
}
// visit root children
if (node.type === 'root') {
// copy children array to not loose cursor when children is spliced
for (const child of node.children) {
visit(child, visitor, node);
}
}
// visit element children if still attached to parent
if (node.type === 'element') {
if (parentNode.children.includes(node)) {
for (const child of node.children) {
visit(child, visitor, node);
}
}
}
if (callbacks && callbacks.exit) {
// @ts-ignore hard to infer
callbacks.exit(node, parentNode);
}
};
exports.visit = visit;
/**
* @type {(node: XastChild, parentNode: XastParent) => void}
*/
const detachNodeFromParent = (node, parentNode) => {
// avoid splice to not break for loops
parentNode.children = parentNode.children.filter((child) => child !== node);
};
exports.detachNodeFromParent = detachNodeFromParent;

440
node_modules/svgo/node_modules/commander/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,440 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.)
<!-- markdownlint-disable MD024 -->
<!-- markdownlint-disable MD004 -->
## [7.2.0] (2021-03-26)
### Added
- TypeScript typing for `parent` property on `Command` ([#1475])
- TypeScript typing for `.attributeName()` on `Option` ([#1483])
- support information in package ([#1477])
### Changed
- improvements to error messages, README, and tests
- update dependencies
## [7.1.0] (2021-02-15)
### Added
- support for named imports from ECMAScript modules ([#1440])
- add `.cjs` to list of expected script file extensions ([#1449])
- allow using option choices and variadic together ([#1454])
### Fixed
- replace use of deprecated `process.mainModule` ([#1448])
- regression for legacy `command('*')` and call when command line includes options ([#1464])
- regression for `on('command:*', ...)` and call when command line includes unknown options ([#1464])
- display best error for combination of unknown command and unknown option (i.e. unknown command) ([#1464])
### Changed
- make TypeScript typings tests stricter ([#1453])
- improvements to README and tests
## [7.0.0] (2021-01-15)
### Added
- `.enablePositionalOptions()` to let program and subcommand reuse same option ([#1427])
- `.passThroughOptions()` to pass options through to other programs without needing `--` ([#1427])
- `.allowExcessArguments(false)` to show an error message if there are too many command-arguments on command line for the action handler ([#1409])
- `.configureOutput()` to modify use of stdout and stderr or customise display of errors ([#1387])
- use `.addHelpText()` to add text before or after the built-in help, for just current command or also for all subcommands ([#1296])
- enhance Option class ([#1331])
- allow hiding options from help
- allow restricting option arguments to a list of choices
- allow setting how default value is shown in help
- `.createOption()` to support subclassing of automatically created options (like `.createCommand()`) ([#1380])
- refactor the code generating the help into a separate public Help class ([#1365])
- support sorting subcommands and options in help
- support specifying wrap width (columns)
- allow subclassing Help class
- allow configuring Help class without subclassing
### Changed
- *Breaking:* options are stored safely by default, not as properties on the command ([#1409])
- this especially affects accessing options on program, use `program.opts()`
- revert behaviour with `.storeOptionsAsProperties()`
- *Breaking:* action handlers are passed options and command separately ([#1409])
- deprecated callback parameter to `.help()` and `.outputHelp()` (removed from README) ([#1296])
- *Breaking:* errors now displayed using `process.stderr.write()` instead of `console.error()`
- deprecate `.on('--help')` (removed from README) ([#1296])
- initialise the command description to empty string (previously undefined) ([#1365])
- document and annotate deprecated routines ([#1349])
### Fixed
- wrapping bugs in help ([#1365])
- first line of command description was wrapping two characters early
- pad width calculation was not including help option and help command
- pad width calculation was including hidden options and commands
- improve backwards compatibility for custom command event listeners ([#1403])
### Deleted
- *Breaking:* `.passCommandToAction()` ([#1409])
- no longer needed as action handler is passed options and command
- *Breaking:* "extra arguments" parameter to action handler ([#1409])
- if being used to detect excess arguments, there is now an error available by setting `.allowExcessArguments(false)`
### Migration Tips
The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately.
If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`.
To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_,
to match the new "options" and "command" parameters (see below).
**program options**
Use the `.opts()` method to access the options. This is available on any command but is used most with the program.
```js
program.option('-d, --debug');
program.parse();
// Old code before Commander 7
if (program.debug) console.log(`Program name is ${program.name()}`);
```
```js
// New code
const options = program.opts();
if (options.debug) console.log(`Program name is ${program.name()}`);
```
**action handler**
The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you
only accessed the options there may be no code changes required.
```js
program
.command('compress <filename>')
.option('-t, --trace')
// Old code before Commander 7
.action((filename, cmd)) => {
if (cmd.trace) console.log(`Command name is ${cmd.name()}`);
});
```
```js
// New code
.action((filename, options, command)) => {
if (options.trace) console.log(`Command name is ${command.name()}`);
});
```
If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code.
```js
program
.command('compress <filename>')
.storeOptionsAsProperties(false)
.option('-t, --trace')
// Old code before Commander 7
.action((filename, command)) => {
if (command.opts().trace) console.log(`Command name is ${command.name()}`);
});
```
```js
// New code
.action((filename, options, command)) => {
if (command.opts().trace) console.log(`Command name is ${command.name()}`);
});
```
## [7.0.0-2] (2020-12-14)
(Released in 7.0.0)
## [7.0.0-1] (2020-11-21)
(Released in 7.0.0)
## [7.0.0-0] (2020-10-25)
(Released in 7.0.0)
## [6.2.1] (2020-12-13)
### Fixed
- some tests failed if directory path included a space ([1390])
## [6.2.0] (2020-10-25)
### Added
- added 'tsx' file extension for stand-alone executable subcommands ([#1368])
- documented second parameter to `.description()` to describe command arguments ([#1353])
- documentation of special cases with options taking varying numbers of option-arguments ([#1332])
- documentation for terminology ([#1361])
### Fixed
- add missing TypeScript definition for `.addHelpCommand()' ([#1375])
- removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" ([#1360])
### Changed
- update dependencies
## [6.1.0] (2020-08-28)
### Added
- include URL to relevant section of README for error for potential conflict between Command properties and option values ([#1306])
- `.combineFlagAndOptionalValue(false)` to ease upgrade path from older versions of Commander ([#1326])
- allow disabling the built-in help option using `.helpOption(false)` ([#1325])
- allow just some arguments in `argumentDescription` to `.description()` ([#1323])
### Changed
- tidy async test and remove lint override ([#1312])
### Fixed
- executable subcommand launching when script path not known ([#1322])
## [6.0.0] (2020-07-21)
### Added
- add support for variadic options ([#1250])
- allow options to be added with just a short flag ([#1256])
- *Breaking* the option property has same case as flag. e.g. flag `-n` accessed as `opts().n` (previously uppercase)
- *Breaking* throw an error if there might be a clash between option name and a Command property, with advice on how to resolve ([#1275])
### Fixed
- Options which contain -no- in the middle of the option flag should not be treated as negatable. ([#1301])
## [6.0.0-0] (2020-06-20)
(Released in 6.0.0)
## [5.1.0] (2020-04-25)
### Added
- support for multiple command aliases, the first of which is shown in the auto-generated help ([#531], [#1236])
- configuration support in `addCommand()` for `hidden` and `isDefault` ([#1232])
### Fixed
- omit masked help flags from the displayed help ([#645], [#1247])
- remove old short help flag when change help flags using `helpOption` ([#1248])
### Changed
- remove use of `arguments` to improve auto-generated help in editors ([#1235])
- rename `.command()` configuration `noHelp` to `hidden` (but not remove old support) ([#1232])
- improvements to documentation
- update dependencies
- update tested versions of node
- eliminate lint errors in TypeScript ([#1208])
## [5.0.0] (2020-03-14)
### Added
* support for nested commands with action-handlers ([#1] [#764] [#1149])
* `.addCommand()` for adding a separately configured command ([#764] [#1149])
* allow a non-executable to be set as the default command ([#742] [#1149])
* implicit help command when there are subcommands (previously only if executables) ([#1149])
* customise implicit help command with `.addHelpCommand()` ([#1149])
* display error message for unknown subcommand, by default ([#432] [#1088] [#1149])
* display help for missing subcommand, by default ([#1088] [#1149])
* combined short options as single argument may include boolean flags and value flag and value (e.g. `-a -b -p 80` can be written as `-abp80`) ([#1145])
* `.parseOption()` includes short flag and long flag expansions ([#1145])
* `.helpInformation()` returns help text as a string, previously a private routine ([#1169])
* `.parse()` implicitly uses `process.argv` if arguments not specified ([#1172])
* optionally specify where `.parse()` arguments "from", if not following node conventions ([#512] [#1172])
* suggest help option along with unknown command error ([#1179])
* TypeScript definition for `commands` property of `Command` ([#1184])
* export `program` property ([#1195])
* `createCommand` factory method to simplify subclassing ([#1191])
### Fixed
* preserve argument order in subcommands ([#508] [#962] [#1138])
* do not emit `command:*` for executable subcommands ([#809] [#1149])
* action handler called whether or not there are non-option arguments ([#1062] [#1149])
* combining option short flag and value in single argument now works for subcommands ([#1145])
* only add implicit help command when it will not conflict with other uses of argument ([#1153] [#1149])
* implicit help command works with command aliases ([#948] [#1149])
* options are validated whether or not there is an action handler ([#1149])
### Changed
* *Breaking* `.args` contains command arguments with just recognised options removed ([#1032] [#1138])
* *Breaking* display error if required argument for command is missing ([#995] [#1149])
* tighten TypeScript definition of custom option processing function passed to `.option()` ([#1119])
* *Breaking* `.allowUnknownOption()` ([#802] [#1138])
* unknown options included in arguments passed to command action handler
* unknown options included in `.args`
* only recognised option short flags and long flags are expanded (e.g. `-ab` or `--foo=bar`) ([#1145])
* *Breaking* `.parseOptions()` ([#1138])
* `args` in returned result renamed `operands` and does not include anything after first unknown option
* `unknown` in returned result has arguments after first unknown option including operands, not just options and values
* *Breaking* `.on('command:*', callback)` and other command events passed (changed) results from `.parseOptions`, i.e. operands and unknown ([#1138])
* refactor Option from prototype to class ([#1133])
* refactor Command from prototype to class ([#1159])
* changes to error handling ([#1165])
* throw for author error, not just display message
* preflight for variadic error
* add tips to missing subcommand executable
* TypeScript fluent return types changed to be more subclass friendly, return `this` rather than `Command` ([#1180])
* `.parseAsync` returns `Promise<this>` to be consistent with `.parse()` ([#1180])
* update dependencies
### Removed
* removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on `@types/node` ([#1146])
* removed private function `normalize` (the functionality has been integrated into `parseOptions`) ([#1145])
* `parseExpectedArgs` is now private ([#1149])
### Migration Tips
If you use `.on('command:*')` or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour.
If you use `program.args` or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour.
If you use `.command('*')` to add a default command, you may be be able to switch to `isDefault:true` with a named command.
If you want to continue combining short options with optional values as though they were boolean flags, set `combineFlagAndOptionalValue(false)`
to expand `-fb` to `-f -b` rather than `-f b`.
## [5.0.0-4] (2020-03-03)
(Released in 5.0.0)
## [5.0.0-3] (2020-02-20)
(Released in 5.0.0)
## [5.0.0-2] (2020-02-10)
(Released in 5.0.0)
## [5.0.0-1] (2020-02-08)
(Released in 5.0.0)
## [5.0.0-0] (2020-02-02)
(Released in 5.0.0)
## Older versions
* [4.x](./changelogs/CHANGELOG-4.md)
* [3.x](./changelogs/CHANGELOG-3.md)
* [2.x](./changelogs/CHANGELOG-2.md)
* [1.x](./changelogs/CHANGELOG-1.md)
* [0.x](./changelogs/CHANGELOG-0.md)
[#1]: https://github.com/tj/commander.js/issues/1
[#432]: https://github.com/tj/commander.js/issues/432
[#508]: https://github.com/tj/commander.js/issues/508
[#512]: https://github.com/tj/commander.js/issues/512
[#531]: https://github.com/tj/commander.js/issues/531
[#645]: https://github.com/tj/commander.js/issues/645
[#742]: https://github.com/tj/commander.js/issues/742
[#764]: https://github.com/tj/commander.js/issues/764
[#802]: https://github.com/tj/commander.js/issues/802
[#809]: https://github.com/tj/commander.js/issues/809
[#948]: https://github.com/tj/commander.js/issues/948
[#962]: https://github.com/tj/commander.js/issues/962
[#995]: https://github.com/tj/commander.js/issues/995
[#1032]: https://github.com/tj/commander.js/issues/1032
[#1062]: https://github.com/tj/commander.js/pull/1062
[#1088]: https://github.com/tj/commander.js/issues/1088
[#1119]: https://github.com/tj/commander.js/pull/1119
[#1133]: https://github.com/tj/commander.js/pull/1133
[#1138]: https://github.com/tj/commander.js/pull/1138
[#1145]: https://github.com/tj/commander.js/pull/1145
[#1146]: https://github.com/tj/commander.js/pull/1146
[#1149]: https://github.com/tj/commander.js/pull/1149
[#1153]: https://github.com/tj/commander.js/issues/1153
[#1159]: https://github.com/tj/commander.js/pull/1159
[#1165]: https://github.com/tj/commander.js/pull/1165
[#1169]: https://github.com/tj/commander.js/pull/1169
[#1172]: https://github.com/tj/commander.js/pull/1172
[#1179]: https://github.com/tj/commander.js/pull/1179
[#1180]: https://github.com/tj/commander.js/pull/1180
[#1184]: https://github.com/tj/commander.js/pull/1184
[#1191]: https://github.com/tj/commander.js/pull/1191
[#1195]: https://github.com/tj/commander.js/pull/1195
[#1208]: https://github.com/tj/commander.js/pull/1208
[#1232]: https://github.com/tj/commander.js/pull/1232
[#1235]: https://github.com/tj/commander.js/pull/1235
[#1236]: https://github.com/tj/commander.js/pull/1236
[#1247]: https://github.com/tj/commander.js/pull/1247
[#1248]: https://github.com/tj/commander.js/pull/1248
[#1250]: https://github.com/tj/commander.js/pull/1250
[#1256]: https://github.com/tj/commander.js/pull/1256
[#1275]: https://github.com/tj/commander.js/pull/1275
[#1296]: https://github.com/tj/commander.js/pull/1296
[#1301]: https://github.com/tj/commander.js/issues/1301
[#1306]: https://github.com/tj/commander.js/pull/1306
[#1312]: https://github.com/tj/commander.js/pull/1312
[#1322]: https://github.com/tj/commander.js/pull/1322
[#1323]: https://github.com/tj/commander.js/pull/1323
[#1325]: https://github.com/tj/commander.js/pull/1325
[#1326]: https://github.com/tj/commander.js/pull/1326
[#1331]: https://github.com/tj/commander.js/pull/1331
[#1332]: https://github.com/tj/commander.js/pull/1332
[#1349]: https://github.com/tj/commander.js/pull/1349
[#1353]: https://github.com/tj/commander.js/pull/1353
[#1360]: https://github.com/tj/commander.js/pull/1360
[#1361]: https://github.com/tj/commander.js/pull/1361
[#1365]: https://github.com/tj/commander.js/pull/1365
[#1368]: https://github.com/tj/commander.js/pull/1368
[#1375]: https://github.com/tj/commander.js/pull/1375
[#1380]: https://github.com/tj/commander.js/pull/1380
[#1387]: https://github.com/tj/commander.js/pull/1387
[#1390]: https://github.com/tj/commander.js/pull/1390
[#1403]: https://github.com/tj/commander.js/pull/1403
[#1409]: https://github.com/tj/commander.js/pull/1409
[#1427]: https://github.com/tj/commander.js/pull/1427
[#1440]: https://github.com/tj/commander.js/pull/1440
[#1448]: https://github.com/tj/commander.js/pull/1448
[#1449]: https://github.com/tj/commander.js/pull/1449
[#1453]: https://github.com/tj/commander.js/pull/1453
[#1454]: https://github.com/tj/commander.js/pull/1454
[#1464]: https://github.com/tj/commander.js/pull/1464
[#1475]: https://github.com/tj/commander.js/pull/1475
[#1477]: https://github.com/tj/commander.js/pull/1477
[#1483]: https://github.com/tj/commander.js/pull/1483
[Unreleased]: https://github.com/tj/commander.js/compare/master...develop
[7.2.0]: https://github.com/tj/commander.js/compare/v7.1.0...v7.2.0
[7.1.0]: https://github.com/tj/commander.js/compare/v7.0.0...v7.1.0
[7.0.0]: https://github.com/tj/commander.js/compare/v6.2.1...v7.0.0
[7.0.0-2]: https://github.com/tj/commander.js/compare/v7.0.0-1...v7.0.0-2
[7.0.0-1]: https://github.com/tj/commander.js/compare/v7.0.0-0...v7.0.0-1
[7.0.0-0]: https://github.com/tj/commander.js/compare/v6.2.0...v7.0.0-0
[6.2.1]: https://github.com/tj/commander.js/compare/v6.2.0..v6.2.1
[6.2.0]: https://github.com/tj/commander.js/compare/v6.1.0..v6.2.0
[6.1.0]: https://github.com/tj/commander.js/compare/v6.0.0..v6.1.0
[6.0.0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0
[6.0.0-0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0-0
[5.1.0]: https://github.com/tj/commander.js/compare/v5.0.0..v5.1.0
[5.0.0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0
[5.0.0-4]: https://github.com/tj/commander.js/compare/v5.0.0-3..v5.0.0-4
[5.0.0-3]: https://github.com/tj/commander.js/compare/v5.0.0-2..v5.0.0-3
[5.0.0-2]: https://github.com/tj/commander.js/compare/v5.0.0-1..v5.0.0-2
[5.0.0-1]: https://github.com/tj/commander.js/compare/v5.0.0-0..v5.0.0-1
[5.0.0-0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0-0

22
node_modules/svgo/node_modules/commander/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

917
node_modules/svgo/node_modules/commander/Readme.md generated vendored Normal file
View File

@@ -0,0 +1,917 @@
# Commander.js
[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
The complete solution for [node.js](http://nodejs.org) command-line interfaces.
Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
- [Commander.js](#commanderjs)
- [Installation](#installation)
- [Declaring _program_ variable](#declaring-program-variable)
- [Options](#options)
- [Common option types, boolean and value](#common-option-types-boolean-and-value)
- [Default option value](#default-option-value)
- [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
- [Required option](#required-option)
- [Variadic option](#variadic-option)
- [Version option](#version-option)
- [More configuration](#more-configuration)
- [Custom option processing](#custom-option-processing)
- [Commands](#commands)
- [Specify the argument syntax](#specify-the-argument-syntax)
- [Action handler](#action-handler)
- [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
- [Automated help](#automated-help)
- [Custom help](#custom-help)
- [Display help from code](#display-help-from-code)
- [.usage and .name](#usage-and-name)
- [.helpOption(flags, description)](#helpoptionflags-description)
- [.addHelpCommand()](#addhelpcommand)
- [More configuration](#more-configuration-1)
- [Custom event listeners](#custom-event-listeners)
- [Bits and pieces](#bits-and-pieces)
- [.parse() and .parseAsync()](#parse-and-parseasync)
- [Parsing Configuration](#parsing-configuration)
- [Legacy options as properties](#legacy-options-as-properties)
- [TypeScript](#typescript)
- [createCommand()](#createcommand)
- [Node options such as `--harmony`](#node-options-such-as---harmony)
- [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
- [Override exit and output handling](#override-exit-and-output-handling)
- [Additional documentation](#additional-documentation)
- [Examples](#examples)
- [Support](#support)
- [Commander for enterprise](#commander-for-enterprise)
For information about terms used in this document see: [terminology](./docs/terminology.md)
## Installation
```bash
npm install commander
```
## Declaring _program_ variable
Commander exports a global object which is convenient for quick programs.
This is used in the examples in this README for brevity.
```js
const { program } = require('commander');
program.version('0.0.1');
```
For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
```js
const { Command } = require('commander');
const program = new Command();
program.version('0.0.1');
```
For named imports in ECMAScript modules, import from `commander/esm.mjs`.
```js
// index.mjs
import { Command } from 'commander/esm.mjs';
const program = new Command();
```
And in TypeScript:
```ts
// index.ts
import { Command } from 'commander';
const program = new Command();
```
## Options
Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').
The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).
For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
By default options on the command line are not positional, and can be specified before or after other arguments.
### Common option types, boolean and value
The two most used option types are a boolean option, and an option which takes its value
from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
Example file: [options-common.js](./examples/options-common.js)
```js
program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');
program.parse(process.argv);
const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
```
```bash
$ pizza-options -d
{ debug: true, small: undefined, pizzaType: undefined }
pizza details:
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -ds -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese
```
`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.
### Default option value
You can specify a default value for an option which takes a value.
Example file: [options-defaults.js](./examples/options-defaults.js)
```js
program
.option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
program.parse();
console.log(`cheese: ${program.opts().cheese}`);
```
```bash
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton
```
### Other option types, negatable boolean and boolean|value
You can define a boolean option long name with a leading `no-` to set the option value to false when used.
Defined alone this also makes the option true by default.
If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
otherwise be. You can specify a default boolean value for a boolean option and it can be overridden on command line.
Example file: [options-negatable.js](./examples/options-negatable.js)
```js
program
.option('--no-sauce', 'Remove sauce')
.option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
.option('--no-cheese', 'plain with no cheese')
.parse();
const options = program.opts();
const sauceStr = options.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
```
```bash
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese
```
You can specify an option which may be used as a boolean option but may optionally take an option-argument
(declared with square brackets like `--optional [value]`).
Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
```js
program
.option('-c, --cheese [type]', 'Add cheese with optional type');
program.parse(process.argv);
const options = program.opts();
if (options.cheese === undefined) console.log('no cheese');
else if (options.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${options.cheese}`);
```
```bash
$ pizza-options
no cheese
$ pizza-options --cheese
add cheese
$ pizza-options --cheese mozzarella
add cheese type mozzarella
```
For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
### Required option
You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.
Example file: [options-required.js](./examples/options-required.js)
```js
program
.requiredOption('-c, --cheese <type>', 'pizza must have cheese');
program.parse();
```
```bash
$ pizza
error: required option '-c, --cheese <type>' not specified
```
### Variadic option
You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
is specified in the same argument as the option then no further values are read.
Example file: [options-variadic.js](./examples/options-variadic.js)
```js
program
.option('-n, --number <numbers...>', 'specify numbers')
.option('-l, --letter [letters...]', 'specify letters');
program.parse();
console.log('Options: ', program.opts());
console.log('Remaining arguments: ', program.args);
```
```bash
$ collect -n 1 2 3 --letter a b c
Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
Remaining arguments: []
$ collect --letter=A -n80 operand
Options: { number: [ '80' ], letter: [ 'A' ] }
Remaining arguments: [ 'operand' ]
$ collect --letter -n 1 -n 2 3 -- operand
Options: { number: [ '1', '2', '3' ], letter: true }
Remaining arguments: [ 'operand' ]
```
For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
### Version option
The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
```js
program.version('0.0.1');
```
```bash
$ ./examples/pizza -V
0.0.1
```
You may change the flags and description by passing additional parameters to the `version` method, using
the same syntax for flags as the `option` method.
```js
program.version('0.0.1', '-v, --vers', 'output the current version');
```
### More configuration
You can add most options using the `.option()` method, but there are some additional features available
by constructing an `Option` explicitly for less common cases.
Example file: [options-extra.js](./examples/options-extra.js)
```js
program
.addOption(new Option('-s, --secret').hideHelp())
.addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
.addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']));
```
```bash
$ extra --help
Usage: help [options]
Options:
-t, --timeout <delay> timeout in seconds (default: one minute)
-d, --drink <size> drink cup size (choices: "small", "medium", "large")
-h, --help display help for command
$ extra --drink huge
error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.
```
### Custom option processing
You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
the user specified option-argument and the previous value for the option. It returns the new value for the option.
This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
You can optionally specify the default/starting value for the option after the function parameter.
Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
```js
function myParseInt(value, dummyPrevious) {
// parseInt takes a string and a radix
const parsedValue = parseInt(value, 10);
if (isNaN(parsedValue)) {
throw new commander.InvalidOptionArgumentError('Not a number.');
}
return parsedValue;
}
function increaseVerbosity(dummyValue, previous) {
return previous + 1;
}
function collect(value, previous) {
return previous.concat([value]);
}
function commaSeparatedList(value, dummyPrevious) {
return value.split(',');
}
program
.option('-f, --float <number>', 'float argument', parseFloat)
.option('-i, --integer <number>', 'integer argument', myParseInt)
.option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
.option('-c, --collect <value>', 'repeatable value', collect, [])
.option('-l, --list <items>', 'comma separated list', commaSeparatedList)
;
program.parse();
const options = program.opts();
if (options.float !== undefined) console.log(`float: ${options.float}`);
if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
if (options.collect.length > 0) console.log(options.collect);
if (options.list !== undefined) console.log(options.list);
```
```bash
$ custom -f 1e2
float: 100
$ custom --integer 2
integer: 2
$ custom -v -v -v
verbose: 3
$ custom -c a -c b -c c
[ 'a', 'b', 'c' ]
$ custom --list x,y,z
[ 'x', 'y', 'z' ]
```
## Commands
You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
In the first parameter to `.command()` you specify the command name and any command-arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
You can use `.addCommand()` to add an already configured subcommand to the program.
For example:
```js
// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination) => {
console.log('clone command called');
});
// Command implemented using stand-alone executable file (description is second parameter to `.command`)
// Returns `this` for adding more commands.
program
.command('start <service>', 'start named service')
.command('stop [service]', 'stop named service, or all if no name supplied');
// Command prepared separately.
// Returns `this` for adding more commands.
program
.addCommand(build.makeBuildCommand());
```
Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
subcommand is specified ([example](./examples/defaultCommand.js)).
### Specify the argument syntax
You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually
included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.
Square brackets (e.g. `[optional]`) indicate optional command-arguments.
You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.
Example file: [arguments.js](./examples/arguments.js)
```js
program
.version('0.1.0')
.arguments('<username> [password]')
.description('test command', {
username: 'user to login',
password: 'password for user, if required'
})
.action((username, password) => {
console.log('username:', username);
console.log('environment:', password || 'no password given');
});
```
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
append `...` to the argument name. For example:
```js
program
.version('0.1.0')
.command('rmdir <dirs...>')
.action(function (dirs) {
dirs.forEach((dir) => {
console.log('rmdir %s', dir);
});
});
```
The variadic argument is passed to the action handler as an array.
### Action handler
The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
which are the parsed options and the command object itself.
Example file: [thank.js](./examples/thank.js)
```js
program
.arguments('<name>')
.option('-t, --title <honorific>', 'title to use before name')
.option('-d, --debug', 'display some debugging')
.action((name, options, command) => {
if (options.debug) {
console.error('Called %s with options %o', command.name(), options);
}
const title = options.title ? `${options.title} ` : '';
console.log(`Thank-you ${title}${name}`);
});
```
You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
```js
async function run() { /* code goes here */ }
async function main() {
program
.command('run')
.action(run);
await program.parseAsync(process.argv);
}
```
A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to
pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.
### Stand-alone executable (sub)commands
When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
You can specify a custom name with the `executableFile` configuration option.
You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
Example file: [pm](./examples/pm)
```js
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
.command('list', 'list packages installed', { isDefault: true });
program.parse(process.argv);
```
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
## Automated help
The help information is auto-generated based on the information commander already knows about your program. The default
help option is `-h,--help`.
Example file: [pizza](./examples/pizza)
```bash
$ node ./examples/pizza --help
Usage: pizza [options]
An application for pizza ordering
Options:
-p, --peppers Add peppers
-c, --cheese <type> Add the specified type of cheese (default: "marble")
-C, --no-cheese You do not want any cheese
-h, --help display help for command
```
A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
```bash
shell help
shell --help
shell help spawn
shell spawn --help
```
### Custom help
You can add extra text to be displayed along with the built-in help.
Example file: [custom-help](./examples/custom-help)
```js
program
.option('-f, --foo', 'enable some foo');
program.addHelpText('after', `
Example call:
$ custom-help --help`);
```
Yields the following help output:
```Text
Usage: custom-help [options]
Options:
-f, --foo enable some foo
-h, --help display help for command
Example call:
$ custom-help --help
```
The positions in order displayed are:
- `beforeAll`: add to the program for a global banner or header
- `before`: display extra information before built-in help
- `after`: display extra information after built-in help
- `afterAll`: add to the program for a global footer (epilog)
The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.
The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:
- error: a boolean for whether the help is being displayed due to a usage error
- command: the Command which is displaying the help
### Display help from code
`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.
`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.
### .usage and .name
These allow you to customise the usage description in the first line of the help. The name is otherwise
deduced from the (full) program arguments. Given:
```js
program
.name("my-command")
.usage("[global options] command")
```
The help will start with:
```Text
Usage: my-command [global options] command
```
### .helpOption(flags, description)
By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option.
```js
program
.helpOption('-e, --HELP', 'read more information');
```
### .addHelpCommand()
A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.
You can both turn on and customise the help command by supplying the name and description:
```js
program.addHelpCommand('assist [command]', 'show assistance');
```
### More configuration
The built-in help is formatted using the Help class.
You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.
The data properties are:
- `helpWidth`: specify the wrap width, useful for unit tests
- `sortSubcommands`: sort the subcommands alphabetically
- `sortOptions`: sort the options alphabetically
There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.
Example file: [configure-help.js](./examples/configure-help.js)
```
program.configureHelp({
sortSubcommands: true,
subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
});
```
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.opts().verbose;
});
program.on('command:*', function (operands) {
console.error(`error: unknown command '${operands[0]}'`);
const availableCommands = program.commands.map(cmd => cmd.name());
mySuggestBestMatch(operands[0], availableCommands);
process.exitCode = 1;
});
```
## Bits and pieces
### .parse() and .parseAsync()
The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
- 'electron': `argv[1]` varies depending on whether the electron application is packaged
- 'user': all of the arguments from the user
For example:
```js
program.parse(process.argv); // Explicit, node conventions
program.parse(); // Implicit, and auto-detect electron
program.parse(['-f', 'filename'], { from: 'user' });
```
### Parsing Configuration
If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
an option for a different purpose in subcommands.
Example file: [positional-options.js](./examples/positional-options.js)
With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:
```sh
program -b subcommand
program subcommand -b
```
By default options are recognised before and after command-arguments. To only process options that come
before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
without needing to use `--` to end the option processing.
To use pass through options in a subcommand, the program needs to enable positional options.
Example file: [pass-through-options.js](./examples/pass-through-options.js)
With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line:
```sh
program --port=80 arg
program arg --port=80
```
By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.
By default the argument processing does not display an error for more command-arguments than expected.
To display an error for excess arguments, use`.allowExcessArguments(false)`.
### Legacy options as properties
Before Commander 7, the option values were stored as properties on the command.
This was convenient to code but the downside was possible clashes with
existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
```js
program
.storeOptionsAsProperties()
.option('-d, --debug')
.action((commandAndOptions) => {
if (commandAndOptions.debug) {
console.error(`Called ${commandAndOptions.name()}`);
}
});
```
### TypeScript
If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.
```bash
node -r ts-node/register pm.ts
```
### createCommand()
This factory function creates a new command. It is exported and may be used instead of using `new`, like:
```js
const { createCommand } = require('commander');
const program = createCommand();
```
`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
when creating subcommands using `.command()`, and you may override it to
customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
### Node options such as `--harmony`
You can enable `--harmony` option in two ways:
- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
### Debugging stand-alone executable subcommands
An executable subcommand is launched as a separate child process.
If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,
the inspector port is incremented by 1 for the spawned subcommand.
If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
### Override exit and output handling
By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
is not affected by the override which is called after the display.
```js
program.exitOverride();
try {
program.parse(process.argv);
} catch (err) {
// custom processing...
}
```
By default Commander is configured for a command-line application and writes to stdout and stderr.
You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
Example file: [configure-output.js](./examples/configure-output.js)
```js
function errorColor(str) {
// Add ANSI escape codes to display text in red.
return `\x1b[31m${str}\x1b[0m`;
}
program
.configureOutput({
// Visibly override write routines as example!
writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
// Highlight errors in color.
outputError: (str, write) => write(errorColor(str))
});
```
### Additional documentation
There is more information available about:
- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
- [options taking varying arguments](./docs/options-taking-varying-arguments.md)
## Examples
In a single command program, you might not need an action handler.
Example file: [pizza](./examples/pizza)
```js
const { program } = require('commander');
program
.description('An application for pizza ordering')
.option('-p, --peppers', 'Add peppers')
.option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')
.option('-C, --no-cheese', 'You do not want any cheese');
program.parse();
const options = program.opts();
console.log('you ordered a pizza with:');
if (options.peppers) console.log(' - peppers');
const cheese = !options.cheese ? 'no' : options.cheese;
console.log(' - %s cheese', cheese);
```
In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands).
Example file: [deploy](./examples/deploy)
```js
const { Command } = require('commander');
const program = new Command();
program
.version('0.0.1')
.option('-c, --config <path>', 'set config path', './deploy.conf');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')
.action((env, options) => {
env = env || 'all';
console.log('read config from %s', program.opts().config);
console.log('setup for %s env(s) with %s mode', env, options.setup_mode);
});
program
.command('exec <script>')
.alias('ex')
.description('execute the given remote cmd')
.option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')
.action((script, options) => {
console.log('read config from %s', program.opts().config);
console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config);
}).addHelpText('after', `
Examples:
$ deploy exec sequential
$ deploy exec async`
);
program.parse(process.argv);
```
More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## Support
The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v10.
(For older versions of node, use an older version of Commander. Commander version 2.x has the widest support.)
The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
### Commander for enterprise
Available as part of the Tidelift Subscription
The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

4
node_modules/svgo/node_modules/commander/esm.mjs generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import commander from './index.js';
// wrapper to provide named exports for ESM.
export const { program, Option, Command, CommanderError, InvalidOptionArgumentError, Help, createCommand } = commander;

2217
node_modules/svgo/node_modules/commander/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "supported"
},
"response": {
"type": "time-permitting"
},
"backing": {
"npm-funding": true
}
}
]
}

68
node_modules/svgo/node_modules/commander/package.json generated vendored Normal file
View File

@@ -0,0 +1,68 @@
{
"name": "commander",
"version": "7.2.0",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser",
"cli",
"argument",
"args",
"argv"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "eslint index.js esm.mjs \"tests/**/*.js\"",
"typescript-lint": "eslint typings/*.ts tests/*.ts",
"test": "jest && npm run test-typings",
"test-esm": "node --experimental-modules ./tests/esm-imports-test.mjs",
"test-typings": "tsd",
"typescript-checkJS": "tsc --allowJS --checkJS index.js --noEmit",
"test-all": "npm run test && npm run lint && npm run typescript-lint && npm run typescript-checkJS && npm run test-esm"
},
"main": "./index.js",
"files": [
"index.js",
"esm.mjs",
"typings/index.d.ts",
"package-support.json"
],
"type": "commonjs",
"dependencies": {},
"devDependencies": {
"@types/jest": "^26.0.20",
"@types/node": "^14.14.20",
"@typescript-eslint/eslint-plugin": "^4.12.0",
"@typescript-eslint/parser": "^4.12.0",
"eslint": "^7.17.0",
"eslint-config-standard": "^16.0.2",
"eslint-plugin-jest": "^24.1.3",
"jest": "^26.6.3",
"standard": "^16.0.3",
"ts-jest": "^26.5.1",
"tsd": "^0.14.0",
"typescript": "^4.1.2"
},
"types": "typings/index.d.ts",
"jest": {
"testEnvironment": "node",
"collectCoverage": true,
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testPathIgnorePatterns": [
"/node_modules/"
]
},
"engines": {
"node": ">= 10"
},
"support": true
}

View File

@@ -0,0 +1,627 @@
// Type definitions for commander
// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Using method rather than property for method-signature-style, to document method overloads separately. Allow either.
/* eslint-disable @typescript-eslint/method-signature-style */
/* eslint-disable @typescript-eslint/no-explicit-any */
declare namespace commander {
interface CommanderError extends Error {
code: string;
exitCode: number;
message: string;
nestedError?: string;
}
type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface InvalidOptionArgumentError extends CommanderError {
}
type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;
interface Option {
flags: string;
description: string;
required: boolean; // A value must be supplied when the option is specified.
optional: boolean; // A value is optional when the option is specified.
variadic: boolean;
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
optionFlags: string;
short?: string;
long?: string;
negate: boolean;
defaultValue?: any;
defaultValueDescription?: string;
parseArg?: <T>(value: string, previous: T) => T;
hidden: boolean;
argChoices?: string[];
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default(value: any, description?: string): this;
/**
* Calculate the full description, including defaultValue etc.
*/
fullDescription(): string;
/**
* Set the custom handler for processing CLI option arguments into option values.
*/
argParser<T>(fn: (value: string, previous: T) => T): this;
/**
* Whether the option is mandatory and must have a value after parsing.
*/
makeOptionMandatory(mandatory?: boolean): this;
/**
* Hide option in help.
*/
hideHelp(hide?: boolean): this;
/**
* Validation of option argument failed.
* Intended for use from custom argument processing functions.
*/
argumentRejected(messsage: string): never;
/**
* Only allow option value to be one of choices.
*/
choices(values: string[]): this;
/**
* Return option name.
*/
name(): string;
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*/
attributeName(): string;
}
type OptionConstructor = new (flags: string, description?: string) => Option;
interface Help {
/** output helpWidth, long lines are wrapped to fit */
helpWidth?: number;
sortSubcommands: boolean;
sortOptions: boolean;
/** Get the command term to show in the list of subcommands. */
subcommandTerm(cmd: Command): string;
/** Get the command description to show in the list of subcommands. */
subcommandDescription(cmd: Command): string;
/** Get the option term to show in the list of options. */
optionTerm(option: Option): string;
/** Get the option description to show in the list of options. */
optionDescription(option: Option): string;
/** Get the command usage to be displayed at the top of the built-in help. */
commandUsage(cmd: Command): string;
/** Get the description for the command. */
commandDescription(cmd: Command): string;
/** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
visibleCommands(cmd: Command): Command[];
/** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
visibleOptions(cmd: Command): Option[];
/** Get an array of the arguments which have descriptions. */
visibleArguments(cmd: Command): Array<{ term: string; description: string}>;
/** Get the longest command term length. */
longestSubcommandTermLength(cmd: Command, helper: Help): number;
/** Get the longest option term length. */
longestOptionTermLength(cmd: Command, helper: Help): number;
/** Get the longest argument term length. */
longestArgumentTermLength(cmd: Command, helper: Help): number;
/** Calculate the pad width from the maximum term length. */
padWidth(cmd: Command, helper: Help): number;
/**
* Wrap the given string to width characters per line, with lines after the first indented.
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
*/
wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;
/** Generate the built-in help text. */
formatHelp(cmd: Command, helper: Help): string;
}
type HelpConstructor = new () => Help;
type HelpConfiguration = Partial<Help>;
interface ParseOptions {
from: 'node' | 'electron' | 'user';
}
interface HelpContext { // optional parameter for .help() and .outputHelp()
error: boolean;
}
interface AddHelpTextContext { // passed to text function used with .addHelpText()
error: boolean;
command: Command;
}
interface OutputConfiguration {
writeOut?(str: string): void;
writeErr?(str: string): void;
getOutHelpWidth?(): number;
getErrHelpWidth?(): number;
outputError?(str: string, write: (str: string) => void): void;
}
type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
interface OptionValues {
[key: string]: any;
}
interface Command {
args: string[];
commands: Command[];
parent: Command | null;
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*/
version(str: string, flags?: string, description?: string): this;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns `this` command for chaining
*/
command(nameAndArgs: string, description: string, opts?: commander.ExecutableCommandOptions): this;
/**
* Factory routine to create a new unattached command.
*
* See .command() for creating an attached subcommand, which uses this routine to
* create the command. You can override createCommand to customise subcommands.
*/
createCommand(name?: string): Command;
/**
* Add a prepared subcommand.
*
* See .command() for creating an attached subcommand which inherits settings from its parent.
*
* @returns `this` command for chaining
*/
addCommand(cmd: Command, opts?: CommandOptions): this;
/**
* Define argument syntax for command.
*
* @returns `this` command for chaining
*/
arguments(desc: string): this;
/**
* Override default decision whether to add implicit help command.
*
* addHelpCommand() // force on
* addHelpCommand(false); // force off
* addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
*
* @returns `this` command for chaining
*/
addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
/**
* Register callback to use as replacement for calling process.exit.
*/
exitOverride(callback?: (err: CommanderError) => never|void): this;
/**
* You can customise the help with a subclass of Help by overriding createHelp,
* or by overriding Help properties using configureHelp().
*/
createHelp(): Help;
/**
* You can customise the help by overriding Help properties using configureHelp(),
* or with a subclass of Help by overriding createHelp().
*/
configureHelp(configuration: HelpConfiguration): this;
/** Get configuration */
configureHelp(): HelpConfiguration;
/**
* The default output goes to stdout and stderr. You can customise this for special
* applications. You can also customise the display of errors by overriding outputError.
*
* The configuration properties are all functions:
*
* // functions to change where being written, stdout and stderr
* writeOut(str)
* writeErr(str)
* // matching functions to specify width for wrapping help
* getOutHelpWidth()
* getErrHelpWidth()
* // functions based on what is being written out
* outputError(str, write) // used for displaying errors, and not used for displaying help
*/
configureOutput(configuration: OutputConfiguration): this;
/** Get configuration */
configureOutput(): OutputConfiguration;
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @returns `this` command for chaining
*/
action(fn: (...args: any[]) => void | Promise<void>): this;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string contains the short and/or long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @returns `this` command for chaining
*/
option(flags: string, description?: string, defaultValue?: string | boolean): this;
option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
/** @deprecated since v7, instead use choices or a custom function */
option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
/**
* Define a required option, which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
*/
requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;
requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
/** @deprecated since v7, instead use choices or a custom function */
requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
/**
* Factory routine to create a new unattached option.
*
* See .option() for creating an attached option, which uses this routine to
* create the option. You can override createOption to return a custom option.
*/
createOption(flags: string, description?: string): Option;
/**
* Add a prepared Option.
*
* See .option() and .requiredOption() for creating and attaching an option in a single call.
*/
addOption(option: Option): this;
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @returns `this` command for chaining
*/
storeOptionsAsProperties(): this & OptionValues;
storeOptionsAsProperties(storeAsProperties: true): this & OptionValues;
storeOptionsAsProperties(storeAsProperties?: boolean): this;
/**
* Alter parsing of short flags with optional values.
*
* @example
* // for `.option('-f,--flag [value]'):
* .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
* .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
*
* @returns `this` command for chaining
*/
combineFlagAndOptionalValue(combine?: boolean): this;
/**
* Allow unknown options on the command line.
*
* @returns `this` command for chaining
*/
allowUnknownOption(allowUnknown?: boolean): this;
/**
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
*
* @returns `this` command for chaining
*/
allowExcessArguments(allowExcess?: boolean): this;
/**
* Enable positional options. Positional means global options are specified before subcommands which lets
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
*
* The default behaviour is non-positional and global options may appear anywhere on the command line.
*
* @returns `this` command for chaining
*/
enablePositionalOptions(positional?: boolean): this;
/**
* Pass through options that come after command-arguments rather than treat them as command-options,
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
* positional options to have been enabled on the program (parent commands).
*
* The default behaviour is non-positional and options may appear before or after command-arguments.
*
* @returns `this` command for chaining
*/
passThroughOptions(passThrough?: boolean): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* The default expectation is that the arguments are from node and have the application as argv[0]
* and the script being run in argv[1], with user parameters after that.
*
* Examples:
*
* program.parse(process.argv);
* program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
*
* @returns `this` command for chaining
*/
parse(argv?: string[], options?: ParseOptions): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
*
* The default expectation is that the arguments are from node and have the application as argv[0]
* and the script being run in argv[1], with user parameters after that.
*
* Examples:
*
* program.parseAsync(process.argv);
* program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
* program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
*
* @returns Promise
*/
parseAsync(argv?: string[], options?: ParseOptions): Promise<this>;
/**
* Parse options from `argv` removing known options,
* and return argv split into operands and unknown arguments.
*
* @example
* argv => operands, unknown
* --known kkk op => [op], []
* op --known kkk => [op], []
* sub --unknown uuu op => [sub], [--unknown uuu op]
* sub -- --unknown uuu op => [sub --unknown uuu op], []
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;
/**
* Return an object containing options as key-value pairs
*/
opts(): OptionValues;
/**
* Set the description.
*
* @returns `this` command for chaining
*/
description(str: string, argsDescription?: {[argName: string]: string}): this;
/**
* Get the description.
*/
description(): string;
/**
* Set an alias for the command.
*
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
alias(alias: string): this;
/**
* Get alias for the command.
*/
alias(): string;
/**
* Set aliases for the command.
*
* Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
aliases(aliases: string[]): this;
/**
* Get aliases for the command.
*/
aliases(): string[];
/**
* Set the command usage.
*
* @returns `this` command for chaining
*/
usage(str: string): this;
/**
* Get the command usage.
*/
usage(): string;
/**
* Set the name of the command.
*
* @returns `this` command for chaining
*/
name(str: string): this;
/**
* Get the name of the command.
*/
name(): string;
/**
* Output help information for this command.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*
*/
outputHelp(context?: HelpContext): void;
/** @deprecated since v7 */
outputHelp(cb?: (str: string) => string): void;
/**
* Return command help documentation.
*/
helpInformation(context?: HelpContext): string;
/**
* You can pass in flags and a description to override the help
* flags and help description for your command. Pass in false
* to disable the built-in help option.
*/
helpOption(flags?: string | boolean, description?: string): this;
/**
* Output help information and exit.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*/
help(context?: HelpContext): never;
/** @deprecated since v7 */
help(cb?: (str: string) => string): never;
/**
* Add additional text to be displayed with the built-in help.
*
* Position is 'before' or 'after' to affect just this command,
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
*/
addHelpText(position: AddHelpTextPosition, text: string): this;
addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string | undefined): this;
/**
* Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
*/
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
type CommandConstructor = new (name?: string) => Command;
interface CommandOptions {
hidden?: boolean;
isDefault?: boolean;
/** @deprecated since v7, replaced by hidden */
noHelp?: boolean;
}
interface ExecutableCommandOptions extends CommandOptions {
executableFile?: string;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface ParseOptionsResult {
operands: string[];
unknown: string[];
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface CommanderStatic extends Command {
program: Command;
Command: CommandConstructor;
Option: OptionConstructor;
CommanderError: CommanderErrorConstructor;
InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor;
Help: HelpConstructor;
}
}
// Declaring namespace AND global
// eslint-disable-next-line @typescript-eslint/no-redeclare
declare const commander: commander.CommanderStatic;
export = commander;

11
node_modules/svgo/node_modules/css-select/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

255
node_modules/svgo/node_modules/css-select/README.md generated vendored Normal file
View File

@@ -0,0 +1,255 @@
# css-select [![NPM version](http://img.shields.io/npm/v/css-select.svg)](https://npmjs.org/package/css-select) [![Build Status](https://travis-ci.com/fb55/css-select.svg?branch=master)](http://travis-ci.com/fb55/css-select) [![Downloads](https://img.shields.io/npm/dm/css-select.svg)](https://npmjs.org/package/css-select) [![Coverage](https://coveralls.io/repos/fb55/css-select/badge.svg?branch=master)](https://coveralls.io/r/fb55/css-select)
A CSS selector compiler and engine
## What?
As a **compiler**, css-select turns CSS selectors into functions that tests if
elements match them.
As an **engine**, css-select looks through a DOM tree, searching for elements.
Elements are tested "from the top", similar to how browsers execute CSS
selectors.
In its default configuration, css-select queries the DOM structure of the
[`domhandler`](https://github.com/fb55/domhandler) module (also known as
htmlparser2 DOM). To query alternative DOM structures, see [`Options`](#options)
below.
**Features:**
- 🔬 Full implementation of CSS3 selectors, as well as most CSS4 selectors
- 🧪 Partial implementation of jQuery/Sizzle extensions (see
[cheerio-select](https://github.com/cheeriojs/cheerio-select) for the
remaining selectors)
- 🧑‍🔬 High test coverage, including the full test suites from Sizzle, Qwery and
NWMatcher.
- 🥼 Reliably great performance
## Why?
Most CSS engines written in JavaScript execute selectors left-to-right. That
means thet execute every component of the selector in order, from left to right
_(duh)_. As an example: For the selector `a b`, these engines will first query
for `a` elements, then search these for `b` elements. (That's the approach of
eg. [`Sizzle`](https://github.com/jquery/sizzle),
[`nwmatcher`](https://github.com/dperini/nwmatcher/) and
[`qwery`](https://github.com/ded/qwery).)
While this works, it has some downsides: Children of `a`s will be checked
multiple times; first, to check if they are also `a`s, then, for every superior
`a` once, if they are `b`s. Using
[Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be
`O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space
in the example above).
The far more efficient approach is to first look for `b` elements, then check if
they have superior `a` elements: Using big O notation again, that would be
`O(n)`. That's called right-to-left execution.
And that's what css-select does and why it's quite performant.
## How does it work?
By building a stack of functions.
_Wait, what?_
Okay, so let's suppose we want to compile the selector `a b`, for right-to-left
execution. We start by _parsing_ the selector. This turns the selector into an
array of the building blocks. That's what the
[`css-what`](https://github.com/fb55/css-what) module is for, if you want to
have a look.
Anyway, after parsing, we end up with an array like this one:
```js
[
{ type: "tag", name: "a" },
{ type: "descendant" },
{ type: "tag", name: "b" },
];
```
(Actually, this array is wrapped in another array, but that's another story,
involving commas in selectors.)
Now that we know the meaning of every part of the selector, we can compile it.
That is where things become interesting.
The basic idea is to turn every part of the selector into a function, which
takes an element as its only argument. The function checks whether a passed
element matches its part of the selector: If it does, the element is passed to
the next function representing the next part of the selector. That function does
the same. If an element is accepted by all parts of the selector, it _matches_
the selector and double rainbow ALL THE WAY.
As said before, we want to do right-to-left execution with all the big O
improvements. That means elements are passed from the rightmost part of the
selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course
`a`).
For traversals, such as the _descendant_ operating the space between `a` and
`b`, we walk up the DOM tree, starting from the element passed as argument.
_//TODO: More in-depth description. Implementation details. Build a spaceship._
## API
```js
const CSSselect = require("css-select");
```
**Note:** css-select throws errors when invalid selectors are passed to it.This
is done to aid with writing css selectors, but can be unexpected when processing
arbitrary strings.
#### `CSSselect.selectAll(query, elems, options)`
Queries `elems`, returns an array containing all matches.
- `query` can be either a CSS selector or a function.
- `elems` can be either an array of elements, or a single element. If it is an
element, its children will be queried.
- `options` is described below.
Aliases: `default` export, `CSSselect.iterate(query, elems)`.
#### `CSSselect.compile(query, options)`
Compiles the query, returns a function.
#### `CSSselect.is(elem, query, options)`
Tests whether or not an element is matched by `query`. `query` can be either a
CSS selector or a function.
#### `CSSselect.selectOne(query, elems, options)`
Arguments are the same as for `CSSselect.selectAll(query, elems)`. Only returns
the first match, or `null` if there was no match.
### Options
All options are optional.
- `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`.
- `rootFunc`: The last function in the stack, will be called with the last
element that's looked at.
- `adapter`: The adapter to use when interacting with the backing DOM
structure. By default it uses the `domutils` module.
- `context`: The context of the current query. Used to limit the scope of
searches. Can be matched directly using the `:scope` pseudo-selector.
- `cacheResults`: Allow css-select to cache results for some selectors,
sometimes greatly improving querying performance. Disable this if your
document can change in between queries with the same compiled selector.
Default: `true`.
#### Custom Adapters
A custom adapter must match the interface described
[here](https://github.com/fb55/css-select/blob/1aa44bdd64aaf2ebdfd7f338e2e76bed36521957/src/types.ts#L6-L96).
You may want to have a look at [`domutils`](https://github.com/fb55/domutils) to
see the default implementation, or at
[`css-select-browser-adapter`](https://github.com/nrkn/css-select-browser-adapter/blob/master/index.js)
for an implementation backed by the DOM.
## Supported selectors
_As defined by CSS 4 and / or jQuery._
- [Selector lists](https://developer.mozilla.org/en-US/docs/Web/CSS/Selector_list)
(`,`)
- [Universal](https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors)
(`*`)
- [Type](https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors)
(`<tagname>`)
- [Descendant](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator)
(` `)
- [Child](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator)
(`>`)
- Parent (`<`)
- [Adjacent sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator)
(`+`)
- [General sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator)
(`~`)
- [Attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors)
(`[attr=foo]`), with supported comparisons:
- `[attr]` (existential)
- `=`
- `~=`
- `|=`
- `*=`
- `^=`
- `$=`
- `!=`
- `i` and `s` can be added after the comparison to make the comparison
case-insensitive or case-sensitive (eg. `[attr=foo i]`). If neither is
supplied, css-select will follow the HTML spec's
[case-sensitivity rules](https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors).
- Pseudos:
- [`:not`](https://developer.mozilla.org/en-US/docs/Web/CSS/:not)
- [`:contains`](https://api.jquery.com/contains-selector)
- `:icontains` (case-insensitive version of `:contains`)
- [`:has`](https://developer.mozilla.org/en-US/docs/Web/CSS/:has)
- [`:root`](https://developer.mozilla.org/en-US/docs/Web/CSS/:root)
- [`:empty`](https://developer.mozilla.org/en-US/docs/Web/CSS/:empty)
- [`:parent`](https://api.jquery.com/parent-selector)
- [`:first-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child),
[`:last-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child),
[`:first-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type),
[`:last-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type)
- [`:only-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type),
[`:only-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child)
- [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child),
[`:nth-last-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child),
[`:nth-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type),
[`:nth-last-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type),
- [`:link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:link),
[`:any-link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:any-link)
- [`:visited`](https://developer.mozilla.org/en-US/docs/Web/CSS/:visited),
[`:hover`](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover),
[`:active`](https://developer.mozilla.org/en-US/docs/Web/CSS/:active)
(these depend on optional `Adapter` methods, so these will only match
elements if implemented in `Adapter`)
- [`:selected`](https://api.jquery.com/selected-selector),
[`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked)
- [`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled),
[`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled)
- [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required),
[`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional)
- [`:header`](https://api.jquery.com/header-selector),
[`:button`](https://api.jquery.com/button-selector),
[`:input`](https://api.jquery.com/input-selector),
[`:text`](https://api.jquery.com/text-selector),
[`:checkbox`](https://api.jquery.com/checkbox-selector),
[`:file`](https://api.jquery.com/file-selector),
[`:password`](https://api.jquery.com/password-selector),
[`:reset`](https://api.jquery.com/reset-selector),
[`:radio`](https://api.jquery.com/radio-selector) etc.
- [`:is`](https://developer.mozilla.org/en-US/docs/Web/CSS/:is), plus its
legacy alias `:matches`
- [`:scope`](https://developer.mozilla.org/en-US/docs/Web/CSS/:scope)
(uses the context from the passed options)
---
License: BSD-2-Clause
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security). Tidelift will
coordinate the fix and disclosure.
## `css-select` for enterprise
Available as part of the Tidelift Subscription
The maintainers of `css-select` and thousands of other packages are working with
Tidelift to deliver commercial support and maintenance for the open source
dependencies you use to build your applications. Save time, reduce risk, and
improve code health, while paying the maintainers of the exact dependencies you
use.
[Learn more.](https://tidelift.com/subscription/pkg/npm-css-select?utm_source=npm-css-select&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

View File

@@ -0,0 +1,7 @@
import { CompiledQuery, InternalOptions } from "./types";
import type { AttributeSelector, AttributeAction } from "css-what";
/**
* Attribute selectors
*/
export declare const attributeRules: Record<AttributeAction, <Node, ElementNode extends Node>(next: CompiledQuery<ElementNode>, data: AttributeSelector, options: InternalOptions<Node, ElementNode>) => CompiledQuery<ElementNode>>;
//# sourceMappingURL=attributes.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"attributes.d.ts","sourceRoot":"","sources":["../src/attributes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AACzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AA+EnE;;GAEG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,CAC/B,eAAe,EACf,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAC3B,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,EAChC,IAAI,EAAE,iBAAiB,EACvB,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,KAC1C,aAAa,CAAC,WAAW,CAAC,CAsLlC,CAAC"}

View File

@@ -0,0 +1,232 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.attributeRules = void 0;
var boolbase_1 = require("boolbase");
/**
* All reserved characters in a regex, used for escaping.
*
* Taken from XRegExp, (c) 2007-2020 Steven Levithan under the MIT license
* https://github.com/slevithan/xregexp/blob/95eeebeb8fac8754d54eafe2b4743661ac1cf028/src/xregexp.js#L794
*/
var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g;
function escapeRegex(value) {
return value.replace(reChars, "\\$&");
}
/**
* Attributes that are case-insensitive in HTML.
*
* @private
* @see https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
*/
var caseInsensitiveAttributes = new Set([
"accept",
"accept-charset",
"align",
"alink",
"axis",
"bgcolor",
"charset",
"checked",
"clear",
"codetype",
"color",
"compact",
"declare",
"defer",
"dir",
"direction",
"disabled",
"enctype",
"face",
"frame",
"hreflang",
"http-equiv",
"lang",
"language",
"link",
"media",
"method",
"multiple",
"nohref",
"noresize",
"noshade",
"nowrap",
"readonly",
"rel",
"rev",
"rules",
"scope",
"scrolling",
"selected",
"shape",
"target",
"text",
"type",
"valign",
"valuetype",
"vlink",
]);
function shouldIgnoreCase(selector, options) {
return typeof selector.ignoreCase === "boolean"
? selector.ignoreCase
: selector.ignoreCase === "quirks"
? !!options.quirksMode
: !options.xmlMode && caseInsensitiveAttributes.has(selector.name);
}
/**
* Attribute selectors
*/
exports.attributeRules = {
equals: function (next, data, options) {
var adapter = options.adapter;
var name = data.name;
var value = data.value;
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function (elem) {
var attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length === value.length &&
attr.toLowerCase() === value &&
next(elem));
};
}
return function (elem) {
return adapter.getAttributeValue(elem, name) === value && next(elem);
};
},
hyphen: function (next, data, options) {
var adapter = options.adapter;
var name = data.name;
var value = data.value;
var len = value.length;
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function hyphenIC(elem) {
var attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
(attr.length === len || attr.charAt(len) === "-") &&
attr.substr(0, len).toLowerCase() === value &&
next(elem));
};
}
return function hyphen(elem) {
var attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
(attr.length === len || attr.charAt(len) === "-") &&
attr.substr(0, len) === value &&
next(elem));
};
},
element: function (next, data, options) {
var adapter = options.adapter;
var name = data.name, value = data.value;
if (/\s/.test(value)) {
return boolbase_1.falseFunc;
}
var regex = new RegExp("(?:^|\\s)".concat(escapeRegex(value), "(?:$|\\s)"), shouldIgnoreCase(data, options) ? "i" : "");
return function element(elem) {
var attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= value.length &&
regex.test(attr) &&
next(elem));
};
},
exists: function (next, _a, _b) {
var name = _a.name;
var adapter = _b.adapter;
return function (elem) { return adapter.hasAttrib(elem, name) && next(elem); };
},
start: function (next, data, options) {
var adapter = options.adapter;
var name = data.name;
var value = data.value;
var len = value.length;
if (len === 0) {
return boolbase_1.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function (elem) {
var attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= len &&
attr.substr(0, len).toLowerCase() === value &&
next(elem));
};
}
return function (elem) {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.startsWith(value)) &&
next(elem);
};
},
end: function (next, data, options) {
var adapter = options.adapter;
var name = data.name;
var value = data.value;
var len = -value.length;
if (len === 0) {
return boolbase_1.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function (elem) {
var _a;
return ((_a = adapter
.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.substr(len).toLowerCase()) === value && next(elem);
};
}
return function (elem) {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.endsWith(value)) &&
next(elem);
};
},
any: function (next, data, options) {
var adapter = options.adapter;
var name = data.name, value = data.value;
if (value === "") {
return boolbase_1.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
var regex_1 = new RegExp(escapeRegex(value), "i");
return function anyIC(elem) {
var attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= value.length &&
regex_1.test(attr) &&
next(elem));
};
}
return function (elem) {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.includes(value)) &&
next(elem);
};
},
not: function (next, data, options) {
var adapter = options.adapter;
var name = data.name;
var value = data.value;
if (value === "") {
return function (elem) {
return !!adapter.getAttributeValue(elem, name) && next(elem);
};
}
else if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function (elem) {
var attr = adapter.getAttributeValue(elem, name);
return ((attr == null ||
attr.length !== value.length ||
attr.toLowerCase() !== value) &&
next(elem));
};
}
return function (elem) {
return adapter.getAttributeValue(elem, name) !== value && next(elem);
};
},
};

View File

@@ -0,0 +1,14 @@
import { InternalSelector } from "./types";
import { Selector } from "css-what";
import type { CompiledQuery, InternalOptions } from "./types";
/**
* Compiles a selector to an executable function.
*
* @param selector Selector to compile.
* @param options Compilation options.
* @param context Optional context for the selector.
*/
export declare function compile<Node, ElementNode extends Node>(selector: string | Selector[][], options: InternalOptions<Node, ElementNode>, context?: Node[] | Node): CompiledQuery<Node>;
export declare function compileUnsafe<Node, ElementNode extends Node>(selector: string | Selector[][], options: InternalOptions<Node, ElementNode>, context?: Node[] | Node): CompiledQuery<ElementNode>;
export declare function compileToken<Node, ElementNode extends Node>(token: InternalSelector[][], options: InternalOptions<Node, ElementNode>, context?: Node[] | Node): CompiledQuery<ElementNode>;
//# sourceMappingURL=compile.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAS,QAAQ,EAAgB,MAAM,UAAU,CAAC;AASzD,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE9D;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAClD,QAAQ,EAAE,MAAM,GAAG,QAAQ,EAAE,EAAE,EAC/B,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,IAAI,GACxB,aAAa,CAAC,IAAI,CAAC,CAGrB;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EACxD,QAAQ,EAAE,MAAM,GAAG,QAAQ,EAAE,EAAE,EAC/B,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,IAAI,GACxB,aAAa,CAAC,WAAW,CAAC,CAG5B;AAiDD,wBAAgB,YAAY,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EACvD,KAAK,EAAE,gBAAgB,EAAE,EAAE,EAC3B,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,IAAI,GACxB,aAAa,CAAC,WAAW,CAAC,CA2C5B"}

View File

@@ -0,0 +1,119 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileToken = exports.compileUnsafe = exports.compile = void 0;
var css_what_1 = require("css-what");
var boolbase_1 = require("boolbase");
var sort_1 = __importDefault(require("./sort"));
var procedure_1 = require("./procedure");
var general_1 = require("./general");
var subselects_1 = require("./pseudo-selectors/subselects");
/**
* Compiles a selector to an executable function.
*
* @param selector Selector to compile.
* @param options Compilation options.
* @param context Optional context for the selector.
*/
function compile(selector, options, context) {
var next = compileUnsafe(selector, options, context);
return (0, subselects_1.ensureIsTag)(next, options.adapter);
}
exports.compile = compile;
function compileUnsafe(selector, options, context) {
var token = typeof selector === "string" ? (0, css_what_1.parse)(selector) : selector;
return compileToken(token, options, context);
}
exports.compileUnsafe = compileUnsafe;
function includesScopePseudo(t) {
return (t.type === "pseudo" &&
(t.name === "scope" ||
(Array.isArray(t.data) &&
t.data.some(function (data) { return data.some(includesScopePseudo); }))));
}
var DESCENDANT_TOKEN = { type: css_what_1.SelectorType.Descendant };
var FLEXIBLE_DESCENDANT_TOKEN = {
type: "_flexibleDescendant",
};
var SCOPE_TOKEN = {
type: css_what_1.SelectorType.Pseudo,
name: "scope",
data: null,
};
/*
* CSS 4 Spec (Draft): 3.3.1. Absolutizing a Scope-relative Selector
* http://www.w3.org/TR/selectors4/#absolutizing
*/
function absolutize(token, _a, context) {
var adapter = _a.adapter;
// TODO Use better check if the context is a document
var hasContext = !!(context === null || context === void 0 ? void 0 : context.every(function (e) {
var parent = adapter.isTag(e) && adapter.getParent(e);
return e === subselects_1.PLACEHOLDER_ELEMENT || (parent && adapter.isTag(parent));
}));
for (var _i = 0, token_1 = token; _i < token_1.length; _i++) {
var t = token_1[_i];
if (t.length > 0 && (0, procedure_1.isTraversal)(t[0]) && t[0].type !== "descendant") {
// Don't continue in else branch
}
else if (hasContext && !t.some(includesScopePseudo)) {
t.unshift(DESCENDANT_TOKEN);
}
else {
continue;
}
t.unshift(SCOPE_TOKEN);
}
}
function compileToken(token, options, context) {
var _a;
token = token.filter(function (t) { return t.length > 0; });
token.forEach(sort_1.default);
context = (_a = options.context) !== null && _a !== void 0 ? _a : context;
var isArrayContext = Array.isArray(context);
var finalContext = context && (Array.isArray(context) ? context : [context]);
absolutize(token, options, finalContext);
var shouldTestNextSiblings = false;
var query = token
.map(function (rules) {
if (rules.length >= 2) {
var first = rules[0], second = rules[1];
if (first.type !== "pseudo" || first.name !== "scope") {
// Ignore
}
else if (isArrayContext && second.type === "descendant") {
rules[1] = FLEXIBLE_DESCENDANT_TOKEN;
}
else if (second.type === "adjacent" ||
second.type === "sibling") {
shouldTestNextSiblings = true;
}
}
return compileRules(rules, options, finalContext);
})
.reduce(reduceRules, boolbase_1.falseFunc);
query.shouldTestNextSiblings = shouldTestNextSiblings;
return query;
}
exports.compileToken = compileToken;
function compileRules(rules, options, context) {
var _a;
return rules.reduce(function (previous, rule) {
return previous === boolbase_1.falseFunc
? boolbase_1.falseFunc
: (0, general_1.compileGeneralSelector)(previous, rule, options, context, compileToken);
}, (_a = options.rootFunc) !== null && _a !== void 0 ? _a : boolbase_1.trueFunc);
}
function reduceRules(a, b) {
if (b === boolbase_1.falseFunc || a === boolbase_1.trueFunc) {
return a;
}
if (a === boolbase_1.falseFunc || b === boolbase_1.trueFunc) {
return b;
}
return function combine(elem) {
return a(elem) || b(elem);
};
}

View File

@@ -0,0 +1,3 @@
import type { CompiledQuery, InternalOptions, InternalSelector, CompileToken } from "./types";
export declare function compileGeneralSelector<Node, ElementNode extends Node>(next: CompiledQuery<ElementNode>, selector: InternalSelector, options: InternalOptions<Node, ElementNode>, context: Node[] | undefined, compileToken: CompileToken<Node, ElementNode>): CompiledQuery<ElementNode>;
//# sourceMappingURL=general.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"general.d.ts","sourceRoot":"","sources":["../src/general.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACR,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,YAAY,EACf,MAAM,SAAS,CAAC;AAOjB,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EACjE,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,EAChC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS,EAC3B,YAAY,EAAE,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,GAC9C,aAAa,CAAC,WAAW,CAAC,CAiK5B"}

View File

@@ -0,0 +1,140 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileGeneralSelector = void 0;
var attributes_1 = require("./attributes");
var pseudo_selectors_1 = require("./pseudo-selectors");
var css_what_1 = require("css-what");
/*
* All available rules
*/
function compileGeneralSelector(next, selector, options, context, compileToken) {
var adapter = options.adapter, equals = options.equals;
switch (selector.type) {
case css_what_1.SelectorType.PseudoElement: {
throw new Error("Pseudo-elements are not supported by css-select");
}
case css_what_1.SelectorType.ColumnCombinator: {
throw new Error("Column combinators are not yet supported by css-select");
}
case css_what_1.SelectorType.Attribute: {
if (selector.namespace != null) {
throw new Error("Namespaced attributes are not yet supported by css-select");
}
if (!options.xmlMode || options.lowerCaseAttributeNames) {
selector.name = selector.name.toLowerCase();
}
return attributes_1.attributeRules[selector.action](next, selector, options);
}
case css_what_1.SelectorType.Pseudo: {
return (0, pseudo_selectors_1.compilePseudoSelector)(next, selector, options, context, compileToken);
}
// Tags
case css_what_1.SelectorType.Tag: {
if (selector.namespace != null) {
throw new Error("Namespaced tag names are not yet supported by css-select");
}
var name_1 = selector.name;
if (!options.xmlMode || options.lowerCaseTags) {
name_1 = name_1.toLowerCase();
}
return function tag(elem) {
return adapter.getName(elem) === name_1 && next(elem);
};
}
// Traversal
case css_what_1.SelectorType.Descendant: {
if (options.cacheResults === false ||
typeof WeakSet === "undefined") {
return function descendant(elem) {
var current = elem;
while ((current = adapter.getParent(current))) {
if (adapter.isTag(current) && next(current)) {
return true;
}
}
return false;
};
}
// @ts-expect-error `ElementNode` is not extending object
var isFalseCache_1 = new WeakSet();
return function cachedDescendant(elem) {
var current = elem;
while ((current = adapter.getParent(current))) {
if (!isFalseCache_1.has(current)) {
if (adapter.isTag(current) && next(current)) {
return true;
}
isFalseCache_1.add(current);
}
}
return false;
};
}
case "_flexibleDescendant": {
// Include element itself, only used while querying an array
return function flexibleDescendant(elem) {
var current = elem;
do {
if (adapter.isTag(current) && next(current))
return true;
} while ((current = adapter.getParent(current)));
return false;
};
}
case css_what_1.SelectorType.Parent: {
return function parent(elem) {
return adapter
.getChildren(elem)
.some(function (elem) { return adapter.isTag(elem) && next(elem); });
};
}
case css_what_1.SelectorType.Child: {
return function child(elem) {
var parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(parent);
};
}
case css_what_1.SelectorType.Sibling: {
return function sibling(elem) {
var siblings = adapter.getSiblings(elem);
for (var i = 0; i < siblings.length; i++) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) && next(currentSibling)) {
return true;
}
}
return false;
};
}
case css_what_1.SelectorType.Adjacent: {
if (adapter.prevElementSibling) {
return function adjacent(elem) {
var previous = adapter.prevElementSibling(elem);
return previous != null && next(previous);
};
}
return function adjacent(elem) {
var siblings = adapter.getSiblings(elem);
var lastElement;
for (var i = 0; i < siblings.length; i++) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling)) {
lastElement = currentSibling;
}
}
return !!lastElement && next(lastElement);
};
}
case css_what_1.SelectorType.Universal: {
if (selector.namespace != null && selector.namespace !== "*") {
throw new Error("Namespaced universal selectors are not yet supported by css-select");
}
return next;
}
}
}
exports.compileGeneralSelector = compileGeneralSelector;

View File

@@ -0,0 +1,49 @@
import type { CompiledQuery, Options, Query, Adapter } from "./types";
export type { Options };
/**
* Compiles the query, returns a function.
*/
export declare const compile: <Node_1, ElementNode extends Node_1>(selector: string | import("css-what").Selector[][], options?: Options<Node_1, ElementNode> | undefined, context?: Node_1 | Node_1[] | undefined) => CompiledQuery<Node_1>;
export declare const _compileUnsafe: <Node_1, ElementNode extends Node_1>(selector: string | import("css-what").Selector[][], options?: Options<Node_1, ElementNode> | undefined, context?: Node_1 | Node_1[] | undefined) => CompiledQuery<ElementNode>;
export declare const _compileToken: <Node_1, ElementNode extends Node_1>(selector: import("./types").InternalSelector[][], options?: Options<Node_1, ElementNode> | undefined, context?: Node_1 | Node_1[] | undefined) => CompiledQuery<ElementNode>;
export declare function prepareContext<Node, ElementNode extends Node>(elems: Node | Node[], adapter: Adapter<Node, ElementNode>, shouldTestNextSiblings?: boolean): Node[];
/**
* @template Node The generic Node type for the DOM adapter being used.
* @template ElementNode The Node type for elements for the DOM adapter being used.
* @param elems Elements to query. If it is an element, its children will be queried..
* @param query can be either a CSS selector string or a compiled query function.
* @param [options] options for querying the document.
* @see compile for supported selector queries.
* @returns All matching elements.
*
*/
export declare const selectAll: <Node_1, ElementNode extends Node_1>(query: Query<ElementNode>, elements: Node_1 | Node_1[], options?: Options<Node_1, ElementNode> | undefined) => ElementNode[];
/**
* @template Node The generic Node type for the DOM adapter being used.
* @template ElementNode The Node type for elements for the DOM adapter being used.
* @param elems Elements to query. If it is an element, its children will be queried..
* @param query can be either a CSS selector string or a compiled query function.
* @param [options] options for querying the document.
* @see compile for supported selector queries.
* @returns the first match, or null if there was no match.
*/
export declare const selectOne: <Node_1, ElementNode extends Node_1>(query: Query<ElementNode>, elements: Node_1 | Node_1[], options?: Options<Node_1, ElementNode> | undefined) => ElementNode | null;
/**
* Tests whether or not an element is matched by query.
*
* @template Node The generic Node type for the DOM adapter being used.
* @template ElementNode The Node type for elements for the DOM adapter being used.
* @param elem The element to test if it matches the query.
* @param query can be either a CSS selector string or a compiled query function.
* @param [options] options for querying the document.
* @see compile for supported selector queries.
* @returns
*/
export declare function is<Node, ElementNode extends Node>(elem: ElementNode, query: Query<ElementNode>, options?: Options<Node, ElementNode>): boolean;
/**
* Alias for selectAll(query, elems, options).
* @see [compile] for supported selector queries.
*/
export default selectAll;
export { filters, pseudos, aliases } from "./pseudo-selectors";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACR,aAAa,EACb,OAAO,EAEP,KAAK,EACL,OAAO,EAEV,MAAM,SAAS,CAAC;AAGjB,YAAY,EAAE,OAAO,EAAE,CAAC;AA0CxB;;GAEG;AACH,eAAO,MAAM,OAAO,gNAA0B,CAAC;AAC/C,eAAO,MAAM,cAAc,qNAA6B,CAAC;AACzD,eAAO,MAAM,aAAa,mNAA4B,CAAC;AA6BvD,wBAAgB,cAAc,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EACzD,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,EACpB,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,EACnC,sBAAsB,UAAQ,GAC/B,IAAI,EAAE,CAYR;AAiBD;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS,mKASrB,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,SAAS,wKASrB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,EAAE,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAC7C,IAAI,EAAE,WAAW,EACjB,KAAK,EAAE,KAAK,CAAC,WAAW,CAAC,EACzB,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,GACrC,OAAO,CAKT;AAED;;;GAGG;AACH,eAAe,SAAS,CAAC;AAGzB,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC"}

149
node_modules/svgo/node_modules/css-select/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,149 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.aliases = exports.pseudos = exports.filters = exports.is = exports.selectOne = exports.selectAll = exports.prepareContext = exports._compileToken = exports._compileUnsafe = exports.compile = void 0;
var DomUtils = __importStar(require("domutils"));
var boolbase_1 = require("boolbase");
var compile_1 = require("./compile");
var subselects_1 = require("./pseudo-selectors/subselects");
var defaultEquals = function (a, b) { return a === b; };
var defaultOptions = {
adapter: DomUtils,
equals: defaultEquals,
};
function convertOptionFormats(options) {
var _a, _b, _c, _d;
/*
* We force one format of options to the other one.
*/
// @ts-expect-error Default options may have incompatible `Node` / `ElementNode`.
var opts = options !== null && options !== void 0 ? options : defaultOptions;
// @ts-expect-error Same as above.
(_a = opts.adapter) !== null && _a !== void 0 ? _a : (opts.adapter = DomUtils);
// @ts-expect-error `equals` does not exist on `Options`
(_b = opts.equals) !== null && _b !== void 0 ? _b : (opts.equals = (_d = (_c = opts.adapter) === null || _c === void 0 ? void 0 : _c.equals) !== null && _d !== void 0 ? _d : defaultEquals);
return opts;
}
function wrapCompile(func) {
return function addAdapter(selector, options, context) {
var opts = convertOptionFormats(options);
return func(selector, opts, context);
};
}
/**
* Compiles the query, returns a function.
*/
exports.compile = wrapCompile(compile_1.compile);
exports._compileUnsafe = wrapCompile(compile_1.compileUnsafe);
exports._compileToken = wrapCompile(compile_1.compileToken);
function getSelectorFunc(searchFunc) {
return function select(query, elements, options) {
var opts = convertOptionFormats(options);
if (typeof query !== "function") {
query = (0, compile_1.compileUnsafe)(query, opts, elements);
}
var filteredElements = prepareContext(elements, opts.adapter, query.shouldTestNextSiblings);
return searchFunc(query, filteredElements, opts);
};
}
function prepareContext(elems, adapter, shouldTestNextSiblings) {
if (shouldTestNextSiblings === void 0) { shouldTestNextSiblings = false; }
/*
* Add siblings if the query requires them.
* See https://github.com/fb55/css-select/pull/43#issuecomment-225414692
*/
if (shouldTestNextSiblings) {
elems = appendNextSiblings(elems, adapter);
}
return Array.isArray(elems)
? adapter.removeSubsets(elems)
: adapter.getChildren(elems);
}
exports.prepareContext = prepareContext;
function appendNextSiblings(elem, adapter) {
// Order matters because jQuery seems to check the children before the siblings
var elems = Array.isArray(elem) ? elem.slice(0) : [elem];
var elemsLength = elems.length;
for (var i = 0; i < elemsLength; i++) {
var nextSiblings = (0, subselects_1.getNextSiblings)(elems[i], adapter);
elems.push.apply(elems, nextSiblings);
}
return elems;
}
/**
* @template Node The generic Node type for the DOM adapter being used.
* @template ElementNode The Node type for elements for the DOM adapter being used.
* @param elems Elements to query. If it is an element, its children will be queried..
* @param query can be either a CSS selector string or a compiled query function.
* @param [options] options for querying the document.
* @see compile for supported selector queries.
* @returns All matching elements.
*
*/
exports.selectAll = getSelectorFunc(function (query, elems, options) {
return query === boolbase_1.falseFunc || !elems || elems.length === 0
? []
: options.adapter.findAll(query, elems);
});
/**
* @template Node The generic Node type for the DOM adapter being used.
* @template ElementNode The Node type for elements for the DOM adapter being used.
* @param elems Elements to query. If it is an element, its children will be queried..
* @param query can be either a CSS selector string or a compiled query function.
* @param [options] options for querying the document.
* @see compile for supported selector queries.
* @returns the first match, or null if there was no match.
*/
exports.selectOne = getSelectorFunc(function (query, elems, options) {
return query === boolbase_1.falseFunc || !elems || elems.length === 0
? null
: options.adapter.findOne(query, elems);
});
/**
* Tests whether or not an element is matched by query.
*
* @template Node The generic Node type for the DOM adapter being used.
* @template ElementNode The Node type for elements for the DOM adapter being used.
* @param elem The element to test if it matches the query.
* @param query can be either a CSS selector string or a compiled query function.
* @param [options] options for querying the document.
* @see compile for supported selector queries.
* @returns
*/
function is(elem, query, options) {
var opts = convertOptionFormats(options);
return (typeof query === "function" ? query : (0, compile_1.compile)(query, opts))(elem);
}
exports.is = is;
/**
* Alias for selectAll(query, elems, options).
* @see [compile] for supported selector queries.
*/
exports.default = exports.selectAll;
// Export filters, pseudos and aliases to allow users to supply their own.
var pseudo_selectors_1 = require("./pseudo-selectors");
Object.defineProperty(exports, "filters", { enumerable: true, get: function () { return pseudo_selectors_1.filters; } });
Object.defineProperty(exports, "pseudos", { enumerable: true, get: function () { return pseudo_selectors_1.pseudos; } });
Object.defineProperty(exports, "aliases", { enumerable: true, get: function () { return pseudo_selectors_1.aliases; } });

View File

@@ -0,0 +1,5 @@
import type { Traversal } from "css-what";
import type { InternalSelector } from "./types";
export declare const procedure: Record<InternalSelector["type"], number>;
export declare function isTraversal(t: InternalSelector): t is Traversal;
//# sourceMappingURL=procedure.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"procedure.d.ts","sourceRoot":"","sources":["../src/procedure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEhD,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,gBAAgB,CAAC,MAAM,CAAC,EAAE,MAAM,CAa9D,CAAC;AAEF,wBAAgB,WAAW,CAAC,CAAC,EAAE,gBAAgB,GAAG,CAAC,IAAI,SAAS,CAE/D"}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTraversal = exports.procedure = void 0;
exports.procedure = {
universal: 50,
tag: 30,
attribute: 1,
pseudo: 0,
"pseudo-element": 0,
"column-combinator": -1,
descendant: -1,
child: -1,
parent: -1,
sibling: -1,
adjacent: -1,
_flexibleDescendant: -1,
};
function isTraversal(t) {
return exports.procedure[t.type] < 0;
}
exports.isTraversal = isTraversal;

View File

@@ -0,0 +1,5 @@
/**
* Aliases are pseudos that are expressed as selectors.
*/
export declare const aliases: Record<string, string>;
//# sourceMappingURL=aliases.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"aliases.d.ts","sourceRoot":"","sources":["../../src/pseudo-selectors/aliases.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAwC1C,CAAC"}

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.aliases = void 0;
/**
* Aliases are pseudos that are expressed as selectors.
*/
exports.aliases = {
// Links
"any-link": ":is(a, area, link)[href]",
link: ":any-link:not(:visited)",
// Forms
// https://html.spec.whatwg.org/multipage/scripting.html#disabled-elements
disabled: ":is(\n :is(button, input, select, textarea, optgroup, option)[disabled],\n optgroup[disabled] > option,\n fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)\n )",
enabled: ":not(:disabled)",
checked: ":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",
required: ":is(input, select, textarea)[required]",
optional: ":is(input, select, textarea):not([required])",
// JQuery extensions
// https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-selectedness
selected: "option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",
checkbox: "[type=checkbox]",
file: "[type=file]",
password: "[type=password]",
radio: "[type=radio]",
reset: "[type=reset]",
image: "[type=image]",
submit: "[type=submit]",
parent: ":not(:empty)",
header: ":is(h1, h2, h3, h4, h5, h6)",
button: ":is(button, input[type=button])",
input: ":is(input, textarea, select, button)",
text: "input:is(:not([type!='']), [type=text])",
};

View File

@@ -0,0 +1,4 @@
import type { CompiledQuery, InternalOptions } from "../types";
export declare type Filter = <Node, ElementNode extends Node>(next: CompiledQuery<ElementNode>, text: string, options: InternalOptions<Node, ElementNode>, context?: Node[]) => CompiledQuery<ElementNode>;
export declare const filters: Record<string, Filter>;
//# sourceMappingURL=filters.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"filters.d.ts","sourceRoot":"","sources":["../../src/pseudo-selectors/filters.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAW,MAAM,UAAU,CAAC;AAExE,oBAAY,MAAM,GAAG,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAChD,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,EAChC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,CAAC,EAAE,IAAI,EAAE,KACf,aAAa,CAAC,WAAW,CAAC,CAAC;AAYhC,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA2I1C,CAAC"}

View File

@@ -0,0 +1,156 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.filters = void 0;
var nth_check_1 = __importDefault(require("nth-check"));
var boolbase_1 = require("boolbase");
function getChildFunc(next, adapter) {
return function (elem) {
var parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(elem);
};
}
exports.filters = {
contains: function (next, text, _a) {
var adapter = _a.adapter;
return function contains(elem) {
return next(elem) && adapter.getText(elem).includes(text);
};
},
icontains: function (next, text, _a) {
var adapter = _a.adapter;
var itext = text.toLowerCase();
return function icontains(elem) {
return (next(elem) &&
adapter.getText(elem).toLowerCase().includes(itext));
};
},
// Location specific methods
"nth-child": function (next, rule, _a) {
var adapter = _a.adapter, equals = _a.equals;
var func = (0, nth_check_1.default)(rule);
if (func === boolbase_1.falseFunc)
return boolbase_1.falseFunc;
if (func === boolbase_1.trueFunc)
return getChildFunc(next, adapter);
return function nthChild(elem) {
var siblings = adapter.getSiblings(elem);
var pos = 0;
for (var i = 0; i < siblings.length; i++) {
if (equals(elem, siblings[i]))
break;
if (adapter.isTag(siblings[i])) {
pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-last-child": function (next, rule, _a) {
var adapter = _a.adapter, equals = _a.equals;
var func = (0, nth_check_1.default)(rule);
if (func === boolbase_1.falseFunc)
return boolbase_1.falseFunc;
if (func === boolbase_1.trueFunc)
return getChildFunc(next, adapter);
return function nthLastChild(elem) {
var siblings = adapter.getSiblings(elem);
var pos = 0;
for (var i = siblings.length - 1; i >= 0; i--) {
if (equals(elem, siblings[i]))
break;
if (adapter.isTag(siblings[i])) {
pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-of-type": function (next, rule, _a) {
var adapter = _a.adapter, equals = _a.equals;
var func = (0, nth_check_1.default)(rule);
if (func === boolbase_1.falseFunc)
return boolbase_1.falseFunc;
if (func === boolbase_1.trueFunc)
return getChildFunc(next, adapter);
return function nthOfType(elem) {
var siblings = adapter.getSiblings(elem);
var pos = 0;
for (var i = 0; i < siblings.length; i++) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === adapter.getName(elem)) {
pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-last-of-type": function (next, rule, _a) {
var adapter = _a.adapter, equals = _a.equals;
var func = (0, nth_check_1.default)(rule);
if (func === boolbase_1.falseFunc)
return boolbase_1.falseFunc;
if (func === boolbase_1.trueFunc)
return getChildFunc(next, adapter);
return function nthLastOfType(elem) {
var siblings = adapter.getSiblings(elem);
var pos = 0;
for (var i = siblings.length - 1; i >= 0; i--) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === adapter.getName(elem)) {
pos++;
}
}
return func(pos) && next(elem);
};
},
// TODO determine the actual root element
root: function (next, _rule, _a) {
var adapter = _a.adapter;
return function (elem) {
var parent = adapter.getParent(elem);
return (parent == null || !adapter.isTag(parent)) && next(elem);
};
},
scope: function (next, rule, options, context) {
var equals = options.equals;
if (!context || context.length === 0) {
// Equivalent to :root
return exports.filters.root(next, rule, options);
}
if (context.length === 1) {
// NOTE: can't be unpacked, as :has uses this for side-effects
return function (elem) { return equals(context[0], elem) && next(elem); };
}
return function (elem) { return context.includes(elem) && next(elem); };
},
hover: dynamicStatePseudo("isHovered"),
visited: dynamicStatePseudo("isVisited"),
active: dynamicStatePseudo("isActive"),
};
/**
* Dynamic state pseudos. These depend on optional Adapter methods.
*
* @param name The name of the adapter method to call.
* @returns Pseudo for the `filters` object.
*/
function dynamicStatePseudo(name) {
return function dynamicPseudo(next, _rule, _a) {
var adapter = _a.adapter;
var func = adapter[name];
if (typeof func !== "function") {
return boolbase_1.falseFunc;
}
return function active(elem) {
return func(elem) && next(elem);
};
};
}

View File

@@ -0,0 +1,8 @@
import type { CompiledQuery, InternalOptions, CompileToken } from "../types";
import { PseudoSelector } from "css-what";
import { filters } from "./filters";
import { pseudos } from "./pseudos";
import { aliases } from "./aliases";
export { filters, pseudos, aliases };
export declare function compilePseudoSelector<Node, ElementNode extends Node>(next: CompiledQuery<ElementNode>, selector: PseudoSelector, options: InternalOptions<Node, ElementNode>, context: Node[] | undefined, compileToken: CompileToken<Node, ElementNode>): CompiledQuery<ElementNode>;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pseudo-selectors/index.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAC7E,OAAO,EAAS,cAAc,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,OAAO,EAAoB,MAAM,WAAW,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAErC,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAChE,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,EAChC,QAAQ,EAAE,cAAc,EACxB,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS,EAC3B,YAAY,EAAE,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,GAC9C,aAAa,CAAC,WAAW,CAAC,CA6B5B"}

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compilePseudoSelector = exports.aliases = exports.pseudos = exports.filters = void 0;
/*
* Pseudo selectors
*
* Pseudo selectors are available in three forms:
*
* 1. Filters are called when the selector is compiled and return a function
* that has to return either false, or the results of `next()`.
* 2. Pseudos are called on execution. They have to return a boolean.
* 3. Subselects work like filters, but have an embedded selector that will be run separately.
*
* Filters are great if you want to do some pre-processing, or change the call order
* of `next()` and your code.
* Pseudos should be used to implement simple checks.
*/
var boolbase_1 = require("boolbase");
var css_what_1 = require("css-what");
var filters_1 = require("./filters");
Object.defineProperty(exports, "filters", { enumerable: true, get: function () { return filters_1.filters; } });
var pseudos_1 = require("./pseudos");
Object.defineProperty(exports, "pseudos", { enumerable: true, get: function () { return pseudos_1.pseudos; } });
var aliases_1 = require("./aliases");
Object.defineProperty(exports, "aliases", { enumerable: true, get: function () { return aliases_1.aliases; } });
var subselects_1 = require("./subselects");
function compilePseudoSelector(next, selector, options, context, compileToken) {
var name = selector.name, data = selector.data;
if (Array.isArray(data)) {
return subselects_1.subselects[name](next, data, options, context, compileToken);
}
if (name in aliases_1.aliases) {
if (data != null) {
throw new Error("Pseudo ".concat(name, " doesn't have any arguments"));
}
// The alias has to be parsed here, to make sure options are respected.
var alias = (0, css_what_1.parse)(aliases_1.aliases[name]);
return subselects_1.subselects.is(next, alias, options, context, compileToken);
}
if (name in filters_1.filters) {
return filters_1.filters[name](next, data, options, context);
}
if (name in pseudos_1.pseudos) {
var pseudo_1 = pseudos_1.pseudos[name];
(0, pseudos_1.verifyPseudoArgs)(pseudo_1, name, data);
return pseudo_1 === boolbase_1.falseFunc
? boolbase_1.falseFunc
: next === boolbase_1.trueFunc
? function (elem) { return pseudo_1(elem, options, data); }
: function (elem) { return pseudo_1(elem, options, data) && next(elem); };
}
throw new Error("unmatched pseudo-class :".concat(name));
}
exports.compilePseudoSelector = compilePseudoSelector;

View File

@@ -0,0 +1,6 @@
import { PseudoSelector } from "css-what";
import type { InternalOptions } from "../types";
export declare type Pseudo = <Node, ElementNode extends Node>(elem: ElementNode, options: InternalOptions<Node, ElementNode>, subselect?: ElementNode | string | null) => boolean;
export declare const pseudos: Record<string, Pseudo>;
export declare function verifyPseudoArgs(func: Pseudo, name: string, subselect: PseudoSelector["data"]): void;
//# sourceMappingURL=pseudos.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pseudos.d.ts","sourceRoot":"","sources":["../../src/pseudo-selectors/pseudos.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD,oBAAY,MAAM,GAAG,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAChD,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,SAAS,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,IAAI,KACtC,OAAO,CAAC;AAGb,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CA8E1C,CAAC;AAEF,wBAAgB,gBAAgB,CAC5B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,cAAc,CAAC,MAAM,CAAC,GAClC,IAAI,CAQN"}

View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyPseudoArgs = exports.pseudos = void 0;
// While filters are precompiled, pseudos get called when they are needed
exports.pseudos = {
empty: function (elem, _a) {
var adapter = _a.adapter;
return !adapter.getChildren(elem).some(function (elem) {
// FIXME: `getText` call is potentially expensive.
return adapter.isTag(elem) || adapter.getText(elem) !== "";
});
},
"first-child": function (elem, _a) {
var adapter = _a.adapter, equals = _a.equals;
var firstChild = adapter
.getSiblings(elem)
.find(function (elem) { return adapter.isTag(elem); });
return firstChild != null && equals(elem, firstChild);
},
"last-child": function (elem, _a) {
var adapter = _a.adapter, equals = _a.equals;
var siblings = adapter.getSiblings(elem);
for (var i = siblings.length - 1; i >= 0; i--) {
if (equals(elem, siblings[i]))
return true;
if (adapter.isTag(siblings[i]))
break;
}
return false;
},
"first-of-type": function (elem, _a) {
var adapter = _a.adapter, equals = _a.equals;
var siblings = adapter.getSiblings(elem);
var elemName = adapter.getName(elem);
for (var i = 0; i < siblings.length; i++) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
return true;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === elemName) {
break;
}
}
return false;
},
"last-of-type": function (elem, _a) {
var adapter = _a.adapter, equals = _a.equals;
var siblings = adapter.getSiblings(elem);
var elemName = adapter.getName(elem);
for (var i = siblings.length - 1; i >= 0; i--) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
return true;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === elemName) {
break;
}
}
return false;
},
"only-of-type": function (elem, _a) {
var adapter = _a.adapter, equals = _a.equals;
var elemName = adapter.getName(elem);
return adapter
.getSiblings(elem)
.every(function (sibling) {
return equals(elem, sibling) ||
!adapter.isTag(sibling) ||
adapter.getName(sibling) !== elemName;
});
},
"only-child": function (elem, _a) {
var adapter = _a.adapter, equals = _a.equals;
return adapter
.getSiblings(elem)
.every(function (sibling) { return equals(elem, sibling) || !adapter.isTag(sibling); });
},
};
function verifyPseudoArgs(func, name, subselect) {
if (subselect === null) {
if (func.length > 2) {
throw new Error("pseudo-selector :".concat(name, " requires an argument"));
}
}
else if (func.length === 2) {
throw new Error("pseudo-selector :".concat(name, " doesn't have any arguments"));
}
}
exports.verifyPseudoArgs = verifyPseudoArgs;

View File

@@ -0,0 +1,10 @@
import { CompileToken } from "./../types";
import type { Selector } from "css-what";
import type { CompiledQuery, InternalOptions, Adapter } from "../types";
/** Used as a placeholder for :has. Will be replaced with the actual element. */
export declare const PLACEHOLDER_ELEMENT: {};
export declare function ensureIsTag<Node, ElementNode extends Node>(next: CompiledQuery<ElementNode>, adapter: Adapter<Node, ElementNode>): CompiledQuery<Node>;
export declare type Subselect = <Node, ElementNode extends Node>(next: CompiledQuery<ElementNode>, subselect: Selector[][], options: InternalOptions<Node, ElementNode>, context: Node[] | undefined, compileToken: CompileToken<Node, ElementNode>) => CompiledQuery<ElementNode>;
export declare function getNextSiblings<Node, ElementNode extends Node>(elem: Node, adapter: Adapter<Node, ElementNode>): ElementNode[];
export declare const subselects: Record<string, Subselect>;
//# sourceMappingURL=subselects.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"subselects.d.ts","sourceRoot":"","sources":["../../src/pseudo-selectors/subselects.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAGxE,gFAAgF;AAChF,eAAO,MAAM,mBAAmB,IAAK,CAAC;AAEtC,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EACtD,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,EAChC,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,GACpC,aAAa,CAAC,IAAI,CAAC,CAGrB;AAED,oBAAY,SAAS,GAAG,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EACnD,IAAI,EAAE,aAAa,CAAC,WAAW,CAAC,EAChC,SAAS,EAAE,QAAQ,EAAE,EAAE,EACvB,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS,EAC3B,YAAY,EAAE,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,KAC5C,aAAa,CAAC,WAAW,CAAC,CAAC;AAEhC,wBAAgB,eAAe,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,EAC1D,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,GACpC,WAAW,EAAE,CAMf;AAkBD,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CA6EhD,CAAC"}

View File

@@ -0,0 +1,110 @@
"use strict";
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.subselects = exports.getNextSiblings = exports.ensureIsTag = exports.PLACEHOLDER_ELEMENT = void 0;
var boolbase_1 = require("boolbase");
var procedure_1 = require("../procedure");
/** Used as a placeholder for :has. Will be replaced with the actual element. */
exports.PLACEHOLDER_ELEMENT = {};
function ensureIsTag(next, adapter) {
if (next === boolbase_1.falseFunc)
return boolbase_1.falseFunc;
return function (elem) { return adapter.isTag(elem) && next(elem); };
}
exports.ensureIsTag = ensureIsTag;
function getNextSiblings(elem, adapter) {
var siblings = adapter.getSiblings(elem);
if (siblings.length <= 1)
return [];
var elemIndex = siblings.indexOf(elem);
if (elemIndex < 0 || elemIndex === siblings.length - 1)
return [];
return siblings.slice(elemIndex + 1).filter(adapter.isTag);
}
exports.getNextSiblings = getNextSiblings;
var is = function (next, token, options, context, compileToken) {
var opts = {
xmlMode: !!options.xmlMode,
adapter: options.adapter,
equals: options.equals,
};
var func = compileToken(token, opts, context);
return function (elem) { return func(elem) && next(elem); };
};
/*
* :not, :has, :is, :matches and :where have to compile selectors
* doing this in src/pseudos.ts would lead to circular dependencies,
* so we add them here
*/
exports.subselects = {
is: is,
/**
* `:matches` and `:where` are aliases for `:is`.
*/
matches: is,
where: is,
not: function (next, token, options, context, compileToken) {
var opts = {
xmlMode: !!options.xmlMode,
adapter: options.adapter,
equals: options.equals,
};
var func = compileToken(token, opts, context);
if (func === boolbase_1.falseFunc)
return next;
if (func === boolbase_1.trueFunc)
return boolbase_1.falseFunc;
return function not(elem) {
return !func(elem) && next(elem);
};
},
has: function (next, subselect, options, _context, compileToken) {
var adapter = options.adapter;
var opts = {
xmlMode: !!options.xmlMode,
adapter: adapter,
equals: options.equals,
};
// @ts-expect-error Uses an array as a pointer to the current element (side effects)
var context = subselect.some(function (s) {
return s.some(procedure_1.isTraversal);
})
? [exports.PLACEHOLDER_ELEMENT]
: undefined;
var compiled = compileToken(subselect, opts, context);
if (compiled === boolbase_1.falseFunc)
return boolbase_1.falseFunc;
if (compiled === boolbase_1.trueFunc) {
return function (elem) {
return adapter.getChildren(elem).some(adapter.isTag) && next(elem);
};
}
var hasElement = ensureIsTag(compiled, adapter);
var _a = compiled.shouldTestNextSiblings, shouldTestNextSiblings = _a === void 0 ? false : _a;
/*
* `shouldTestNextSiblings` will only be true if the query starts with
* a traversal (sibling or adjacent). That means we will always have a context.
*/
if (context) {
return function (elem) {
context[0] = elem;
var childs = adapter.getChildren(elem);
var nextElements = shouldTestNextSiblings
? __spreadArray(__spreadArray([], childs, true), getNextSiblings(elem, adapter), true) : childs;
return (next(elem) && adapter.existsOne(hasElement, nextElements));
};
}
return function (elem) {
return next(elem) &&
adapter.existsOne(hasElement, adapter.getChildren(elem));
};
},
};

View File

@@ -0,0 +1,10 @@
import type { InternalSelector } from "./types";
/**
* Sort the parts of the passed selector,
* as there is potential for optimization
* (some types of selectors are faster than others)
*
* @param arr Selector to sort
*/
export default function sortByProcedure(arr: InternalSelector[]): void;
//# sourceMappingURL=sort.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAehD;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,GAAG,EAAE,gBAAgB,EAAE,GAAG,IAAI,CAerE"}

85
node_modules/svgo/node_modules/css-select/lib/sort.js generated vendored Normal file
View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var css_what_1 = require("css-what");
var procedure_1 = require("./procedure");
var attributes = {
exists: 10,
equals: 8,
not: 7,
start: 6,
end: 6,
any: 5,
hyphen: 4,
element: 4,
};
/**
* Sort the parts of the passed selector,
* as there is potential for optimization
* (some types of selectors are faster than others)
*
* @param arr Selector to sort
*/
function sortByProcedure(arr) {
var procs = arr.map(getProcedure);
for (var i = 1; i < arr.length; i++) {
var procNew = procs[i];
if (procNew < 0)
continue;
for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {
var token = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = token;
procs[j + 1] = procs[j];
procs[j] = procNew;
}
}
}
exports.default = sortByProcedure;
function getProcedure(token) {
var proc = procedure_1.procedure[token.type];
if (token.type === css_what_1.SelectorType.Attribute) {
proc = attributes[token.action];
if (proc === attributes.equals && token.name === "id") {
// Prefer ID selectors (eg. #ID)
proc = 9;
}
if (token.ignoreCase) {
/*
* IgnoreCase adds some overhead, prefer "normal" token
* this is a binary operation, to ensure it's still an int
*/
proc >>= 1;
}
}
else if (token.type === css_what_1.SelectorType.Pseudo) {
if (!token.data) {
proc = 3;
}
else if (token.name === "has" || token.name === "contains") {
proc = 0; // Expensive in any case
}
else if (Array.isArray(token.data)) {
// "matches" and "not"
proc = 0;
for (var i = 0; i < token.data.length; i++) {
// TODO better handling of complex selectors
if (token.data[i].length !== 1)
continue;
var cur = getProcedure(token.data[i][0]);
// Avoid executing :has or :contains
if (cur === 0) {
proc = 0;
break;
}
if (cur > proc)
proc = cur;
}
if (token.data.length > 1 && proc > 0)
proc -= 1;
}
else {
proc = 1;
}
}
return proc;
}

View File

@@ -0,0 +1,144 @@
import type { Selector } from "css-what";
export declare type InternalSelector = Selector | {
type: "_flexibleDescendant";
};
export declare type Predicate<Value> = (v: Value) => boolean;
export interface Adapter<Node, ElementNode extends Node> {
/**
* Is the node a tag?
*/
isTag: (node: Node) => node is ElementNode;
/**
* Does at least one of passed element nodes pass the test predicate?
*/
existsOne: (test: Predicate<ElementNode>, elems: Node[]) => boolean;
/**
* Get the attribute value.
*/
getAttributeValue: (elem: ElementNode, name: string) => string | undefined;
/**
* Get the node's children
*/
getChildren: (node: Node) => Node[];
/**
* Get the name of the tag
*/
getName: (elem: ElementNode) => string;
/**
* Get the parent of the node
*/
getParent: (node: ElementNode) => ElementNode | null;
/**
* Get the siblings of the node. Note that unlike jQuery's `siblings` method,
* this is expected to include the current node as well
*/
getSiblings: (node: Node) => Node[];
/**
* Returns the previous element sibling of a node.
*/
prevElementSibling?: (node: Node) => ElementNode | null;
/**
* Get the text content of the node, and its children if it has any.
*/
getText: (node: Node) => string;
/**
* Does the element have the named attribute?
*/
hasAttrib: (elem: ElementNode, name: string) => boolean;
/**
* Takes an array of nodes, and removes any duplicates, as well as any
* nodes whose ancestors are also in the array.
*/
removeSubsets: (nodes: Node[]) => Node[];
/**
* Finds all of the element nodes in the array that match the test predicate,
* as well as any of their children that match it.
*/
findAll: (test: Predicate<ElementNode>, nodes: Node[]) => ElementNode[];
/**
* Finds the first node in the array that matches the test predicate, or one
* of its children.
*/
findOne: (test: Predicate<ElementNode>, elems: Node[]) => ElementNode | null;
/**
* The adapter can also optionally include an equals method, if your DOM
* structure needs a custom equality test to compare two objects which refer
* to the same underlying node. If not provided, `css-select` will fall back to
* `a === b`.
*/
equals?: (a: Node, b: Node) => boolean;
/**
* Is the element in hovered state?
*/
isHovered?: (elem: ElementNode) => boolean;
/**
* Is the element in visited state?
*/
isVisited?: (elem: ElementNode) => boolean;
/**
* Is the element in active state?
*/
isActive?: (elem: ElementNode) => boolean;
}
export interface Options<Node, ElementNode extends Node> {
/**
* When enabled, tag names will be case-sensitive.
*
* @default false
*/
xmlMode?: boolean;
/**
* Lower-case attribute names.
*
* @default !xmlMode
*/
lowerCaseAttributeNames?: boolean;
/**
* Lower-case tag names.
*
* @default !xmlMode
*/
lowerCaseTags?: boolean;
/**
* Is the document in quirks mode?
*
* This will lead to .className and #id being case-insensitive.
*
* @default false
*/
quirksMode?: boolean;
/**
* The last function in the stack, will be called with the last element
* that's looked at.
*/
rootFunc?: (element: ElementNode) => boolean;
/**
* The adapter to use when interacting with the backing DOM structure. By
* default it uses the `domutils` module.
*/
adapter?: Adapter<Node, ElementNode>;
/**
* The context of the current query. Used to limit the scope of searches.
* Can be matched directly using the `:scope` pseudo-selector.
*/
context?: Node | Node[];
/**
* Allow css-select to cache results for some selectors, sometimes greatly
* improving querying performance. Disable this if your document can
* change in between queries with the same compiled selector.
*
* @default true
*/
cacheResults?: boolean;
}
export interface InternalOptions<Node, ElementNode extends Node> extends Options<Node, ElementNode> {
adapter: Adapter<Node, ElementNode>;
equals: (a: Node, b: Node) => boolean;
}
export interface CompiledQuery<ElementNode> {
(node: ElementNode): boolean;
shouldTestNextSiblings?: boolean;
}
export declare type Query<ElementNode> = string | CompiledQuery<ElementNode> | Selector[][];
export declare type CompileToken<Node, ElementNode extends Node> = (token: InternalSelector[][], options: InternalOptions<Node, ElementNode>, context?: Node[] | Node) => CompiledQuery<ElementNode>;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,oBAAY,gBAAgB,GAAG,QAAQ,GAAG;IAAE,IAAI,EAAE,qBAAqB,CAAA;CAAE,CAAC;AAE1E,oBAAY,SAAS,CAAC,KAAK,IAAI,CAAC,CAAC,EAAE,KAAK,KAAK,OAAO,CAAC;AACrD,MAAM,WAAW,OAAO,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI;IACnD;;OAEG;IACH,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,IAAI,WAAW,CAAC;IAE3C;;OAEG;IACH,SAAS,EAAE,CAAC,IAAI,EAAE,SAAS,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,OAAO,CAAC;IAEpE;;OAEG;IACH,iBAAiB,EAAE,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAE3E;;OAEG;IACH,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,EAAE,CAAC;IAEpC;;OAEG;IACH,OAAO,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,MAAM,CAAC;IAEvC;;OAEG;IACH,SAAS,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,WAAW,GAAG,IAAI,CAAC;IAErD;;;OAGG;IACH,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,EAAE,CAAC;IAEpC;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,WAAW,GAAG,IAAI,CAAC;IAExD;;OAEG;IACH,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,MAAM,CAAC;IAEhC;;OAEG;IACH,SAAS,EAAE,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IAExD;;;OAGG;IACH,aAAa,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;IAEzC;;;OAGG;IACH,OAAO,EAAE,CAAC,IAAI,EAAE,SAAS,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,WAAW,EAAE,CAAC;IAExE;;;OAGG;IACH,OAAO,EAAE,CACL,IAAI,EAAE,SAAS,CAAC,WAAW,CAAC,EAC5B,KAAK,EAAE,IAAI,EAAE,KACZ,WAAW,GAAG,IAAI,CAAC;IAExB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,KAAK,OAAO,CAAC;IAEvC;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC;IAE3C;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC;IAE3C;;OAEG;IACH,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC;CAC7C;AAED,MAAM,WAAW,OAAO,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI;IACnD;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC;;;;OAIG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC;IAC7C;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IACrC;;;OAGG;IACH,OAAO,CAAC,EAAE,IAAI,GAAG,IAAI,EAAE,CAAC;IACxB;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CAC1B;AAGD,MAAM,WAAW,eAAe,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,CAC3D,SAAQ,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC;IAClC,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IACpC,MAAM,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,KAAK,OAAO,CAAC;CACzC;AAED,MAAM,WAAW,aAAa,CAAC,WAAW;IACtC,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC;IAC7B,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC;AACD,oBAAY,KAAK,CAAC,WAAW,IACvB,MAAM,GACN,aAAa,CAAC,WAAW,CAAC,GAC1B,QAAQ,EAAE,EAAE,CAAC;AACnB,oBAAY,YAAY,CAAC,IAAI,EAAE,WAAW,SAAS,IAAI,IAAI,CACvD,KAAK,EAAE,gBAAgB,EAAE,EAAE,EAC3B,OAAO,EAAE,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAC3C,OAAO,CAAC,EAAE,IAAI,EAAE,GAAG,IAAI,KACtB,aAAa,CAAC,WAAW,CAAC,CAAC"}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

70
node_modules/svgo/node_modules/css-select/package.json generated vendored Normal file
View File

@@ -0,0 +1,70 @@
{
"name": "css-select",
"version": "4.3.0",
"description": "a CSS selector compiler/engine",
"author": "Felix Boehm <me@feedic.com>",
"funding": {
"url": "https://github.com/sponsors/fb55"
},
"keywords": [
"css",
"selector",
"sizzle"
],
"repository": {
"type": "git",
"url": "git://github.com/fb55/css-select.git"
},
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib"
],
"dependencies": {
"boolbase": "^1.0.0",
"css-what": "^6.0.1",
"domhandler": "^4.3.1",
"domutils": "^2.8.0",
"nth-check": "^2.0.1"
},
"devDependencies": {
"@types/boolbase": "^1.0.1",
"@types/jest": "^27.4.1",
"@types/node": "^17.0.23",
"@typescript-eslint/eslint-plugin": "^5.16.0",
"@typescript-eslint/parser": "^5.16.0",
"cheerio-soupselect": "^0.1.1",
"eslint": "^8.12.0",
"eslint-config-prettier": "^8.5.0",
"htmlparser2": "^7.2.0",
"jest": "^27.5.1",
"prettier": "^2.6.1",
"ts-jest": "^27.1.4",
"typescript": "^4.6.3"
},
"scripts": {
"test": "npm run test:jest && npm run lint",
"test:jest": "jest",
"lint": "npm run lint:es && npm run lint:prettier",
"lint:es": "eslint src",
"lint:prettier": "npm run prettier -- --check",
"format": "npm run format:es && npm run format:prettier",
"format:es": "npm run lint:es -- --fix",
"format:prettier": "npm run prettier -- --write",
"prettier": "prettier '**/*.{ts,md,json,yml}'",
"build": "tsc",
"prepare": "npm run build"
},
"license": "BSD-2-Clause",
"prettier": {
"tabWidth": 4,
"proseWrap": "always"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node",
"testMatch": [
"<rootDir>/test/*.ts"
]
}
}

11
node_modules/svgo/node_modules/dom-serializer/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,11 @@
License
(The MIT License)
Copyright (c) 2014 The cheeriojs contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,97 @@
# dom-serializer [![Build Status](https://travis-ci.com/cheeriojs/dom-serializer.svg?branch=master)](https://travis-ci.com/cheeriojs/dom-serializer)
Renders a [domhandler](https://github.com/fb55/domhandler) DOM node or an array of domhandler DOM nodes to a string.
```js
import render from "dom-serializer";
// OR
const render = require("dom-serializer").default;
```
# API
## `render`
**render**(`node`: Node \| Node[], `options?`: [_Options_](#Options)): _string_
Renders a DOM node or an array of DOM nodes to a string.
Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
#### Parameters:
| Name | Type | Default value | Description |
| :-------- | :--------------------------------- | :------------ | :----------------------------- |
| `node` | Node \| Node[] | - | Node to be rendered. |
| `options` | [_DomSerializerOptions_](#Options) | {} | Changes serialization behavior |
**Returns:** _string_
## Options
### `decodeEntities`
`Optional` **decodeEntities**: _boolean_
Encode characters that are either reserved in HTML or XML, or are outside of the ASCII range.
**`default`** true
---
### `emptyAttrs`
`Optional` **emptyAttrs**: _boolean_
Print an empty attribute's value.
**`default`** xmlMode
**`example`** With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code>
**`example`** With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code>
---
### `selfClosingTags`
`Optional` **selfClosingTags**: _boolean_
Print self-closing tags for tags without contents.
**`default`** xmlMode
**`example`** With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;</code>
**`example`** With <code>selfClosingTags: true</code>: <code>&lt;foo /&gt;</code>
---
### `xmlMode`
`Optional` **xmlMode**: _boolean_ \| _"foreign"_
Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
If the value is `"foreign"`, it will try to correct mixed-case attribute names.
**`default`** false
---
## Ecosystem
| Name | Description |
| ------------------------------------------------------------- | ------------------------------------------------------- |
| [htmlparser2](https://github.com/fb55/htmlparser2) | Fast & forgiving HTML/XML parser |
| [domhandler](https://github.com/fb55/domhandler) | Handler for htmlparser2 that turns documents into a DOM |
| [domutils](https://github.com/fb55/domutils) | Utilities for working with domhandler's DOM |
| [css-select](https://github.com/fb55/css-select) | CSS selector engine, compatible with domhandler's DOM |
| [cheerio](https://github.com/cheeriojs/cheerio) | The jQuery API for domhandler's DOM |
| [dom-serializer](https://github.com/cheeriojs/dom-serializer) | Serializer for domhandler's DOM |
---
LICENSE: MIT

View File

@@ -0,0 +1,3 @@
export declare const elementNames: Map<string, string>;
export declare const attributeNames: Map<string, string>;
//# sourceMappingURL=foreignNames.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"foreignNames.d.ts","sourceRoot":"","sources":["../../src/foreignNames.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,qBAwCxB,CAAC;AACF,eAAO,MAAM,cAAc,qBA8D1B,CAAC"}

View File

@@ -0,0 +1,100 @@
export const elementNames = new Map([
"altGlyph",
"altGlyphDef",
"altGlyphItem",
"animateColor",
"animateMotion",
"animateTransform",
"clipPath",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"foreignObject",
"glyphRef",
"linearGradient",
"radialGradient",
"textPath",
].map((val) => [val.toLowerCase(), val]));
export const attributeNames = new Map([
"definitionURL",
"attributeName",
"attributeType",
"baseFrequency",
"baseProfile",
"calcMode",
"clipPathUnits",
"diffuseConstant",
"edgeMode",
"filterUnits",
"glyphRef",
"gradientTransform",
"gradientUnits",
"kernelMatrix",
"kernelUnitLength",
"keyPoints",
"keySplines",
"keyTimes",
"lengthAdjust",
"limitingConeAngle",
"markerHeight",
"markerUnits",
"markerWidth",
"maskContentUnits",
"maskUnits",
"numOctaves",
"pathLength",
"patternContentUnits",
"patternTransform",
"patternUnits",
"pointsAtX",
"pointsAtY",
"pointsAtZ",
"preserveAlpha",
"preserveAspectRatio",
"primitiveUnits",
"refX",
"refY",
"repeatCount",
"repeatDur",
"requiredExtensions",
"requiredFeatures",
"specularConstant",
"specularExponent",
"spreadMethod",
"startOffset",
"stdDeviation",
"stitchTiles",
"surfaceScale",
"systemLanguage",
"tableValues",
"targetX",
"targetY",
"textLength",
"viewBox",
"viewTarget",
"xChannelSelector",
"yChannelSelector",
"zoomAndPan",
].map((val) => [val.toLowerCase(), val]));

View File

@@ -0,0 +1,52 @@
import type { AnyNode } from "domhandler";
export interface DomSerializerOptions {
/**
* Print an empty attribute's value.
*
* @default xmlMode
* @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code>
* @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code>
*/
emptyAttrs?: boolean;
/**
* Print self-closing tags for tags without contents.
*
* @default xmlMode
* @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;</code>
* @example With <code>selfClosingTags: true</code>: <code>&lt;foo /&gt;</code>
*/
selfClosingTags?: boolean;
/**
* Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
*
* If the value is `"foreign"`, it will try to correct mixed-case attribute names.
*
* @default false
*/
xmlMode?: boolean | "foreign";
/**
* Encode characters that are either reserved in HTML or XML.
*
* If `xmlMode` is `true` or the value not `'utf8'`, characters outside of the utf8 range will be encoded as well.
*
* @default `decodeEntities`
*/
encodeEntities?: boolean | "utf8";
/**
* Option inherited from parsing; will be used as the default value for `encodeEntities`.
*
* @default true
*/
decodeEntities?: boolean;
}
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
export declare function render(node: AnyNode | ArrayLike<AnyNode>, options?: DomSerializerOptions): string;
export default render;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,OAAO,EAMR,MAAM,YAAY,CAAC;AAWpB,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAClC;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AA4ED;;;;;;;GAOG;AACH,wBAAgB,MAAM,CACpB,IAAI,EAAE,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,EAClC,OAAO,GAAE,oBAAyB,GACjC,MAAM,CAUR;AAED,eAAe,MAAM,CAAC"}

View File

@@ -0,0 +1,190 @@
/*
* Module dependencies
*/
import * as ElementType from "domelementtype";
import { encodeXML, escapeAttribute, escapeText } from "entities";
/**
* Mixed-case SVG and MathML tags & attributes
* recognized by the HTML parser.
*
* @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
*/
import { elementNames, attributeNames } from "./foreignNames.js";
const unencodedElements = new Set([
"style",
"script",
"xmp",
"iframe",
"noembed",
"noframes",
"plaintext",
"noscript",
]);
function replaceQuotes(value) {
return value.replace(/"/g, "&quot;");
}
/**
* Format attributes
*/
function formatAttributes(attributes, opts) {
var _a;
if (!attributes)
return;
const encode = ((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) === false
? replaceQuotes
: opts.xmlMode || opts.encodeEntities !== "utf8"
? encodeXML
: escapeAttribute;
return Object.keys(attributes)
.map((key) => {
var _a, _b;
const value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : "";
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case attribute names */
key = (_b = attributeNames.get(key)) !== null && _b !== void 0 ? _b : key;
}
if (!opts.emptyAttrs && !opts.xmlMode && value === "") {
return key;
}
return `${key}="${encode(value)}"`;
})
.join(" ");
}
/**
* Self-enclosing tags
*/
const singleTag = new Set([
"area",
"base",
"basefont",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"isindex",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
export function render(node, options = {}) {
const nodes = "length" in node ? node : [node];
let output = "";
for (let i = 0; i < nodes.length; i++) {
output += renderNode(nodes[i], options);
}
return output;
}
export default render;
function renderNode(node, options) {
switch (node.type) {
case ElementType.Root:
return render(node.children, options);
// @ts-expect-error We don't use `Doctype` yet
case ElementType.Doctype:
case ElementType.Directive:
return renderDirective(node);
case ElementType.Comment:
return renderComment(node);
case ElementType.CDATA:
return renderCdata(node);
case ElementType.Script:
case ElementType.Style:
case ElementType.Tag:
return renderTag(node, options);
case ElementType.Text:
return renderText(node, options);
}
}
const foreignModeIntegrationPoints = new Set([
"mi",
"mo",
"mn",
"ms",
"mtext",
"annotation-xml",
"foreignObject",
"desc",
"title",
]);
const foreignElements = new Set(["svg", "math"]);
function renderTag(elem, opts) {
var _a;
// Handle SVG / MathML in HTML
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case element names */
elem.name = (_a = elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name;
/* Exit foreign mode at integration points */
if (elem.parent &&
foreignModeIntegrationPoints.has(elem.parent.name)) {
opts = { ...opts, xmlMode: false };
}
}
if (!opts.xmlMode && foreignElements.has(elem.name)) {
opts = { ...opts, xmlMode: "foreign" };
}
let tag = `<${elem.name}`;
const attribs = formatAttributes(elem.attribs, opts);
if (attribs) {
tag += ` ${attribs}`;
}
if (elem.children.length === 0 &&
(opts.xmlMode
? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags
opts.selfClosingTags !== false
: // User explicitly asked for self-closing tags, even in HTML mode
opts.selfClosingTags && singleTag.has(elem.name))) {
if (!opts.xmlMode)
tag += " ";
tag += "/>";
}
else {
tag += ">";
if (elem.children.length > 0) {
tag += render(elem.children, opts);
}
if (opts.xmlMode || !singleTag.has(elem.name)) {
tag += `</${elem.name}>`;
}
}
return tag;
}
function renderDirective(elem) {
return `<${elem.data}>`;
}
function renderText(elem, opts) {
var _a;
let data = elem.data || "";
// If entities weren't decoded, no need to encode them back
if (((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) !== false &&
!(!opts.xmlMode &&
elem.parent &&
unencodedElements.has(elem.parent.name))) {
data =
opts.xmlMode || opts.encodeEntities !== "utf8"
? encodeXML(data)
: escapeText(data);
}
return data;
}
function renderCdata(elem) {
return `<![CDATA[${elem.children[0].data}]]>`;
}
function renderComment(elem) {
return `<!--${elem.data}-->`;
}

View File

@@ -0,0 +1 @@
{"type":"module"}

View File

@@ -0,0 +1,3 @@
export declare const elementNames: Map<string, string>;
export declare const attributeNames: Map<string, string>;
//# sourceMappingURL=foreignNames.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"foreignNames.d.ts","sourceRoot":"","sources":["../src/foreignNames.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,qBAsCvB,CAAC;AACH,eAAO,MAAM,cAAc,qBA4DzB,CAAC"}

View File

@@ -0,0 +1,103 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.attributeNames = exports.elementNames = void 0;
exports.elementNames = new Map([
["altglyph", "altGlyph"],
["altglyphdef", "altGlyphDef"],
["altglyphitem", "altGlyphItem"],
["animatecolor", "animateColor"],
["animatemotion", "animateMotion"],
["animatetransform", "animateTransform"],
["clippath", "clipPath"],
["feblend", "feBlend"],
["fecolormatrix", "feColorMatrix"],
["fecomponenttransfer", "feComponentTransfer"],
["fecomposite", "feComposite"],
["feconvolvematrix", "feConvolveMatrix"],
["fediffuselighting", "feDiffuseLighting"],
["fedisplacementmap", "feDisplacementMap"],
["fedistantlight", "feDistantLight"],
["fedropshadow", "feDropShadow"],
["feflood", "feFlood"],
["fefunca", "feFuncA"],
["fefuncb", "feFuncB"],
["fefuncg", "feFuncG"],
["fefuncr", "feFuncR"],
["fegaussianblur", "feGaussianBlur"],
["feimage", "feImage"],
["femerge", "feMerge"],
["femergenode", "feMergeNode"],
["femorphology", "feMorphology"],
["feoffset", "feOffset"],
["fepointlight", "fePointLight"],
["fespecularlighting", "feSpecularLighting"],
["fespotlight", "feSpotLight"],
["fetile", "feTile"],
["feturbulence", "feTurbulence"],
["foreignobject", "foreignObject"],
["glyphref", "glyphRef"],
["lineargradient", "linearGradient"],
["radialgradient", "radialGradient"],
["textpath", "textPath"],
]);
exports.attributeNames = new Map([
["definitionurl", "definitionURL"],
["attributename", "attributeName"],
["attributetype", "attributeType"],
["basefrequency", "baseFrequency"],
["baseprofile", "baseProfile"],
["calcmode", "calcMode"],
["clippathunits", "clipPathUnits"],
["diffuseconstant", "diffuseConstant"],
["edgemode", "edgeMode"],
["filterunits", "filterUnits"],
["glyphref", "glyphRef"],
["gradienttransform", "gradientTransform"],
["gradientunits", "gradientUnits"],
["kernelmatrix", "kernelMatrix"],
["kernelunitlength", "kernelUnitLength"],
["keypoints", "keyPoints"],
["keysplines", "keySplines"],
["keytimes", "keyTimes"],
["lengthadjust", "lengthAdjust"],
["limitingconeangle", "limitingConeAngle"],
["markerheight", "markerHeight"],
["markerunits", "markerUnits"],
["markerwidth", "markerWidth"],
["maskcontentunits", "maskContentUnits"],
["maskunits", "maskUnits"],
["numoctaves", "numOctaves"],
["pathlength", "pathLength"],
["patterncontentunits", "patternContentUnits"],
["patterntransform", "patternTransform"],
["patternunits", "patternUnits"],
["pointsatx", "pointsAtX"],
["pointsaty", "pointsAtY"],
["pointsatz", "pointsAtZ"],
["preservealpha", "preserveAlpha"],
["preserveaspectratio", "preserveAspectRatio"],
["primitiveunits", "primitiveUnits"],
["refx", "refX"],
["refy", "refY"],
["repeatcount", "repeatCount"],
["repeatdur", "repeatDur"],
["requiredextensions", "requiredExtensions"],
["requiredfeatures", "requiredFeatures"],
["specularconstant", "specularConstant"],
["specularexponent", "specularExponent"],
["spreadmethod", "spreadMethod"],
["startoffset", "startOffset"],
["stddeviation", "stdDeviation"],
["stitchtiles", "stitchTiles"],
["surfacescale", "surfaceScale"],
["systemlanguage", "systemLanguage"],
["tablevalues", "tableValues"],
["targetx", "targetX"],
["targety", "targetY"],
["textlength", "textLength"],
["viewbox", "viewBox"],
["viewtarget", "viewTarget"],
["xchannelselector", "xChannelSelector"],
["ychannelselector", "yChannelSelector"],
["zoomandpan", "zoomAndPan"],
]);

View File

@@ -0,0 +1,43 @@
import type { Node } from "domhandler";
export interface DomSerializerOptions {
/**
* Print an empty attribute's value.
*
* @default xmlMode
* @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code>
* @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code>
*/
emptyAttrs?: boolean;
/**
* Print self-closing tags for tags without contents.
*
* @default xmlMode
* @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;</code>
* @example With <code>selfClosingTags: true</code>: <code>&lt;foo /&gt;</code>
*/
selfClosingTags?: boolean;
/**
* Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
*
* If the value is `"foreign"`, it will try to correct mixed-case attribute names.
*
* @default false
*/
xmlMode?: boolean | "foreign";
/**
* Encode characters that are either reserved in HTML or XML, or are outside of the ASCII range.
*
* @default true
*/
decodeEntities?: boolean;
}
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
export default function render(node: Node | ArrayLike<Node>, options?: DomSerializerOptions): string;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAuC,MAAM,YAAY,CAAC;AAW5E,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAqED;;;;;;;GAOG;AACH,MAAM,CAAC,OAAO,UAAU,MAAM,CAC5B,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,EAC5B,OAAO,GAAE,oBAAyB,GACjC,MAAM,CAUR"}

View File

@@ -0,0 +1,211 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Module dependencies
*/
var ElementType = __importStar(require("domelementtype"));
var entities_1 = require("entities");
/**
* Mixed-case SVG and MathML tags & attributes
* recognized by the HTML parser.
*
* @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
*/
var foreignNames_1 = require("./foreignNames");
var unencodedElements = new Set([
"style",
"script",
"xmp",
"iframe",
"noembed",
"noframes",
"plaintext",
"noscript",
]);
/**
* Format attributes
*/
function formatAttributes(attributes, opts) {
if (!attributes)
return;
return Object.keys(attributes)
.map(function (key) {
var _a, _b;
var value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : "";
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case attribute names */
key = (_b = foreignNames_1.attributeNames.get(key)) !== null && _b !== void 0 ? _b : key;
}
if (!opts.emptyAttrs && !opts.xmlMode && value === "") {
return key;
}
return key + "=\"" + (opts.decodeEntities !== false
? entities_1.encodeXML(value)
: value.replace(/"/g, "&quot;")) + "\"";
})
.join(" ");
}
/**
* Self-enclosing tags
*/
var singleTag = new Set([
"area",
"base",
"basefont",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"isindex",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
function render(node, options) {
if (options === void 0) { options = {}; }
var nodes = "length" in node ? node : [node];
var output = "";
for (var i = 0; i < nodes.length; i++) {
output += renderNode(nodes[i], options);
}
return output;
}
exports.default = render;
function renderNode(node, options) {
switch (node.type) {
case ElementType.Root:
return render(node.children, options);
case ElementType.Directive:
case ElementType.Doctype:
return renderDirective(node);
case ElementType.Comment:
return renderComment(node);
case ElementType.CDATA:
return renderCdata(node);
case ElementType.Script:
case ElementType.Style:
case ElementType.Tag:
return renderTag(node, options);
case ElementType.Text:
return renderText(node, options);
}
}
var foreignModeIntegrationPoints = new Set([
"mi",
"mo",
"mn",
"ms",
"mtext",
"annotation-xml",
"foreignObject",
"desc",
"title",
]);
var foreignElements = new Set(["svg", "math"]);
function renderTag(elem, opts) {
var _a;
// Handle SVG / MathML in HTML
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case element names */
elem.name = (_a = foreignNames_1.elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name;
/* Exit foreign mode at integration points */
if (elem.parent &&
foreignModeIntegrationPoints.has(elem.parent.name)) {
opts = __assign(__assign({}, opts), { xmlMode: false });
}
}
if (!opts.xmlMode && foreignElements.has(elem.name)) {
opts = __assign(__assign({}, opts), { xmlMode: "foreign" });
}
var tag = "<" + elem.name;
var attribs = formatAttributes(elem.attribs, opts);
if (attribs) {
tag += " " + attribs;
}
if (elem.children.length === 0 &&
(opts.xmlMode
? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags
opts.selfClosingTags !== false
: // User explicitly asked for self-closing tags, even in HTML mode
opts.selfClosingTags && singleTag.has(elem.name))) {
if (!opts.xmlMode)
tag += " ";
tag += "/>";
}
else {
tag += ">";
if (elem.children.length > 0) {
tag += render(elem.children, opts);
}
if (opts.xmlMode || !singleTag.has(elem.name)) {
tag += "</" + elem.name + ">";
}
}
return tag;
}
function renderDirective(elem) {
return "<" + elem.data + ">";
}
function renderText(elem, opts) {
var data = elem.data || "";
// If entities weren't decoded, no need to encode them back
if (opts.decodeEntities !== false &&
!(!opts.xmlMode &&
elem.parent &&
unencodedElements.has(elem.parent.name))) {
data = entities_1.encodeXML(data);
}
return data;
}
function renderCdata(elem) {
return "<![CDATA[" + elem.children[0].data + "]]>";
}
function renderComment(elem) {
return "<!--" + elem.data + "-->";
}

View File

@@ -0,0 +1,55 @@
{
"name": "dom-serializer",
"version": "1.4.1",
"description": "render domhandler DOM nodes to a string",
"author": "Felix Boehm <me@feedic.com>",
"sideEffects": false,
"keywords": [
"html",
"xml",
"render"
],
"repository": {
"type": "git",
"url": "git://github.com/cheeriojs/dom-renderer.git"
},
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib/**/*"
],
"dependencies": {
"domelementtype": "^2.0.1",
"domhandler": "^4.2.0",
"entities": "^2.0.0"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"@types/node": "^15.3.0",
"@typescript-eslint/eslint-plugin": "^4.23.0",
"@typescript-eslint/parser": "^4.23.0",
"cheerio": "^1.0.0-rc.9",
"coveralls": "^3.0.5",
"eslint": "^7.26.0",
"eslint-config-prettier": "^8.3.0",
"htmlparser2": "^6.1.0",
"jest": "^26.0.1",
"prettier": "^2.3.0",
"ts-jest": "^26.5.6",
"typescript": "^4.0.2"
},
"scripts": {
"test": "jest --coverage && npm run lint",
"coverage": "cat coverage/lcov.info | coveralls",
"lint": "eslint src",
"format": "prettier --write '**/*.{ts,md,json}'",
"build": "tsc",
"prepare": "npm run build"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"funding": "https://github.com/cheeriojs/dom-serializer?sponsor=1",
"license": "MIT"
}

11
node_modules/svgo/node_modules/domhandler/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,85 @@
import { Node, Element, DataNode, NodeWithChildren, Document } from "./node";
export * from "./node";
export interface DomHandlerOptions {
/**
* Add a `startIndex` property to nodes.
* When the parser is used in a non-streaming fashion, `startIndex` is an integer
* indicating the position of the start of the node in the document.
*
* @default false
*/
withStartIndices?: boolean;
/**
* Add an `endIndex` property to nodes.
* When the parser is used in a non-streaming fashion, `endIndex` is an integer
* indicating the position of the end of the node in the document.
*
* @default false
*/
withEndIndices?: boolean;
/**
* Replace all whitespace with single spaces.
*
* **Note:** Enabling this might break your markup.
*
* @default false
* @deprecated
*/
normalizeWhitespace?: boolean;
/**
* Treat the markup as XML.
*
* @default false
*/
xmlMode?: boolean;
}
interface ParserInterface {
startIndex: number | null;
endIndex: number | null;
}
declare type Callback = (error: Error | null, dom: Node[]) => void;
declare type ElementCallback = (element: Element) => void;
export declare class DomHandler {
/** The elements of the DOM */
dom: Node[];
/** The root element for the DOM */
root: Document;
/** Called once parsing has completed. */
private readonly callback;
/** Settings for the handler. */
private readonly options;
/** Callback whenever a tag is closed. */
private readonly elementCB;
/** Indicated whether parsing has been completed. */
private done;
/** Stack of open tags. */
protected tagStack: NodeWithChildren[];
/** A data node that is still being written to. */
protected lastNode: DataNode | null;
/** Reference to the parser instance. Used for location information. */
private parser;
/**
* @param callback Called once parsing has completed.
* @param options Settings for the handler.
* @param elementCB Callback whenever a tag is closed.
*/
constructor(callback?: Callback | null, options?: DomHandlerOptions | null, elementCB?: ElementCallback);
onparserinit(parser: ParserInterface): void;
onreset(): void;
onend(): void;
onerror(error: Error): void;
onclosetag(): void;
onopentag(name: string, attribs: {
[key: string]: string;
}): void;
ontext(data: string): void;
oncomment(data: string): void;
oncommentend(): void;
oncdatastart(): void;
oncdataend(): void;
onprocessinginstruction(name: string, data: string): void;
protected handleCallback(error: Error | null): void;
protected addNode(node: Node): void;
}
export default DomHandler;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,IAAI,EACJ,OAAO,EACP,QAAQ,EAGR,gBAAgB,EAChB,QAAQ,EAEX,MAAM,QAAQ,CAAC;AAEhB,cAAc,QAAQ,CAAC;AAIvB,MAAM,WAAW,iBAAiB;IAC9B;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;;;;OAOG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAE9B;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAUD,UAAU,eAAe;IACrB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,aAAK,QAAQ,GAAG,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,CAAC;AAC3D,aAAK,eAAe,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;AAElD,qBAAa,UAAU;IACnB,8BAA8B;IACvB,GAAG,EAAE,IAAI,EAAE,CAAM;IAExB,mCAAmC;IAC5B,IAAI,WAA0B;IAErC,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkB;IAE3C,gCAAgC;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAE5C,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IAEnD,oDAAoD;IACpD,OAAO,CAAC,IAAI,CAAS;IAErB,0BAA0B;IAC1B,SAAS,CAAC,QAAQ,EAAE,gBAAgB,EAAE,CAAe;IAErD,kDAAkD;IAClD,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAQ;IAE3C,uEAAuE;IACvE,OAAO,CAAC,MAAM,CAAgC;IAE9C;;;;OAIG;gBAEC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,EAC1B,OAAO,CAAC,EAAE,iBAAiB,GAAG,IAAI,EAClC,SAAS,CAAC,EAAE,eAAe;IAiBxB,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,IAAI;IAK3C,OAAO,IAAI,IAAI;IAUf,KAAK,IAAI,IAAI;IAOb,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAI3B,UAAU,IAAI,IAAI;IAYlB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,IAAI;IAOjE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IA2B1B,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAW7B,YAAY,IAAI,IAAI;IAIpB,YAAY,IAAI,IAAI;IAUpB,UAAU,IAAI,IAAI;IAIlB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAKhE,SAAS,CAAC,cAAc,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,GAAG,IAAI;IAQnD,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI;CAwBtC;AAED,eAAe,UAAU,CAAC"}

176
node_modules/svgo/node_modules/domhandler/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,176 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DomHandler = void 0;
var domelementtype_1 = require("domelementtype");
var node_1 = require("./node");
__exportStar(require("./node"), exports);
var reWhitespace = /\s+/g;
// Default options
var defaultOpts = {
normalizeWhitespace: false,
withStartIndices: false,
withEndIndices: false,
xmlMode: false,
};
var DomHandler = /** @class */ (function () {
/**
* @param callback Called once parsing has completed.
* @param options Settings for the handler.
* @param elementCB Callback whenever a tag is closed.
*/
function DomHandler(callback, options, elementCB) {
/** The elements of the DOM */
this.dom = [];
/** The root element for the DOM */
this.root = new node_1.Document(this.dom);
/** Indicated whether parsing has been completed. */
this.done = false;
/** Stack of open tags. */
this.tagStack = [this.root];
/** A data node that is still being written to. */
this.lastNode = null;
/** Reference to the parser instance. Used for location information. */
this.parser = null;
// Make it possible to skip arguments, for backwards-compatibility
if (typeof options === "function") {
elementCB = options;
options = defaultOpts;
}
if (typeof callback === "object") {
options = callback;
callback = undefined;
}
this.callback = callback !== null && callback !== void 0 ? callback : null;
this.options = options !== null && options !== void 0 ? options : defaultOpts;
this.elementCB = elementCB !== null && elementCB !== void 0 ? elementCB : null;
}
DomHandler.prototype.onparserinit = function (parser) {
this.parser = parser;
};
// Resets the handler back to starting state
DomHandler.prototype.onreset = function () {
this.dom = [];
this.root = new node_1.Document(this.dom);
this.done = false;
this.tagStack = [this.root];
this.lastNode = null;
this.parser = null;
};
// Signals the handler that parsing is done
DomHandler.prototype.onend = function () {
if (this.done)
return;
this.done = true;
this.parser = null;
this.handleCallback(null);
};
DomHandler.prototype.onerror = function (error) {
this.handleCallback(error);
};
DomHandler.prototype.onclosetag = function () {
this.lastNode = null;
var elem = this.tagStack.pop();
if (this.options.withEndIndices) {
elem.endIndex = this.parser.endIndex;
}
if (this.elementCB)
this.elementCB(elem);
};
DomHandler.prototype.onopentag = function (name, attribs) {
var type = this.options.xmlMode ? domelementtype_1.ElementType.Tag : undefined;
var element = new node_1.Element(name, attribs, undefined, type);
this.addNode(element);
this.tagStack.push(element);
};
DomHandler.prototype.ontext = function (data) {
var normalizeWhitespace = this.options.normalizeWhitespace;
var lastNode = this.lastNode;
if (lastNode && lastNode.type === domelementtype_1.ElementType.Text) {
if (normalizeWhitespace) {
lastNode.data = (lastNode.data + data).replace(reWhitespace, " ");
}
else {
lastNode.data += data;
}
if (this.options.withEndIndices) {
lastNode.endIndex = this.parser.endIndex;
}
}
else {
if (normalizeWhitespace) {
data = data.replace(reWhitespace, " ");
}
var node = new node_1.Text(data);
this.addNode(node);
this.lastNode = node;
}
};
DomHandler.prototype.oncomment = function (data) {
if (this.lastNode && this.lastNode.type === domelementtype_1.ElementType.Comment) {
this.lastNode.data += data;
return;
}
var node = new node_1.Comment(data);
this.addNode(node);
this.lastNode = node;
};
DomHandler.prototype.oncommentend = function () {
this.lastNode = null;
};
DomHandler.prototype.oncdatastart = function () {
var text = new node_1.Text("");
var node = new node_1.NodeWithChildren(domelementtype_1.ElementType.CDATA, [text]);
this.addNode(node);
text.parent = node;
this.lastNode = text;
};
DomHandler.prototype.oncdataend = function () {
this.lastNode = null;
};
DomHandler.prototype.onprocessinginstruction = function (name, data) {
var node = new node_1.ProcessingInstruction(name, data);
this.addNode(node);
};
DomHandler.prototype.handleCallback = function (error) {
if (typeof this.callback === "function") {
this.callback(error, this.dom);
}
else if (error) {
throw error;
}
};
DomHandler.prototype.addNode = function (node) {
var parent = this.tagStack[this.tagStack.length - 1];
var previousSibling = parent.children[parent.children.length - 1];
if (this.options.withStartIndices) {
node.startIndex = this.parser.startIndex;
}
if (this.options.withEndIndices) {
node.endIndex = this.parser.endIndex;
}
parent.children.push(node);
if (previousSibling) {
node.prev = previousSibling;
previousSibling.next = node;
}
node.parent = parent;
this.lastNode = null;
};
return DomHandler;
}());
exports.DomHandler = DomHandler;
exports.default = DomHandler;

237
node_modules/svgo/node_modules/domhandler/lib/node.d.ts generated vendored Normal file
View File

@@ -0,0 +1,237 @@
import { ElementType } from "domelementtype";
interface SourceCodeLocation {
/** One-based line index of the first character. */
startLine: number;
/** One-based column index of the first character. */
startCol: number;
/** Zero-based first character index. */
startOffset: number;
/** One-based line index of the last character. */
endLine: number;
/** One-based column index of the last character. Points directly *after* the last character. */
endCol: number;
/** Zero-based last character index. Points directly *after* the last character. */
endOffset: number;
}
interface TagSourceCodeLocation extends SourceCodeLocation {
startTag?: SourceCodeLocation;
endTag?: SourceCodeLocation;
}
/**
* This object will be used as the prototype for Nodes when creating a
* DOM-Level-1-compliant structure.
*/
export declare class Node {
type: ElementType;
/** Parent of the node */
parent: NodeWithChildren | null;
/** Previous sibling */
prev: Node | null;
/** Next sibling */
next: Node | null;
/** The start index of the node. Requires `withStartIndices` on the handler to be `true. */
startIndex: number | null;
/** The end index of the node. Requires `withEndIndices` on the handler to be `true. */
endIndex: number | null;
/**
* `parse5` source code location info.
*
* Available if parsing with parse5 and location info is enabled.
*/
sourceCodeLocation?: SourceCodeLocation | null;
/**
*
* @param type The type of the node.
*/
constructor(type: ElementType);
/**
* [DOM spec](https://dom.spec.whatwg.org/#dom-node-nodetype)-compatible
* node {@link type}.
*/
get nodeType(): number;
/**
* Same as {@link parent}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get parentNode(): NodeWithChildren | null;
set parentNode(parent: NodeWithChildren | null);
/**
* Same as {@link prev}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get previousSibling(): Node | null;
set previousSibling(prev: Node | null);
/**
* Same as {@link next}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get nextSibling(): Node | null;
set nextSibling(next: Node | null);
/**
* Clone this node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
cloneNode<T extends Node>(this: T, recursive?: boolean): T;
}
/**
* A node that contains some data.
*/
export declare class DataNode extends Node {
data: string;
/**
* @param type The type of the node
* @param data The content of the data node
*/
constructor(type: ElementType.Comment | ElementType.Text | ElementType.Directive, data: string);
/**
* Same as {@link data}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get nodeValue(): string;
set nodeValue(data: string);
}
/**
* Text within the document.
*/
export declare class Text extends DataNode {
constructor(data: string);
}
/**
* Comments within the document.
*/
export declare class Comment extends DataNode {
constructor(data: string);
}
/**
* Processing instructions, including doc types.
*/
export declare class ProcessingInstruction extends DataNode {
name: string;
constructor(name: string, data: string);
/** If this is a doctype, the document type name (parse5 only). */
"x-name"?: string;
/** If this is a doctype, the document type public identifier (parse5 only). */
"x-publicId"?: string;
/** If this is a doctype, the document type system identifier (parse5 only). */
"x-systemId"?: string;
}
/**
* A `Node` that can have children.
*/
export declare class NodeWithChildren extends Node {
children: Node[];
/**
* @param type Type of the node.
* @param children Children of the node. Only certain node types can have children.
*/
constructor(type: ElementType.Root | ElementType.CDATA | ElementType.Script | ElementType.Style | ElementType.Tag, children: Node[]);
/** First child of the node. */
get firstChild(): Node | null;
/** Last child of the node. */
get lastChild(): Node | null;
/**
* Same as {@link children}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get childNodes(): Node[];
set childNodes(children: Node[]);
}
/**
* The root node of the document.
*/
export declare class Document extends NodeWithChildren {
constructor(children: Node[]);
/** [Document mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks) (parse5 only). */
"x-mode"?: "no-quirks" | "quirks" | "limited-quirks";
}
/**
* The description of an individual attribute.
*/
interface Attribute {
name: string;
value: string;
namespace?: string;
prefix?: string;
}
/**
* An element within the DOM.
*/
export declare class Element extends NodeWithChildren {
name: string;
attribs: {
[name: string]: string;
};
/**
* @param name Name of the tag, eg. `div`, `span`.
* @param attribs Object mapping attribute names to attribute values.
* @param children Children of the node.
*/
constructor(name: string, attribs: {
[name: string]: string;
}, children?: Node[], type?: ElementType.Tag | ElementType.Script | ElementType.Style);
/**
* `parse5` source code location info, with start & end tags.
*
* Available if parsing with parse5 and location info is enabled.
*/
sourceCodeLocation?: TagSourceCodeLocation | null;
/**
* Same as {@link name}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get tagName(): string;
set tagName(name: string);
get attributes(): Attribute[];
/** Element namespace (parse5 only). */
namespace?: string;
/** Element attribute namespaces (parse5 only). */
"x-attribsNamespace"?: Record<string, string>;
/** Element attribute namespace-related prefixes (parse5 only). */
"x-attribsPrefix"?: Record<string, string>;
}
/**
* @param node Node to check.
* @returns `true` if the node is a `Element`, `false` otherwise.
*/
export declare function isTag(node: Node): node is Element;
/**
* @param node Node to check.
* @returns `true` if the node has the type `CDATA`, `false` otherwise.
*/
export declare function isCDATA(node: Node): node is NodeWithChildren;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Text`, `false` otherwise.
*/
export declare function isText(node: Node): node is Text;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Comment`, `false` otherwise.
*/
export declare function isComment(node: Node): node is DataNode;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
export declare function isDirective(node: Node): node is ProcessingInstruction;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
export declare function isDocument(node: Node): node is Document;
/**
* @param node Node to check.
* @returns `true` if the node is a `NodeWithChildren` (has children), `false` otherwise.
*/
export declare function hasChildren(node: Node): node is NodeWithChildren;
/**
* Clone a node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
export declare function cloneNode<T extends Node>(node: T, recursive?: boolean): T;
export {};
//# sourceMappingURL=node.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAqB,MAAM,gBAAgB,CAAC;AAahE,UAAU,kBAAkB;IACxB,mDAAmD;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAC;IACjB,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,OAAO,EAAE,MAAM,CAAC;IAChB,gGAAgG;IAChG,MAAM,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,UAAU,qBAAsB,SAAQ,kBAAkB;IACtD,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAC9B,MAAM,CAAC,EAAE,kBAAkB,CAAC;CAC/B;AAED;;;GAGG;AACH,qBAAa,IAAI;IA2BM,IAAI,EAAE,WAAW;IA1BpC,yBAAyB;IACzB,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAQ;IAEvC,uBAAuB;IACvB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAQ;IAEzB,mBAAmB;IACnB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAQ;IAEzB,2FAA2F;IAC3F,UAAU,EAAE,MAAM,GAAG,IAAI,CAAQ;IAEjC,uFAAuF;IACvF,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE/B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAE/C;;;OAGG;gBACgB,IAAI,EAAE,WAAW;IAIpC;;;OAGG;IACH,IAAI,QAAQ,IAAI,MAAM,CAErB;IAID;;;OAGG;IACH,IAAI,UAAU,IAAI,gBAAgB,GAAG,IAAI,CAExC;IAED,IAAI,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,EAE7C;IAED;;;OAGG;IACH,IAAI,eAAe,IAAI,IAAI,GAAG,IAAI,CAEjC;IAED,IAAI,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAEpC;IAED;;;OAGG;IACH,IAAI,WAAW,IAAI,IAAI,GAAG,IAAI,CAE7B;IAED,IAAI,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAEhC;IAED;;;;;OAKG;IACH,SAAS,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,SAAS,UAAQ,GAAG,CAAC;CAG3D;AAED;;GAEG;AACH,qBAAa,QAAS,SAAQ,IAAI;IAOnB,IAAI,EAAE,MAAM;IANvB;;;OAGG;gBAEC,IAAI,EAAE,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC,IAAI,GAAG,WAAW,CAAC,SAAS,EAC7D,IAAI,EAAE,MAAM;IAKvB;;;OAGG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED,IAAI,SAAS,CAAC,IAAI,EAAE,MAAM,EAEzB;CACJ;AAED;;GAEG;AACH,qBAAa,IAAK,SAAQ,QAAQ;gBAClB,IAAI,EAAE,MAAM;CAG3B;AAED;;GAEG;AACH,qBAAa,OAAQ,SAAQ,QAAQ;gBACrB,IAAI,EAAE,MAAM;CAG3B;AAED;;GAEG;AACH,qBAAa,qBAAsB,SAAQ,QAAQ;IAC5B,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAI7C,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,IAAI;IAY3B,QAAQ,EAAE,IAAI,EAAE;IAX3B;;;OAGG;gBAEC,IAAI,EACE,WAAW,CAAC,IAAI,GAChB,WAAW,CAAC,KAAK,GACjB,WAAW,CAAC,MAAM,GAClB,WAAW,CAAC,KAAK,GACjB,WAAW,CAAC,GAAG,EACd,QAAQ,EAAE,IAAI,EAAE;IAM3B,+BAA+B;IAC/B,IAAI,UAAU,IAAI,IAAI,GAAG,IAAI,CAE5B;IAED,8BAA8B;IAC9B,IAAI,SAAS,IAAI,IAAI,GAAG,IAAI,CAI3B;IAED;;;OAGG;IACH,IAAI,UAAU,IAAI,IAAI,EAAE,CAEvB;IAED,IAAI,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,EAE9B;CACJ;AAED;;GAEG;AACH,qBAAa,QAAS,SAAQ,gBAAgB;gBAC9B,QAAQ,EAAE,IAAI,EAAE;IAI5B,mGAAmG;IACnG,QAAQ,CAAC,EAAE,WAAW,GAAG,QAAQ,GAAG,gBAAgB,CAAC;CACxD;AAED;;GAEG;AACH,UAAU,SAAS;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,qBAAa,OAAQ,SAAQ,gBAAgB;IAO9B,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE;IAP9C;;;;OAIG;gBAEQ,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,EAC1C,QAAQ,GAAE,IAAI,EAAO,EACrB,IAAI,GACE,WAAW,CAAC,GAAG,GACf,WAAW,CAAC,MAAM,GAClB,WAAW,CAAC,KAIG;IAKzB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAIlD;;;OAGG;IACH,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,OAAO,CAAC,IAAI,EAAE,MAAM,EAEvB;IAED,IAAI,UAAU,IAAI,SAAS,EAAE,CAO5B;IAED,uCAAuC;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kDAAkD;IAClD,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9C,kEAAkE;IAClE,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9C;AAED;;;GAGG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,OAAO,CAEjD;AAED;;;GAGG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,gBAAgB,CAE5D;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,IAAI,CAE/C;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,QAAQ,CAEtD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,qBAAqB,CAErE;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,QAAQ,CAEvD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,gBAAgB,CAEhE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,SAAS,UAAQ,GAAG,CAAC,CA4DvE"}

444
node_modules/svgo/node_modules/domhandler/lib/node.js generated vendored Normal file
View File

@@ -0,0 +1,444 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneNode = exports.hasChildren = exports.isDocument = exports.isDirective = exports.isComment = exports.isText = exports.isCDATA = exports.isTag = exports.Element = exports.Document = exports.NodeWithChildren = exports.ProcessingInstruction = exports.Comment = exports.Text = exports.DataNode = exports.Node = void 0;
var domelementtype_1 = require("domelementtype");
var nodeTypes = new Map([
[domelementtype_1.ElementType.Tag, 1],
[domelementtype_1.ElementType.Script, 1],
[domelementtype_1.ElementType.Style, 1],
[domelementtype_1.ElementType.Directive, 1],
[domelementtype_1.ElementType.Text, 3],
[domelementtype_1.ElementType.CDATA, 4],
[domelementtype_1.ElementType.Comment, 8],
[domelementtype_1.ElementType.Root, 9],
]);
/**
* This object will be used as the prototype for Nodes when creating a
* DOM-Level-1-compliant structure.
*/
var Node = /** @class */ (function () {
/**
*
* @param type The type of the node.
*/
function Node(type) {
this.type = type;
/** Parent of the node */
this.parent = null;
/** Previous sibling */
this.prev = null;
/** Next sibling */
this.next = null;
/** The start index of the node. Requires `withStartIndices` on the handler to be `true. */
this.startIndex = null;
/** The end index of the node. Requires `withEndIndices` on the handler to be `true. */
this.endIndex = null;
}
Object.defineProperty(Node.prototype, "nodeType", {
// Read-only aliases
/**
* [DOM spec](https://dom.spec.whatwg.org/#dom-node-nodetype)-compatible
* node {@link type}.
*/
get: function () {
var _a;
return (_a = nodeTypes.get(this.type)) !== null && _a !== void 0 ? _a : 1;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "parentNode", {
// Read-write aliases for properties
/**
* Same as {@link parent}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.parent;
},
set: function (parent) {
this.parent = parent;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "previousSibling", {
/**
* Same as {@link prev}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.prev;
},
set: function (prev) {
this.prev = prev;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "nextSibling", {
/**
* Same as {@link next}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.next;
},
set: function (next) {
this.next = next;
},
enumerable: false,
configurable: true
});
/**
* Clone this node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
Node.prototype.cloneNode = function (recursive) {
if (recursive === void 0) { recursive = false; }
return cloneNode(this, recursive);
};
return Node;
}());
exports.Node = Node;
/**
* A node that contains some data.
*/
var DataNode = /** @class */ (function (_super) {
__extends(DataNode, _super);
/**
* @param type The type of the node
* @param data The content of the data node
*/
function DataNode(type, data) {
var _this = _super.call(this, type) || this;
_this.data = data;
return _this;
}
Object.defineProperty(DataNode.prototype, "nodeValue", {
/**
* Same as {@link data}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.data;
},
set: function (data) {
this.data = data;
},
enumerable: false,
configurable: true
});
return DataNode;
}(Node));
exports.DataNode = DataNode;
/**
* Text within the document.
*/
var Text = /** @class */ (function (_super) {
__extends(Text, _super);
function Text(data) {
return _super.call(this, domelementtype_1.ElementType.Text, data) || this;
}
return Text;
}(DataNode));
exports.Text = Text;
/**
* Comments within the document.
*/
var Comment = /** @class */ (function (_super) {
__extends(Comment, _super);
function Comment(data) {
return _super.call(this, domelementtype_1.ElementType.Comment, data) || this;
}
return Comment;
}(DataNode));
exports.Comment = Comment;
/**
* Processing instructions, including doc types.
*/
var ProcessingInstruction = /** @class */ (function (_super) {
__extends(ProcessingInstruction, _super);
function ProcessingInstruction(name, data) {
var _this = _super.call(this, domelementtype_1.ElementType.Directive, data) || this;
_this.name = name;
return _this;
}
return ProcessingInstruction;
}(DataNode));
exports.ProcessingInstruction = ProcessingInstruction;
/**
* A `Node` that can have children.
*/
var NodeWithChildren = /** @class */ (function (_super) {
__extends(NodeWithChildren, _super);
/**
* @param type Type of the node.
* @param children Children of the node. Only certain node types can have children.
*/
function NodeWithChildren(type, children) {
var _this = _super.call(this, type) || this;
_this.children = children;
return _this;
}
Object.defineProperty(NodeWithChildren.prototype, "firstChild", {
// Aliases
/** First child of the node. */
get: function () {
var _a;
return (_a = this.children[0]) !== null && _a !== void 0 ? _a : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeWithChildren.prototype, "lastChild", {
/** Last child of the node. */
get: function () {
return this.children.length > 0
? this.children[this.children.length - 1]
: null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeWithChildren.prototype, "childNodes", {
/**
* Same as {@link children}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.children;
},
set: function (children) {
this.children = children;
},
enumerable: false,
configurable: true
});
return NodeWithChildren;
}(Node));
exports.NodeWithChildren = NodeWithChildren;
/**
* The root node of the document.
*/
var Document = /** @class */ (function (_super) {
__extends(Document, _super);
function Document(children) {
return _super.call(this, domelementtype_1.ElementType.Root, children) || this;
}
return Document;
}(NodeWithChildren));
exports.Document = Document;
/**
* An element within the DOM.
*/
var Element = /** @class */ (function (_super) {
__extends(Element, _super);
/**
* @param name Name of the tag, eg. `div`, `span`.
* @param attribs Object mapping attribute names to attribute values.
* @param children Children of the node.
*/
function Element(name, attribs, children, type) {
if (children === void 0) { children = []; }
if (type === void 0) { type = name === "script"
? domelementtype_1.ElementType.Script
: name === "style"
? domelementtype_1.ElementType.Style
: domelementtype_1.ElementType.Tag; }
var _this = _super.call(this, type, children) || this;
_this.name = name;
_this.attribs = attribs;
return _this;
}
Object.defineProperty(Element.prototype, "tagName", {
// DOM Level 1 aliases
/**
* Same as {@link name}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.name;
},
set: function (name) {
this.name = name;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Element.prototype, "attributes", {
get: function () {
var _this = this;
return Object.keys(this.attribs).map(function (name) {
var _a, _b;
return ({
name: name,
value: _this.attribs[name],
namespace: (_a = _this["x-attribsNamespace"]) === null || _a === void 0 ? void 0 : _a[name],
prefix: (_b = _this["x-attribsPrefix"]) === null || _b === void 0 ? void 0 : _b[name],
});
});
},
enumerable: false,
configurable: true
});
return Element;
}(NodeWithChildren));
exports.Element = Element;
/**
* @param node Node to check.
* @returns `true` if the node is a `Element`, `false` otherwise.
*/
function isTag(node) {
return (0, domelementtype_1.isTag)(node);
}
exports.isTag = isTag;
/**
* @param node Node to check.
* @returns `true` if the node has the type `CDATA`, `false` otherwise.
*/
function isCDATA(node) {
return node.type === domelementtype_1.ElementType.CDATA;
}
exports.isCDATA = isCDATA;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Text`, `false` otherwise.
*/
function isText(node) {
return node.type === domelementtype_1.ElementType.Text;
}
exports.isText = isText;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Comment`, `false` otherwise.
*/
function isComment(node) {
return node.type === domelementtype_1.ElementType.Comment;
}
exports.isComment = isComment;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
function isDirective(node) {
return node.type === domelementtype_1.ElementType.Directive;
}
exports.isDirective = isDirective;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
function isDocument(node) {
return node.type === domelementtype_1.ElementType.Root;
}
exports.isDocument = isDocument;
/**
* @param node Node to check.
* @returns `true` if the node is a `NodeWithChildren` (has children), `false` otherwise.
*/
function hasChildren(node) {
return Object.prototype.hasOwnProperty.call(node, "children");
}
exports.hasChildren = hasChildren;
/**
* Clone a node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
function cloneNode(node, recursive) {
if (recursive === void 0) { recursive = false; }
var result;
if (isText(node)) {
result = new Text(node.data);
}
else if (isComment(node)) {
result = new Comment(node.data);
}
else if (isTag(node)) {
var children = recursive ? cloneChildren(node.children) : [];
var clone_1 = new Element(node.name, __assign({}, node.attribs), children);
children.forEach(function (child) { return (child.parent = clone_1); });
if (node.namespace != null) {
clone_1.namespace = node.namespace;
}
if (node["x-attribsNamespace"]) {
clone_1["x-attribsNamespace"] = __assign({}, node["x-attribsNamespace"]);
}
if (node["x-attribsPrefix"]) {
clone_1["x-attribsPrefix"] = __assign({}, node["x-attribsPrefix"]);
}
result = clone_1;
}
else if (isCDATA(node)) {
var children = recursive ? cloneChildren(node.children) : [];
var clone_2 = new NodeWithChildren(domelementtype_1.ElementType.CDATA, children);
children.forEach(function (child) { return (child.parent = clone_2); });
result = clone_2;
}
else if (isDocument(node)) {
var children = recursive ? cloneChildren(node.children) : [];
var clone_3 = new Document(children);
children.forEach(function (child) { return (child.parent = clone_3); });
if (node["x-mode"]) {
clone_3["x-mode"] = node["x-mode"];
}
result = clone_3;
}
else if (isDirective(node)) {
var instruction = new ProcessingInstruction(node.name, node.data);
if (node["x-name"] != null) {
instruction["x-name"] = node["x-name"];
instruction["x-publicId"] = node["x-publicId"];
instruction["x-systemId"] = node["x-systemId"];
}
result = instruction;
}
else {
throw new Error("Not implemented yet: ".concat(node.type));
}
result.startIndex = node.startIndex;
result.endIndex = node.endIndex;
if (node.sourceCodeLocation != null) {
result.sourceCodeLocation = node.sourceCodeLocation;
}
return result;
}
exports.cloneNode = cloneNode;
function cloneChildren(childs) {
var children = childs.map(function (child) { return cloneNode(child, true); });
for (var i = 1; i < children.length; i++) {
children[i].prev = children[i - 1];
children[i - 1].next = children[i];
}
return children;
}

58
node_modules/svgo/node_modules/domhandler/package.json generated vendored Normal file
View File

@@ -0,0 +1,58 @@
{
"name": "domhandler",
"version": "4.3.1",
"description": "Handler for htmlparser2 that turns pages into a dom",
"author": "Felix Boehm <me@feedic.com>",
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
},
"license": "BSD-2-Clause",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"sideEffects": false,
"files": [
"lib"
],
"scripts": {
"test": "npm run test:jest && npm run lint",
"test:jest": "jest",
"lint": "eslint src",
"format": "prettier --write '**/*.{ts,md,json}'",
"build": "tsc",
"prepare": "npm run build"
},
"repository": {
"type": "git",
"url": "git://github.com/fb55/domhandler.git"
},
"keywords": [
"dom",
"htmlparser2"
],
"engines": {
"node": ">= 4"
},
"dependencies": {
"domelementtype": "^2.2.0"
},
"devDependencies": {
"@types/jest": "^27.4.1",
"@types/node": "^17.0.21",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
"eslint": "^8.11.0",
"eslint-config-prettier": "^8.5.0",
"htmlparser2": "^7.2.0",
"jest": "^27.5.1",
"prettier": "^2.6.0",
"ts-jest": "^27.1.3",
"typescript": "^4.6.2"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"prettier": {
"tabWidth": 4
}
}

163
node_modules/svgo/node_modules/domhandler/readme.md generated vendored Normal file
View File

@@ -0,0 +1,163 @@
# domhandler [![Build Status](https://travis-ci.com/fb55/domhandler.svg?branch=master)](https://travis-ci.com/fb55/domhandler)
The DOM handler creates a tree containing all nodes of a page.
The tree can be manipulated using the [domutils](https://github.com/fb55/domutils)
or [cheerio](https://github.com/cheeriojs/cheerio) libraries and
rendered using [dom-serializer](https://github.com/cheeriojs/dom-serializer) .
## Usage
```javascript
const handler = new DomHandler([ <func> callback(err, dom), ] [ <obj> options ]);
// const parser = new Parser(handler[, options]);
```
Available options are described below.
## Example
```javascript
const { Parser } = require("htmlparser2");
const { DomHandler } = require("domhandler");
const rawHtml =
"Xyz <script language= javascript>var foo = '<<bar>>';</script><!--<!-- Waah! -- -->";
const handler = new DomHandler((error, dom) => {
if (error) {
// Handle error
} else {
// Parsing completed, do something
console.log(dom);
}
});
const parser = new Parser(handler);
parser.write(rawHtml);
parser.end();
```
Output:
```javascript
[
{
data: "Xyz ",
type: "text",
},
{
type: "script",
name: "script",
attribs: {
language: "javascript",
},
children: [
{
data: "var foo = '<bar>';<",
type: "text",
},
],
},
{
data: "<!-- Waah! -- ",
type: "comment",
},
];
```
## Option: `withStartIndices`
Add a `startIndex` property to nodes.
When the parser is used in a non-streaming fashion, `startIndex` is an integer
indicating the position of the start of the node in the document.
The default value is `false`.
## Option: `withEndIndices`
Add an `endIndex` property to nodes.
When the parser is used in a non-streaming fashion, `endIndex` is an integer
indicating the position of the end of the node in the document.
The default value is `false`.
## Option: `normalizeWhitespace` _(deprecated)_
Replace all whitespace with single spaces.
The default value is `false`.
**Note:** Enabling this might break your markup.
For the following examples, this HTML will be used:
```html
<font> <br />this is the text <font></font></font>
```
### Example: `normalizeWhitespace: true`
```javascript
[
{
type: "tag",
name: "font",
children: [
{
data: " ",
type: "text",
},
{
type: "tag",
name: "br",
},
{
data: "this is the text ",
type: "text",
},
{
type: "tag",
name: "font",
},
],
},
];
```
### Example: `normalizeWhitespace: false`
```javascript
[
{
type: "tag",
name: "font",
children: [
{
data: "\n\t",
type: "text",
},
{
type: "tag",
name: "br",
},
{
data: "this is the text\n",
type: "text",
},
{
type: "tag",
name: "font",
},
],
},
];
```
---
License: BSD-2-Clause
## Security contact information
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
## `domhandler` for enterprise
Available as part of the Tidelift Subscription
The maintainers of `domhandler` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-domhandler?utm_source=npm-domhandler&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

11
node_modules/svgo/node_modules/domutils/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

45
node_modules/svgo/node_modules/domutils/lib/feeds.d.ts generated vendored Normal file
View File

@@ -0,0 +1,45 @@
import type { Node } from "domhandler";
export declare type FeedItemMediaMedium = "image" | "audio" | "video" | "document" | "executable";
export declare type FeedItemMediaExpression = "sample" | "full" | "nonstop";
export interface FeedItemMedia {
medium: FeedItemMediaMedium | undefined;
isDefault: boolean;
url?: string;
fileSize?: number;
type?: string;
expression?: FeedItemMediaExpression;
bitrate?: number;
framerate?: number;
samplingrate?: number;
channels?: number;
duration?: number;
height?: number;
width?: number;
lang?: string;
}
export interface FeedItem {
id?: string;
title?: string;
link?: string;
description?: string;
pubDate?: Date;
media: FeedItemMedia[];
}
export interface Feed {
type: string;
id?: string;
title?: string;
link?: string;
description?: string;
updated?: Date;
author?: string;
items: FeedItem[];
}
/**
* Get the feed object from the root of a DOM tree.
*
* @param doc - The DOM to to extract the feed from.
* @returns The feed.
*/
export declare function getFeed(doc: Node[]): Feed | null;
//# sourceMappingURL=feeds.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"feeds.d.ts","sourceRoot":"","sources":["../src/feeds.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAW,MAAM,YAAY,CAAC;AAIhD,oBAAY,mBAAmB,GACzB,OAAO,GACP,OAAO,GACP,OAAO,GACP,UAAU,GACV,YAAY,CAAC;AAEnB,oBAAY,uBAAuB,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;AAEpE,MAAM,WAAW,aAAa;IAC1B,MAAM,EAAE,mBAAmB,GAAG,SAAS,CAAC;IACxC,SAAS,EAAE,OAAO,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,uBAAuB,CAAC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,QAAQ;IACrB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,KAAK,EAAE,aAAa,EAAE,CAAC;CAC1B;AAED,MAAM,WAAW,IAAI;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,QAAQ,EAAE,CAAC;CACrB;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,IAAI,CAQhD"}

190
node_modules/svgo/node_modules/domutils/lib/feeds.js generated vendored Normal file
View File

@@ -0,0 +1,190 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFeed = void 0;
var stringify_1 = require("./stringify");
var legacy_1 = require("./legacy");
/**
* Get the feed object from the root of a DOM tree.
*
* @param doc - The DOM to to extract the feed from.
* @returns The feed.
*/
function getFeed(doc) {
var feedRoot = getOneElement(isValidFeed, doc);
return !feedRoot
? null
: feedRoot.name === "feed"
? getAtomFeed(feedRoot)
: getRssFeed(feedRoot);
}
exports.getFeed = getFeed;
/**
* Parse an Atom feed.
*
* @param feedRoot The root of the feed.
* @returns The parsed feed.
*/
function getAtomFeed(feedRoot) {
var _a;
var childs = feedRoot.children;
var feed = {
type: "atom",
items: (0, legacy_1.getElementsByTagName)("entry", childs).map(function (item) {
var _a;
var children = item.children;
var entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "id", children);
addConditionally(entry, "title", "title", children);
var href = (_a = getOneElement("link", children)) === null || _a === void 0 ? void 0 : _a.attribs.href;
if (href) {
entry.link = href;
}
var description = fetch("summary", children) || fetch("content", children);
if (description) {
entry.description = description;
}
var pubDate = fetch("updated", children);
if (pubDate) {
entry.pubDate = new Date(pubDate);
}
return entry;
}),
};
addConditionally(feed, "id", "id", childs);
addConditionally(feed, "title", "title", childs);
var href = (_a = getOneElement("link", childs)) === null || _a === void 0 ? void 0 : _a.attribs.href;
if (href) {
feed.link = href;
}
addConditionally(feed, "description", "subtitle", childs);
var updated = fetch("updated", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "email", childs, true);
return feed;
}
/**
* Parse a RSS feed.
*
* @param feedRoot The root of the feed.
* @returns The parsed feed.
*/
function getRssFeed(feedRoot) {
var _a, _b;
var childs = (_b = (_a = getOneElement("channel", feedRoot.children)) === null || _a === void 0 ? void 0 : _a.children) !== null && _b !== void 0 ? _b : [];
var feed = {
type: feedRoot.name.substr(0, 3),
id: "",
items: (0, legacy_1.getElementsByTagName)("item", feedRoot.children).map(function (item) {
var children = item.children;
var entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "guid", children);
addConditionally(entry, "title", "title", children);
addConditionally(entry, "link", "link", children);
addConditionally(entry, "description", "description", children);
var pubDate = fetch("pubDate", children);
if (pubDate)
entry.pubDate = new Date(pubDate);
return entry;
}),
};
addConditionally(feed, "title", "title", childs);
addConditionally(feed, "link", "link", childs);
addConditionally(feed, "description", "description", childs);
var updated = fetch("lastBuildDate", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "managingEditor", childs, true);
return feed;
}
var MEDIA_KEYS_STRING = ["url", "type", "lang"];
var MEDIA_KEYS_INT = [
"fileSize",
"bitrate",
"framerate",
"samplingrate",
"channels",
"duration",
"height",
"width",
];
/**
* Get all media elements of a feed item.
*
* @param where Nodes to search in.
* @returns Media elements.
*/
function getMediaElements(where) {
return (0, legacy_1.getElementsByTagName)("media:content", where).map(function (elem) {
var attribs = elem.attribs;
var media = {
medium: attribs.medium,
isDefault: !!attribs.isDefault,
};
for (var _i = 0, MEDIA_KEYS_STRING_1 = MEDIA_KEYS_STRING; _i < MEDIA_KEYS_STRING_1.length; _i++) {
var attrib = MEDIA_KEYS_STRING_1[_i];
if (attribs[attrib]) {
media[attrib] = attribs[attrib];
}
}
for (var _a = 0, MEDIA_KEYS_INT_1 = MEDIA_KEYS_INT; _a < MEDIA_KEYS_INT_1.length; _a++) {
var attrib = MEDIA_KEYS_INT_1[_a];
if (attribs[attrib]) {
media[attrib] = parseInt(attribs[attrib], 10);
}
}
if (attribs.expression) {
media.expression =
attribs.expression;
}
return media;
});
}
/**
* Get one element by tag name.
*
* @param tagName Tag name to look for
* @param node Node to search in
* @returns The element or null
*/
function getOneElement(tagName, node) {
return (0, legacy_1.getElementsByTagName)(tagName, node, true, 1)[0];
}
/**
* Get the text content of an element with a certain tag name.
*
* @param tagName Tag name to look for.
* @param where Node to search in.
* @param recurse Whether to recurse into child nodes.
* @returns The text content of the element.
*/
function fetch(tagName, where, recurse) {
if (recurse === void 0) { recurse = false; }
return (0, stringify_1.textContent)((0, legacy_1.getElementsByTagName)(tagName, where, recurse, 1)).trim();
}
/**
* Adds a property to an object if it has a value.
*
* @param obj Object to be extended
* @param prop Property name
* @param tagName Tag name that contains the conditionally added property
* @param where Element to search for the property
* @param recurse Whether to recurse into child nodes.
*/
function addConditionally(obj, prop, tagName, where, recurse) {
if (recurse === void 0) { recurse = false; }
var val = fetch(tagName, where, recurse);
if (val)
obj[prop] = val;
}
/**
* Checks if an element is a feed root node.
*
* @param value The name of the element to check.
* @returns Whether an element is a feed root node.
*/
function isValidFeed(value) {
return value === "rss" || value === "feed" || value === "rdf:RDF";
}

View File

@@ -0,0 +1,51 @@
import { Node } from "domhandler";
/**
* Given an array of nodes, remove any member that is contained by another.
*
* @param nodes Nodes to filter.
* @returns Remaining nodes that aren't subtrees of each other.
*/
export declare function removeSubsets(nodes: Node[]): Node[];
export declare const enum DocumentPosition {
DISCONNECTED = 1,
PRECEDING = 2,
FOLLOWING = 4,
CONTAINS = 8,
CONTAINED_BY = 16
}
/**
* Compare the position of one node against another node in any other document.
* The return value is a bitmask with the following values:
*
* Document order:
* > There is an ordering, document order, defined on all the nodes in the
* > document corresponding to the order in which the first character of the
* > XML representation of each node occurs in the XML representation of the
* > document after expansion of general entities. Thus, the document element
* > node will be the first node. Element nodes occur before their children.
* > Thus, document order orders element nodes in order of the occurrence of
* > their start-tag in the XML (after expansion of entities). The attribute
* > nodes of an element occur after the element and before its children. The
* > relative order of attribute nodes is implementation-dependent./
*
* Source:
* http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
*
* @param nodeA The first node to use in the comparison
* @param nodeB The second node to use in the comparison
* @returns A bitmask describing the input nodes' relative position.
*
* See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
* a description of these values.
*/
export declare function compareDocumentPosition(nodeA: Node, nodeB: Node): number;
/**
* Sort an array of nodes based on their relative position in the document and
* remove any duplicate nodes. If the array contains nodes that do not belong
* to the same document, sort order is unspecified.
*
* @param nodes Array of DOM nodes.
* @returns Collection of unique nodes, sorted in document order.
*/
export declare function uniqueSort<T extends Node>(nodes: T[]): T[];
//# sourceMappingURL=helpers.d.ts.map

Some files were not shown because too many files have changed in this diff Show More