Last commit july 5th

This commit is contained in:
2024-07-05 13:46:23 +02:00
parent dad0d86e8c
commit b0e4dfbb76
24982 changed files with 2621219 additions and 413 deletions

21
spa/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.

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

@@ -0,0 +1,199 @@
<div align="center">
<img src="./logo/logo-web.svg" width="348.61" height="100" alt=""/>
</div>
# SVGO [![npm](https://img.shields.io/npm/v/svgo)](https://npmjs.org/package/svgo) [![chat](https://img.shields.io/discord/815166721315831868)](https://discord.gg/z8jX8NYxrE) [![docs](https://img.shields.io/badge/docs-svgo.dev-blue)](https://svgo.dev/)
SVGO, short for **SVG O**ptimizer, is a Node.js library and command-line application for optimizing SVG files.
## Why?
SVG files, especially those exported from vector editors, usually contain a lot of redundant information. This includes editor metadata, comments, hidden elements, default or suboptimal values, and other stuff that can be safely removed or converted without impacting rendering.
## Installation
You can install SVGO globally through npm, yarn, or pnpm. Alternatively, drop the global flag (`global`/`-g`) to use it in your Node.js project.
```sh
# npm
npm install -g svgo
# yarn
yarn global add svgo
# pnpm
pnpm add -g svgo
```
## Command-line usage
Process single files:
```sh
svgo one.svg two.svg -o one.min.svg two.min.svg
```
Process a directory of files recursively with `-f`/`--folder`:
```sh
svgo -f path/to/directory_with_svgs -o path/to/output_directory
```
Help for advanced usage:
```sh
svgo --help
```
## Configuration
SVGO has a plugin architecture. You can read more about all plugins in [Plugins | SVGO Documentation](https://svgo.dev/docs/plugins/), and the default plugins in [Preset Default | SVGO Documentation](https://svgo.dev/docs/preset-default/).
SVGO reads the configuration from `svgo.config.js` or the `--config path/to/config.js` command-line option. Some other parameters can be configured though command-line options too.
**`svgo.config.js`**
```js
module.exports = {
multipass: false, // boolean
datauri: 'base64', // 'base64'|'enc'|'unenc'
js2svg: {
indent: 4, // number
pretty: false, // boolean
},
plugins: [
'preset-default', // built-in plugins enabled by default
'prefixIds', // enable built-in plugins by name
// enable built-in plugins with an object to configure plugins
{
name: 'prefixIds',
params: {
prefix: 'uwu',
},
},
],
};
```
### Default preset
Instead of configuring SVGO from scratch, you can tweak the default preset to suit your needs by configuring or disabling the respective plugin.
**`svgo.config.js`**
```js
module.exports = {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
// disable a default plugin
removeViewBox: false,
// customize the params of a default plugin
inlineStyles: {
onlyMatchedOnce: false,
},
},
},
},
],
};
```
You can find a list of the default plugins in the order they run in [Preset Default | SVGO Documentation](https://svgo.dev/docs/preset-default/#plugins-list).
### Custom plugins
You can also specify custom plugins:
**`svgo.config.js`**
```js
const importedPlugin = require('./imported-plugin');
module.exports = {
plugins: [
// plugin imported from another JavaScript file
importedPlugin,
// plugin defined inline
{
name: 'customPlugin',
params: {
paramName: 'paramValue',
},
fn: (ast, params, info) => {},
},
],
};
```
## 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, {
path: 'path-to.svg', // recommended
multipass: true, // all other config fields are available here
});
const optimizedSvgString = result.data;
```
### loadConfig
If you write a tool on top of SVGO you may want to resolve the `svgo.config.js` file.
```js
const { loadConfig } = require('svgo');
const config = await loadConfig();
```
You can also specify a path and customize the current working directory.
```js
const config = await loadConfig(configFile, cwd);
```
## Other ways to use SVGO
| Method | Reference |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Web app | [SVGOMG](https://jakearchibald.github.io/svgomg/) |
| Grunt task | [grunt-svgmin](https://github.com/sindresorhus/grunt-svgmin) |
| Gulp task | [gulp-svgmin](https://github.com/ben-eb/gulp-svgmin) |
| Webpack loader | [image-minimizer-webpack-plugin](https://github.com/webpack-contrib/image-minimizer-webpack-plugin/#optimize-with-svgo) |
| PostCSS plugin | [postcss-svgo](https://github.com/cssnano/cssnano/tree/master/packages/postcss-svgo) |
| Inkscape plugin | [inkscape-svgo](https://github.com/konsumer/inkscape-svgo) |
| Sketch plugin | [svgo-compressor](https://github.com/BohemianCoding/svgo-compressor) |
| Rollup plugin | [rollup-plugin-svgo](https://github.com/porsager/rollup-plugin-svgo) |
| Visual Studio Code plugin | [vscode-svgo](https://github.com/1000ch/vscode-svgo) |
| Atom plugin | [atom-svgo](https://github.com/1000ch/atom-svgo) |
| Sublime plugin | [Sublime-svgo](https://github.com/1000ch/Sublime-svgo) |
| Figma plugin | [Advanced SVG Export](https://www.figma.com/c/plugin/782713260363070260/Advanced-SVG-Export) |
| Linux app | [Oh My SVG](https://github.com/sonnyp/OhMySVG) |
| Browser extension | [SVG Gobbler](https://github.com/rossmoody/svg-gobbler) |
| API | [Vector Express](https://github.com/smidyo/vectorexpress-api#convertor-svgo) |
## Donors
| [<img src="https://sheetjs.com/sketch128.png" width="80">](https://sheetjs.com/) | [<img src="https://raw.githubusercontent.com/fontello/fontello/8.0.0/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/main/LICENSE).
Logo by [André Castillo](https://github.com/DerianAndre).

10
spa/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);
});

2058
spa/node_modules/svgo/dist/svgo-node.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

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

File diff suppressed because one or more lines are too long

57
spa/node_modules/svgo/lib/builtin.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
'use strict';
exports.builtin = [
require('../plugins/preset-default.js'),
require('../plugins/addAttributesToSVGElement.js'),
require('../plugins/addClassesToSVGElement.js'),
require('../plugins/cleanupAttrs.js'),
require('../plugins/cleanupEnableBackground.js'),
require('../plugins/cleanupIds.js'),
require('../plugins/cleanupListOfValues.js'),
require('../plugins/cleanupNumericValues.js'),
require('../plugins/collapseGroups.js'),
require('../plugins/convertColors.js'),
require('../plugins/convertEllipseToCircle.js'),
require('../plugins/convertOneStopGradients.js'),
require('../plugins/convertPathData.js'),
require('../plugins/convertShapeToPath.js'),
require('../plugins/convertStyleToAttrs.js'),
require('../plugins/convertTransform.js'),
require('../plugins/mergeStyles.js'),
require('../plugins/inlineStyles.js'),
require('../plugins/mergePaths.js'),
require('../plugins/minifyStyles.js'),
require('../plugins/moveElemsAttrsToGroup.js'),
require('../plugins/moveGroupAttrsToElems.js'),
require('../plugins/prefixIds.js'),
require('../plugins/removeAttributesBySelector.js'),
require('../plugins/removeAttrs.js'),
require('../plugins/removeComments.js'),
require('../plugins/removeDesc.js'),
require('../plugins/removeDimensions.js'),
require('../plugins/removeDoctype.js'),
require('../plugins/removeEditorsNSData.js'),
require('../plugins/removeElementsByAttr.js'),
require('../plugins/removeEmptyAttrs.js'),
require('../plugins/removeEmptyContainers.js'),
require('../plugins/removeEmptyText.js'),
require('../plugins/removeHiddenElems.js'),
require('../plugins/removeMetadata.js'),
require('../plugins/removeNonInheritableGroupAttrs.js'),
require('../plugins/removeOffCanvasPaths.js'),
require('../plugins/removeRasterImages.js'),
require('../plugins/removeScriptElement.js'),
require('../plugins/removeStyleElement.js'),
require('../plugins/removeTitle.js'),
require('../plugins/removeUnknownsAndDefaults.js'),
require('../plugins/removeUnusedNS.js'),
require('../plugins/removeUselessDefs.js'),
require('../plugins/removeUselessStrokeAndFill.js'),
require('../plugins/removeViewBox.js'),
require('../plugins/removeXlink.js'),
require('../plugins/removeXMLNS.js'),
require('../plugins/removeXMLProcInst.js'),
require('../plugins/reusePaths.js'),
require('../plugins/sortAttrs.js'),
require('../plugins/sortDefsChildren.js'),
];

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

@@ -0,0 +1,262 @@
'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
* @typedef {import('./types').XastChild} XastChild
*/
// @ts-ignore sax will be replaced with something else later
const SAX = require('@trysound/sax');
const { textElems } = require('../plugins/_collections');
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 = { type: 'root', children: [] };
/**
* @type {XastParent}
*/
let current = root;
/**
* @type {XastParent[]}
*/
const stack = [root];
/**
* @type {(node: XastChild) => void}
*/
const pushToContent = (node) => {
// TODO remove legacy parentNode in v4
Object.defineProperty(node, 'parentNode', {
writable: true,
value: current,
});
current.children.push(node);
};
/**
* @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;
}
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.has(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;

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

@@ -0,0 +1,380 @@
'use strict';
const { removeLeadingZero, toFixed } = require('./svgo/tools');
/**
* @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]}
*/
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) => PathDataItem[]}
*/
const parsePathData = (string) => {
/**
* @type {PathDataItem[]}
*/
const pathData = [];
/**
* @type {?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 treated 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) => {
* roundedStr: string,
* rounded: number
* }}
*/
const roundAndStringify = (number, precision) => {
if (precision != null) {
number = toFixed(number, precision);
}
return {
roundedStr: removeLeadingZero(number),
rounded: number,
};
};
/**
* 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 previous;
for (let i = 0; i < args.length; i++) {
const { roundedStr, rounded } = roundAndStringify(args[i], precision);
if (
disableSpaceAfterFlags &&
(command === 'A' || command === 'a') &&
// consider combined arcs
(i % 7 === 4 || i % 7 === 5)
) {
result += roundedStr;
} else if (i === 0 || rounded < 0) {
// avoid space before first and negative numbers
result += roundedStr;
} else if (
!Number.isInteger(previous) &&
rounded != 0 &&
rounded < 1 &&
rounded > -1
) {
// remove space before decimal with zero whole
// only when previous number is also decimal
result += roundedStr;
} else {
result += ` ${roundedStr}`;
}
previous = rounded;
}
return result;
};
/**
* @typedef {{
* pathData: PathDataItem[];
* precision?: number;
* disableSpaceAfterFlags?: boolean;
* }} StringifyPathDataOptions
*/
/**
* @param {StringifyPathDataOptions} options
* @returns {string}
*/
const stringifyPathData = ({ pathData, precision, disableSpaceAfterFlags }) => {
if (pathData.length === 1) {
const { command, args } = pathData[0];
return (
command + stringifyArgs(command, args, precision, disableSpaceAfterFlags)
);
}
let result = '';
let prev = { ...pathData[0] };
// match leading moveto with following lineto
if (pathData[1].command === 'L') {
prev.command = 'M';
} else if (pathData[1].command === 'l') {
prev.command = 'm';
}
for (let i = 1; i < pathData.length; i++) {
const { command, args } = pathData[i];
if (
(prev.command === command &&
prev.command !== 'M' &&
prev.command !== 'm') ||
// combine matching moveto and lineto sequences
(prev.command === 'M' && command === 'L') ||
(prev.command === 'm' && command === 'l')
) {
prev.args = [...prev.args, ...args];
if (i === pathData.length - 1) {
result +=
prev.command +
stringifyArgs(
prev.command,
prev.args,
precision,
disableSpaceAfterFlags,
);
}
} else {
result +=
prev.command +
stringifyArgs(
prev.command,
prev.args,
precision,
disableSpaceAfterFlags,
);
if (i === pathData.length - 1) {
result +=
command +
stringifyArgs(command, args, precision, disableSpaceAfterFlags);
} else {
prev = { command, args };
}
}
}
return result;
};
exports.stringifyPathData = stringifyPathData;

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

@@ -0,0 +1,295 @@
'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');
/**
* @typedef {{
* indent: string,
* textContext: ?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,
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) => 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 = {
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.endsWith('\n')) {
svg += eol;
}
return svg;
};
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) => {
// 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.has(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)
);
};

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

@@ -0,0 +1,336 @@
'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 csstree = require('css-tree');
const csswhat = require('css-what');
const {
syntax: { specificity },
} = require('csso');
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) => {
/**
* @type {StylesheetDeclaration[]}
*/
const declarations = [];
// collect declarations
ruleNode.block.children.forEach((cssNode) => {
if (cssNode.type === 'Declaration') {
declarations.push({
name: cssNode.property,
value: csstree.generate(cssNode.value),
important: cssNode.important === true,
});
}
});
/** @type {StylesheetRule[]} */
const rules = [];
csstree.walk(ruleNode.prelude, (node) => {
if (node.type === 'Selector') {
const newNode = csstree.clone(node);
let hasPseudoClasses = false;
csstree.walk(newNode, (pseudoClassNode, item, list) => {
if (pseudoClassNode.type === 'PseudoClassSelector') {
hasPseudoClasses = true;
list.remove(item);
}
});
rules.push({
specificity: specificity(node),
dynamic: hasPseudoClasses || dynamic,
// compute specificity from original node to consider pseudo classes
selector: csstree.generate(newNode),
declarations,
});
}
});
return rules;
};
/**
* @type {(css: string, dynamic: boolean) => StylesheetRule[]}
*/
const parseStylesheet = (css, dynamic) => {
/** @type {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' ||
cssNode.name === '-webkit-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) => StylesheetDeclaration[]}
*/
const parseStyleDeclarations = (css) => {
/** @type {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;
};
/**
* @param {Stylesheet} stylesheet
* @param {XastElement} node
* @returns {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.has(name)) {
computedStyle[name] = { type: 'static', inherited: false, value };
importantStyles.set(name, false);
}
}
// collect matching rules
for (const { selector, declarations, dynamic } of stylesheet.rules) {
if (matches(node, selector)) {
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 selector specificities.
* Derived from https://github.com/keeganstreet/specificity/blob/8757133ddd2ed0163f120900047ff0f92760b536/specificity.js#L207
*
* @param {Specificity} a
* @param {Specificity} b
* @returns {number}
*/
const compareSpecificity = (a, b) => {
for (let i = 0; i < 4; i += 1) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
return 0;
};
exports.compareSpecificity = compareSpecificity;
/**
* @type {(root: XastRoot) => Stylesheet}
*/
const collectStylesheet = (root) => {
/** @type {StylesheetRule[]} */
const rules = [];
/** @type {Map<XastElement, XastParent>} */
const parents = new Map();
visit(root, {
element: {
enter: (node, parentNode) => {
parents.set(node, parentNode);
if (node.name !== 'style') {
return;
}
if (
node.attributes.type == null ||
node.attributes.type === '' ||
node.attributes.type === 'text/css'
) {
const dynamic =
node.attributes.media != null && node.attributes.media !== 'all';
for (const child of node.children) {
if (child.type === 'text' || child.type === 'cdata') {
rules.push(...parseStylesheet(child.value, dynamic));
}
}
}
},
},
});
// sort by selectors specificity
rules.sort((a, b) => compareSpecificity(a.specificity, b.specificity));
return { rules, parents };
};
exports.collectStylesheet = collectStylesheet;
/**
* @param {Stylesheet} stylesheet
* @param {XastElement} node
* @returns {ComputedStyles}
*/
const computeStyle = (stylesheet, node) => {
const { parents } = stylesheet;
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 &&
inheritableAttrs.has(name) &&
!presentationNonInheritableGroupAttrs.has(name)
) {
computedStyles[name] = { ...computed, inherited: true };
}
}
parent = parents.get(parent);
}
return computedStyles;
};
exports.computeStyle = computeStyle;
/**
* Determines if the CSS selector includes or traverses the given attribute.
*
* Classes and IDs are generated as attribute selectors, so you can check for
* if a `.class` or `#id` is included by passing `name=class` or `name=id`
* respectively.
*
* @param {csstree.ListItem<csstree.CssNode>|string} selector
* @param {string} name
* @param {?string} value
* @param {boolean} traversed
* @returns {boolean}
*/
const includesAttrSelector = (
selector,
name,
value = null,
traversed = false,
) => {
const selectors =
typeof selector === 'string'
? csswhat.parse(selector)
: csswhat.parse(csstree.generate(selector.data));
for (const subselector of selectors) {
const hasAttrSelector = subselector.some((segment, index) => {
if (traversed) {
if (index === subselector.length - 1) {
return false;
}
const isNextTraversal = csswhat.isTraversal(subselector[index + 1]);
if (!isNextTraversal) {
return false;
}
}
if (segment.type !== 'attribute' || segment.name !== name) {
return false;
}
return value == null ? true : segment.value === value;
});
if (hasAttrSelector) {
return true;
}
}
return false;
};
exports.includesAttrSelector = includesAttrSelector;

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

@@ -0,0 +1,85 @@
'use strict';
const os = require('os');
const fs = require('fs');
const { pathToFileURL } = require('url');
const path = require('path');
const { optimize: optimizeAgnostic } = require('./svgo.js');
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 {
// 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;
}
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;

69
spa/node_modules/svgo/lib/svgo.d.ts generated vendored Normal file
View File

@@ -0,0 +1,69 @@
import type { StringifyOptions, DataUri, Plugin as PluginFn } from './types';
import type {
BuiltinsWithOptionalParams,
BuiltinsWithRequiredParams,
} from '../plugins/plugins-types';
type CustomPlugin = {
name: string;
fn: PluginFn<void>;
};
type PluginConfig =
| keyof BuiltinsWithOptionalParams
| {
[Name in keyof BuiltinsWithOptionalParams]: {
name: Name;
params?: BuiltinsWithOptionalParams[Name];
};
}[keyof BuiltinsWithOptionalParams]
| {
[Name in keyof BuiltinsWithRequiredParams]: {
name: Name;
params: BuiltinsWithRequiredParams[Name];
};
}[keyof BuiltinsWithRequiredParams]
| CustomPlugin;
export type Config = {
/** Can be used by plugins, for example prefixids */
path?: string;
/** Pass over SVGs multiple times to ensure all optimizations are applied. */
multipass?: boolean;
/** Precision of floating point numbers. Will be passed to each plugin that supports this param. */
floatPrecision?: number;
/**
* Plugins configuration
* ['preset-default'] is default
* Can also specify any builtin plugin
* ['sortAttrs', { name: 'prefixIds', params: { prefix: 'my-prefix' } }]
* Or custom
* [{ name: 'myPlugin', fn: () => ({}) }]
*/
plugins?: PluginConfig[];
/** Options for rendering optimized SVG from AST. */
js2svg?: StringifyOptions;
/** Output as Data URI string. */
datauri?: DataUri;
};
type Output = {
data: string;
};
/** The core of SVGO */
export declare function optimize(input: string, config?: Config): Output;
/**
* If you write a tool on top of svgo you might need a way to load svgo config.
*
* You can also specify relative or absolute path and customize current working directory.
*/
export declare function loadConfig(
configFile: string,
cwd?: string,
): Promise<Config>;
export declare function loadConfig(
configFile?: null,
cwd?: string,
): Promise<Config | null>;

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

@@ -0,0 +1,102 @@
'use strict';
const { parseSvg } = require('./parser.js');
const { stringifySvg } = require('./stringifier.js');
const { builtin } = require('./builtin.js');
const { invokePlugins } = require('./svgo/plugins.js');
const { encodeSVGDatauri } = require('./svgo/tools.js');
const pluginsMap = {};
for (const plugin of builtin) {
pluginsMap[plugin.name] = plugin;
}
const resolvePluginConfig = (plugin) => {
if (typeof plugin === 'string') {
// resolve builtin plugin specified as string
const builtinPlugin = pluginsMap[plugin];
if (builtinPlugin == null) {
throw Error(`Unknown builtin plugin "${plugin}" specified.`);
}
return {
name: plugin,
params: {},
fn: builtinPlugin.fn,
};
}
if (typeof plugin === 'object' && plugin != null) {
if (plugin.name == null) {
throw Error(`Plugin name should be specified`);
}
// use custom plugin implementation
let fn = plugin.fn;
if (fn == null) {
// resolve builtin plugin implementation
const builtinPlugin = pluginsMap[plugin.name];
if (builtinPlugin == null) {
throw Error(`Unknown builtin plugin "${plugin.name}" specified.`);
}
fn = builtinPlugin.fn;
}
return {
name: plugin.name,
params: plugin.params,
fn,
};
}
return null;
};
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 output = '';
const info = {};
if (config.path != null) {
info.path = config.path;
}
for (let i = 0; i < maxPassCount; i += 1) {
info.multipassCount = i;
const ast = parseSvg(input, config.path);
const plugins = config.plugins || ['preset-default'];
if (!Array.isArray(plugins)) {
throw Error(
'malformed config, `plugins` property must be an array.\nSee more info here: https://github.com/svg/svgo#configuration',
);
}
const resolvedPlugins = plugins
.filter((plugin) => plugin != null)
.map(resolvePluginConfig);
if (resolvedPlugins.length < plugins.length) {
console.warn(
'Warning: plugins list includes null or undefined elements, these will be ignored.',
);
}
const globalOverrides = {};
if (config.floatPrecision != null) {
globalOverrides.floatPrecision = config.floatPrecision;
}
invokePlugins(ast, info, resolvedPlugins, null, globalOverrides);
output = stringifySvg(ast, config.js2svg);
if (output.length < prevResultSize) {
input = output;
prevResultSize = output.length;
} else {
break;
}
}
if (config.datauri) {
output = encodeSVGDatauri(output, config.datauri);
}
return {
data: output,
};
};
exports.optimize = optimize;

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

@@ -0,0 +1,528 @@
'use strict';
const fs = require('fs');
const path = require('path');
const colors = require('picocolors');
const { loadConfig, optimize } = require('../svgo-node.js');
const { builtin } = require('../builtin.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, null, 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, null, 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, { 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');
let result;
try {
result = optimize(data, { ...config, ...info });
} catch (error) {
if (error.name === 'SvgoParserError') {
console.error(colors.red(error.toString()));
process.exit(1);
} else {
throw error;
}
}
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 == '-') {
process.stdout.write(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 time taken to optimize.
*
* @param {number} time time in milliseconds.
*/
function printTimeInfo(time) {
console.log(`Done in ${time} ms!`);
}
/**
* Write optimizing stats in a human-readable format.
*
* @param {number} inBytes size before optimization.
* @param {number} outBytes size after optimization.
*/
function printProfitInfo(inBytes, outBytes) {
const profitPercent = 100 - (outBytes * 100) / inBytes;
/** @type {[string, Function]} */
const ui = profitPercent < 0 ? ['+', colors.red] : ['-', colors.green];
console.log(
Math.round((inBytes / 1024) * 1000) / 1000 + ' KiB',
ui[0],
ui[1](Math.abs(Math.round(profitPercent * 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 = builtin
.sort((a, b) => a.name.localeCompare(b.name))
.map((plugin) => ` [ ${colors.green(plugin.name)} ] ${plugin.description}`)
.join('\n');
console.log('Currently available plugins:\n' + list);
}
module.exports.checkIsDir = checkIsDir;

View File

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

120
spa/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;

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

@@ -0,0 +1,61 @@
'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?.[plugin.name];
if (override === false) {
continue;
}
const params = { ...plugin.params, ...globalOverrides, ...override };
const visitor = plugin.fn(ast, params, info);
if (visitor != null) {
visit(ast, visitor);
}
}
};
exports.invokePlugins = invokePlugins;
const createPreset = ({ name, plugins }) => {
return {
name,
fn: (ast, params, info) => {
const { floatPrecision, overrides } = params;
const globalOverrides = {};
if (floatPrecision != null) {
globalOverrides.floatPrecision = floatPrecision;
}
if (overrides) {
const pluginNames = plugins.map(({ name }) => name);
for (const pluginName of Object.keys(overrides)) {
if (!pluginNames.includes(pluginName)) {
console.warn(
`You are trying to configure ${pluginName} which is not part of ${name}.\n` +
`Try to put it before or after, for example\n\n` +
`plugins: [\n` +
` {\n` +
` name: '${name}',\n` +
` },\n` +
` '${pluginName}'\n` +
`]\n`,
);
}
}
}
invokePlugins(ast, info, plugins, overrides, globalOverrides);
},
};
};
exports.createPreset = createPreset;

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

@@ -0,0 +1,245 @@
'use strict';
/**
* @typedef {import('../../lib/types').XastElement} XastElement
* @typedef {import('../types').PathDataCommand} PathDataCommand
* @typedef {import('../types').DataUri} DataUri
*/
const { attrsGroups, referencesProps } = require('../../plugins/_collections');
const regReferencesUrl = /\burl\((["'])?#(.+?)\1\)/g;
const regReferencesHref = /^#(.+?)$/;
const regReferencesBegin = /(\w+)\.[a-zA-Z]/;
/**
* Encode plain SVG data string into Data URI string.
*
* @type {(str: string, type?: DataUri) => 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: 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.
*
* @param {number} value
* @returns {string}
* @example
* 0.5 → .5
* -0.5 → -.5
*/
const removeLeadingZero = (value) => {
const strValue = value.toString();
if (0 < value && value < 1 && strValue.startsWith('0')) {
return strValue.slice(1);
}
if (-1 < value && value < 0 && strValue[1] === '0') {
return strValue[0] + strValue.slice(2);
}
return strValue;
};
exports.removeLeadingZero = removeLeadingZero;
/**
* If the current node contains any scripts. This does not check parents or
* children of the node, only the properties and attributes of the node itself.
*
* @param {XastElement} node Current node to check against.
* @returns {boolean} If the current node contains scripts.
*/
const hasScripts = (node) => {
if (node.name === 'script' && node.children.length !== 0) {
return true;
}
if (node.name === 'a') {
const hasJsLinks = Object.entries(node.attributes).some(
([attrKey, attrValue]) =>
(attrKey === 'href' || attrKey.endsWith(':href')) &&
attrValue != null &&
attrValue.trimStart().startsWith('javascript:'),
);
if (hasJsLinks) {
return true;
}
}
const eventAttrs = [
...attrsGroups.animationEvent,
...attrsGroups.documentEvent,
...attrsGroups.documentElementEvent,
...attrsGroups.globalEvent,
...attrsGroups.graphicalEvent,
];
return eventAttrs.some((attr) => node.attributes[attr] != null);
};
exports.hasScripts = hasScripts;
/**
* For example, a string that contains one or more of following would match and
* return true:
*
* * `url(#gradient001)`
* * `url('#gradient001')`
*
* @param {string} body
* @returns {boolean} If the given string includes a URL reference.
*/
const includesUrlReference = (body) => {
return new RegExp(regReferencesUrl).test(body);
};
exports.includesUrlReference = includesUrlReference;
/**
* @param {string} attribute
* @param {string} value
* @returns {string[]}
*/
const findReferences = (attribute, value) => {
const results = [];
if (referencesProps.has(attribute)) {
const matches = value.matchAll(regReferencesUrl);
for (const match of matches) {
results.push(match[2]);
}
}
if (attribute === 'href' || attribute.endsWith(':href')) {
const match = regReferencesHref.exec(value);
if (match != null) {
results.push(match[1]);
}
}
if (attribute === 'begin') {
const match = regReferencesBegin.exec(value);
if (match != null) {
results.push(match[1]);
}
}
return results.map((body) => decodeURI(body));
};
exports.findReferences = findReferences;
/**
* Does the same as {@link Number.toFixed} but without casting
* the return value to a string.
*
* @param {number} num
* @param {number} precision
* @returns {number}
*/
const toFixed = (num, precision) => {
const pow = 10 ** precision;
return Math.round(num * pow) / pow;
};
exports.toFixed = toFixed;

174
spa/node_modules/svgo/lib/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,174 @@
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: XastChild[];
};
export type XastChild =
| XastDoctype
| XastInstruction
| XastComment
| XastCdata
| XastText
| XastElement;
export type XastRoot = {
type: 'root';
children: 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];
export type StylesheetDeclaration = {
name: string;
value: string;
important: boolean;
};
export type StylesheetRule = {
dynamic: boolean;
selector: string;
specificity: Specificity;
declarations: StylesheetDeclaration[];
};
export type Stylesheet = {
rules: 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: number[];
};
export type DataUri = 'base64' | 'enc' | 'unenc';

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

@@ -0,0 +1,87 @@
'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) => XastChild[]}
*/
const querySelectorAll = (node, selector) => {
return selectAll(selector, node, cssSelectOptions);
};
exports.querySelectorAll = querySelectorAll;
/**
* @type {(node: XastNode, selector: string) => ?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;
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;
/**
* @param {XastChild} node
* @param {XastParent} parentNode
*/
const detachNodeFromParent = (node, parentNode) => {
// avoid splice to not break for loops
parentNode.children = parentNode.children.filter((child) => child !== node);
};
exports.detachNodeFromParent = detachNodeFromParent;

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
spa/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
spa/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
spa/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
spa/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
}
}
]
}

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
spa/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.

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

@@ -0,0 +1,264 @@
# 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`](https://github.com/jquery/sizzle),
[`Qwery`](https://github.com/ded/qwery) and
[`NWMatcher`](https://github.com/dperini/nwmatcher/) and .
- 🥼 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.
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),
[`Qwery`](https://github.com/ded/qwery) and
[`NWMatcher`](https://github.com/dperini/nwmatcher/).)
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-class.
- `relativeSelector`: By default, selectors are relative to the `context`,
which means that no parent elements of the context will be matched. (Eg.
`a b c` with context `b` will never give any results.) If `relativeSelector`
is set to `false`, selectors won't be
[absolutized](http://www.w3.org/TR/selectors4/#absolutizing) and selectors
can test for parent elements outside of the `context`.
- `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`.
- `pseudos`: A map of pseudo-class names to functions or strings.
#### 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 type { CompiledQuery, InternalOptions } from "./types.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["attributes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACjE,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,236 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.attributeRules = void 0;
var boolbase_1 = __importDefault(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.default.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.default.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.default.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.default.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);
};
},
};
//# sourceMappingURL=attributes.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
import { Selector } from "css-what";
import type { CompiledQuery, InternalOptions, InternalSelector } from "./types.js";
/**
* 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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["compile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,QAAQ,EAAgB,MAAM,UAAU,CAAC;AAQzD,OAAO,KAAK,EACR,aAAa,EACb,eAAe,EACf,gBAAgB,EACnB,MAAM,YAAY,CAAC;AAEpB;;;;;;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;AAqDD,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,CAsD5B"}

View File

@@ -0,0 +1,151 @@
"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;
};
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 = __importDefault(require("boolbase"));
var sort_js_1 = __importStar(require("./sort.js"));
var general_js_1 = require("./general.js");
var subselects_js_1 = require("./pseudo-selectors/subselects.js");
/**
* 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_js_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 === css_what_1.SelectorType.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.4.1. Absolutizing a 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_js_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, sort_js_1.isTraversal)(t[0]) &&
t[0].type !== css_what_1.SelectorType.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.forEach(sort_js_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]);
// Check if the selector is relative
if (options.relativeSelector !== false) {
absolutize(token, options, finalContext);
}
else if (token.some(function (t) { return t.length > 0 && (0, sort_js_1.isTraversal)(t[0]); })) {
throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");
}
var shouldTestNextSiblings = false;
var query = token
.map(function (rules) {
if (rules.length >= 2) {
var first = rules[0], second = rules[1];
if (first.type !== css_what_1.SelectorType.Pseudo ||
first.name !== "scope") {
// Ignore
}
else if (isArrayContext &&
second.type === css_what_1.SelectorType.Descendant) {
rules[1] = FLEXIBLE_DESCENDANT_TOKEN;
}
else if (second.type === css_what_1.SelectorType.Adjacent ||
second.type === css_what_1.SelectorType.Sibling) {
shouldTestNextSiblings = true;
}
}
return compileRules(rules, options, finalContext);
})
.reduce(reduceRules, boolbase_1.default.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.default.falseFunc
? boolbase_1.default.falseFunc
: (0, general_js_1.compileGeneralSelector)(previous, rule, options, context, compileToken);
}, (_a = options.rootFunc) !== null && _a !== void 0 ? _a : boolbase_1.default.trueFunc);
}
function reduceRules(a, b) {
if (b === boolbase_1.default.falseFunc || a === boolbase_1.default.trueFunc) {
return a;
}
if (a === boolbase_1.default.falseFunc || b === boolbase_1.default.trueFunc) {
return b;
}
return function combine(elem) {
return a(elem) || b(elem);
};
}
//# sourceMappingURL=compile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compile.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["compile.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAyD;AACzD,sDAAgC;AAChC,mDAAmD;AACnD,2CAAsD;AACtD,kEAG0C;AAO1C;;;;;;GAMG;AACH,SAAgB,OAAO,CACnB,QAA+B,EAC/B,OAA2C,EAC3C,OAAuB;IAEvB,IAAM,IAAI,GAAG,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACvD,OAAO,IAAA,2BAAW,EAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC;AAPD,0BAOC;AAED,SAAgB,aAAa,CACzB,QAA+B,EAC/B,OAA2C,EAC3C,OAAuB;IAEvB,IAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,gBAAK,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IACxE,OAAO,YAAY,CAAoB,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AACpE,CAAC;AAPD,sCAOC;AAED,SAAS,mBAAmB,CAAC,CAAmB;IAC5C,OAAO,CACH,CAAC,CAAC,IAAI,KAAK,uBAAY,CAAC,MAAM;QAC9B,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO;YACf,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;gBAClB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,UAAC,IAAI,IAAK,OAAA,IAAI,CAAC,IAAI,CA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C;AACN,CAAC"}

View File

@@ -0,0 +1,7 @@
import type { CompiledQuery, InternalOptions } from "./types.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["attributes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACjE,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,222 @@
import boolbase from "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
*/
const 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
*/
const 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
*/
export const attributeRules = {
equals(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length === value.length &&
attr.toLowerCase() === value &&
next(elem));
};
}
return (elem) => adapter.getAttributeValue(elem, name) === value && next(elem);
},
hyphen(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
const len = value.length;
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function hyphenIC(elem) {
const 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) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
(attr.length === len || attr.charAt(len) === "-") &&
attr.substr(0, len) === value &&
next(elem));
};
},
element(next, data, options) {
const { adapter } = options;
const { name, value } = data;
if (/\s/.test(value)) {
return boolbase.falseFunc;
}
const regex = new RegExp(`(?:^|\\s)${escapeRegex(value)}(?:$|\\s)`, shouldIgnoreCase(data, options) ? "i" : "");
return function element(elem) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= value.length &&
regex.test(attr) &&
next(elem));
};
},
exists(next, { name }, { adapter }) {
return (elem) => adapter.hasAttrib(elem, name) && next(elem);
},
start(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
const len = value.length;
if (len === 0) {
return boolbase.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= len &&
attr.substr(0, len).toLowerCase() === value &&
next(elem));
};
}
return (elem) => {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.startsWith(value)) &&
next(elem);
};
},
end(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
const len = -value.length;
if (len === 0) {
return boolbase.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
var _a;
return ((_a = adapter
.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.substr(len).toLowerCase()) === value && next(elem);
};
}
return (elem) => {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.endsWith(value)) &&
next(elem);
};
},
any(next, data, options) {
const { adapter } = options;
const { name, value } = data;
if (value === "") {
return boolbase.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
const regex = new RegExp(escapeRegex(value), "i");
return function anyIC(elem) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= value.length &&
regex.test(attr) &&
next(elem));
};
}
return (elem) => {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.includes(value)) &&
next(elem);
};
},
not(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
if (value === "") {
return (elem) => !!adapter.getAttributeValue(elem, name) && next(elem);
}
else if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
const attr = adapter.getAttributeValue(elem, name);
return ((attr == null ||
attr.length !== value.length ||
attr.toLowerCase() !== value) &&
next(elem));
};
}
return (elem) => adapter.getAttributeValue(elem, name) !== value && next(elem);
},
};
//# sourceMappingURL=attributes.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
import { Selector } from "css-what";
import type { CompiledQuery, InternalOptions, InternalSelector } from "./types.js";
/**
* 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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["compile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,QAAQ,EAAgB,MAAM,UAAU,CAAC;AAQzD,OAAO,KAAK,EACR,aAAa,EACb,eAAe,EACf,gBAAgB,EACnB,MAAM,YAAY,CAAC;AAEpB;;;;;;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;AAqDD,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,CAsD5B"}

View File

@@ -0,0 +1,115 @@
import { parse, SelectorType } from "css-what";
import boolbase from "boolbase";
import sortRules, { isTraversal } from "./sort.js";
import { compileGeneralSelector } from "./general.js";
import { ensureIsTag, PLACEHOLDER_ELEMENT, } from "./pseudo-selectors/subselects.js";
/**
* Compiles a selector to an executable function.
*
* @param selector Selector to compile.
* @param options Compilation options.
* @param context Optional context for the selector.
*/
export function compile(selector, options, context) {
const next = compileUnsafe(selector, options, context);
return ensureIsTag(next, options.adapter);
}
export function compileUnsafe(selector, options, context) {
const token = typeof selector === "string" ? parse(selector) : selector;
return compileToken(token, options, context);
}
function includesScopePseudo(t) {
return (t.type === SelectorType.Pseudo &&
(t.name === "scope" ||
(Array.isArray(t.data) &&
t.data.some((data) => data.some(includesScopePseudo)))));
}
const DESCENDANT_TOKEN = { type: SelectorType.Descendant };
const FLEXIBLE_DESCENDANT_TOKEN = {
type: "_flexibleDescendant",
};
const SCOPE_TOKEN = {
type: SelectorType.Pseudo,
name: "scope",
data: null,
};
/*
* CSS 4 Spec (Draft): 3.4.1. Absolutizing a Relative Selector
* http://www.w3.org/TR/selectors4/#absolutizing
*/
function absolutize(token, { adapter }, context) {
// TODO Use better check if the context is a document
const hasContext = !!(context === null || context === void 0 ? void 0 : context.every((e) => {
const parent = adapter.isTag(e) && adapter.getParent(e);
return e === PLACEHOLDER_ELEMENT || (parent && adapter.isTag(parent));
}));
for (const t of token) {
if (t.length > 0 &&
isTraversal(t[0]) &&
t[0].type !== SelectorType.Descendant) {
// Don't continue in else branch
}
else if (hasContext && !t.some(includesScopePseudo)) {
t.unshift(DESCENDANT_TOKEN);
}
else {
continue;
}
t.unshift(SCOPE_TOKEN);
}
}
export function compileToken(token, options, context) {
var _a;
token.forEach(sortRules);
context = (_a = options.context) !== null && _a !== void 0 ? _a : context;
const isArrayContext = Array.isArray(context);
const finalContext = context && (Array.isArray(context) ? context : [context]);
// Check if the selector is relative
if (options.relativeSelector !== false) {
absolutize(token, options, finalContext);
}
else if (token.some((t) => t.length > 0 && isTraversal(t[0]))) {
throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");
}
let shouldTestNextSiblings = false;
const query = token
.map((rules) => {
if (rules.length >= 2) {
const [first, second] = rules;
if (first.type !== SelectorType.Pseudo ||
first.name !== "scope") {
// Ignore
}
else if (isArrayContext &&
second.type === SelectorType.Descendant) {
rules[1] = FLEXIBLE_DESCENDANT_TOKEN;
}
else if (second.type === SelectorType.Adjacent ||
second.type === SelectorType.Sibling) {
shouldTestNextSiblings = true;
}
}
return compileRules(rules, options, finalContext);
})
.reduce(reduceRules, boolbase.falseFunc);
query.shouldTestNextSiblings = shouldTestNextSiblings;
return query;
}
function compileRules(rules, options, context) {
var _a;
return rules.reduce((previous, rule) => previous === boolbase.falseFunc
? boolbase.falseFunc
: compileGeneralSelector(previous, rule, options, context, compileToken), (_a = options.rootFunc) !== null && _a !== void 0 ? _a : boolbase.trueFunc);
}
function reduceRules(a, b) {
if (b === boolbase.falseFunc || a === boolbase.trueFunc) {
return a;
}
if (a === boolbase.falseFunc || b === boolbase.trueFunc) {
return b;
}
return function combine(elem) {
return a(elem) || b(elem);
};
}
//# sourceMappingURL=compile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compile.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["compile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAY,YAAY,EAAE,MAAM,U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AAW,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;IAE7C,KAAK,CAAC,sBAAsB,GAAG,sBAAsB,CAAC;IAEtD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,SAAS,YAAY,CACjB,KAAyB,EACzB,OAA2C,EAC3C,OAAgB;;IAEhB,OAAO,KAAK,CAAC,MAAM,CACf,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CACf,QAAQ,KAAK,QAAQ,CAAC,SAAS;QAC3B,CAAC,CAAC,QAAQ,CAAC,SAAS;QACpB,CAAC,CAAC,sBAAsB,CAClB,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,OAAO,EACP,YAAY,CACf,EACX,MAAA,OAAO,CAAC,QAAQ,mCAAI,QAAQ,CAAC,QAAQ,CACxC,CAAC;AACN,CAAC;AAED,SAAS,WAAW,CAChB,CAA6B,EAC7B,CAA6B;IAE7B,IAAI,CAAC,KAAK,QAAQ,CAAC,SAAS,IAAI,CAAC,KAAK,QAAQ,CAAC,QAAQ,EAAE;QACrD,OAAO,CAAC,CAAC;KACZ;IACD,IAAI,CAAC,KAAK,QAAQ,CAAC,SAAS,IAAI,CAAC,KAAK,QAAQ,CAAC,QAAQ,EAAE;QACrD,OAAO,CAAC,CAAC;KACZ;IAED,OAAO,SAAS,OAAO,CAAC,IAAI;QACxB,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC,CAAC;AACN,CAAC"}

View File

@@ -0,0 +1,3 @@
import type { CompiledQuery, InternalOptions, InternalSelector, CompileToken } from "./types.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["general.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAER,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,YAAY,EACf,MAAM,YAAY,CAAC;AAkBpB,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,144 @@
import { attributeRules } from "./attributes.js";
import { compilePseudoSelector } from "./pseudo-selectors/index.js";
import { SelectorType } from "css-what";
function getElementParent(node, adapter) {
const parent = adapter.getParent(node);
if (parent && adapter.isTag(parent)) {
return parent;
}
return null;
}
/*
* All available rules
*/
export function compileGeneralSelector(next, selector, options, context, compileToken) {
const { adapter, equals } = options;
switch (selector.type) {
case SelectorType.PseudoElement: {
throw new Error("Pseudo-elements are not supported by css-select");
}
case SelectorType.ColumnCombinator: {
throw new Error("Column combinators are not yet supported by css-select");
}
case 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 attributeRules[selector.action](next, selector, options);
}
case SelectorType.Pseudo: {
return compilePseudoSelector(next, selector, options, context, compileToken);
}
// Tags
case SelectorType.Tag: {
if (selector.namespace != null) {
throw new Error("Namespaced tag names are not yet supported by css-select");
}
let { name } = selector;
if (!options.xmlMode || options.lowerCaseTags) {
name = name.toLowerCase();
}
return function tag(elem) {
return adapter.getName(elem) === name && next(elem);
};
}
// Traversal
case SelectorType.Descendant: {
if (options.cacheResults === false ||
typeof WeakSet === "undefined") {
return function descendant(elem) {
let current = elem;
while ((current = getElementParent(current, adapter))) {
if (next(current)) {
return true;
}
}
return false;
};
}
// @ts-expect-error `ElementNode` is not extending object
const isFalseCache = new WeakSet();
return function cachedDescendant(elem) {
let current = elem;
while ((current = getElementParent(current, adapter))) {
if (!isFalseCache.has(current)) {
if (adapter.isTag(current) && next(current)) {
return true;
}
isFalseCache.add(current);
}
}
return false;
};
}
case "_flexibleDescendant": {
// Include element itself, only used while querying an array
return function flexibleDescendant(elem) {
let current = elem;
do {
if (next(current))
return true;
} while ((current = getElementParent(current, adapter)));
return false;
};
}
case SelectorType.Parent: {
return function parent(elem) {
return adapter
.getChildren(elem)
.some((elem) => adapter.isTag(elem) && next(elem));
};
}
case SelectorType.Child: {
return function child(elem) {
const parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(parent);
};
}
case SelectorType.Sibling: {
return function sibling(elem) {
const siblings = adapter.getSiblings(elem);
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) && next(currentSibling)) {
return true;
}
}
return false;
};
}
case SelectorType.Adjacent: {
if (adapter.prevElementSibling) {
return function adjacent(elem) {
const previous = adapter.prevElementSibling(elem);
return previous != null && next(previous);
};
}
return function adjacent(elem) {
const siblings = adapter.getSiblings(elem);
let lastElement;
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling)) {
lastElement = currentSibling;
}
}
return !!lastElement && next(lastElement);
};
}
case SelectorType.Universal: {
if (selector.namespace != null && selector.namespace !== "*") {
throw new Error("Namespaced universal selectors are not yet supported by css-select");
}
return next;
}
}
}
//# sourceMappingURL=general.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"general.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/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,GAAG,cAAc,CAAC;qBAChC;iBACJ;gBAED,OAAO,CAAC,CAAC,WAAW,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC;YAC9C,CAAC,CAAC;SACL;QACD,KAAK,YAAY,CAAC,SAAS,CAAC,CAAC;YACzB,IAAI,QAAQ,CAAC,SAAS,IAAI,IAAI,IAAI,QAAQ,CAAC,SAAS,KAAK,GAAG,EAAE;gBAC1D,MAAM,IAAI,KAAK,CACX,oEAAoE,CACvE,CAAC;aACL;YAED,OAAO,IAAI,CAAC;SACf;KACJ;AACL,CAAC"}

View File

@@ -0,0 +1,50 @@
import type { CompiledQuery, Options, Query, Adapter } from "./types.js";
export type { Options };
/**
* Compiles the query, returns a function.
*/
export declare const compile: <Node, ElementNode extends Node>(selector: string | import("css-what").Selector[][], options?: Options<Node, ElementNode> | undefined, context?: Node | Node[] | undefined) => CompiledQuery<Node>;
export declare const _compileUnsafe: <Node, ElementNode extends Node>(selector: string | import("css-what").Selector[][], options?: Options<Node, ElementNode> | undefined, context?: Node | Node[] | undefined) => CompiledQuery<ElementNode>;
export declare const _compileToken: <Node, ElementNode extends Node>(selector: import("./types.js").InternalSelector[][], options?: Options<Node, ElementNode> | undefined, context?: Node | Node[] | 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, ElementNode extends Node>(query: Query<ElementNode>, elements: Node | Node[], options?: Options<Node, 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, ElementNode extends Node>(query: Query<ElementNode>, elements: Node | Node[], options?: Options<Node, 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;
/** @deprecated Use the `pseudos` option instead. */
export { filters, pseudos, aliases } from "./pseudo-selectors/index.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["index.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EACR,aAAa,EACb,OAAO,EAEP,KAAK,EACL,OAAO,EAEV,MAAM,YAAY,CAAC;AAGpB,YAAY,EAAE,OAAO,EAAE,CAAC;AA0CxB;;GAEG;AACH,eAAO,MAAM,OAAO,oMAA0B,CAAC;AAC/C,eAAO,MAAM,cAAc,2MAA6B,CAAC;AACzD,eAAO,MAAM,aAAa,4MAA4B,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,yJASrB,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,SAAS,8JASrB,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,oDAAoD;AACpD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC"}

View File

@@ -0,0 +1,115 @@
import * as DomUtils from "domutils";
import boolbase from "boolbase";
import { compile as compileRaw, compileUnsafe, compileToken, } from "./compile.js";
import { getNextSiblings } from "./pseudo-selectors/subselects.js";
const defaultEquals = (a, b) => a === b;
const 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`.
const 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) {
const opts = convertOptionFormats(options);
return func(selector, opts, context);
};
}
/**
* Compiles the query, returns a function.
*/
export const compile = wrapCompile(compileRaw);
export const _compileUnsafe = wrapCompile(compileUnsafe);
export const _compileToken = wrapCompile(compileToken);
function getSelectorFunc(searchFunc) {
return function select(query, elements, options) {
const opts = convertOptionFormats(options);
if (typeof query !== "function") {
query = compileUnsafe(query, opts, elements);
}
const filteredElements = prepareContext(elements, opts.adapter, query.shouldTestNextSiblings);
return searchFunc(query, filteredElements, opts);
};
}
export function prepareContext(elems, adapter, 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);
}
function appendNextSiblings(elem, adapter) {
// Order matters because jQuery seems to check the children before the siblings
const elems = Array.isArray(elem) ? elem.slice(0) : [elem];
const elemsLength = elems.length;
for (let i = 0; i < elemsLength; i++) {
const nextSiblings = getNextSiblings(elems[i], adapter);
elems.push(...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.
*
*/
export const selectAll = getSelectorFunc((query, elems, options) => query === boolbase.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.
*/
export const selectOne = getSelectorFunc((query, elems, options) => query === boolbase.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
*/
export function is(elem, query, options) {
const opts = convertOptionFormats(options);
return (typeof query === "function" ? query : compileRaw(query, opts))(elem);
}
/**
* Alias for selectAll(query, elems, options).
* @see [compile] for supported selector queries.
*/
export default selectAll;
// Export filters, pseudos and aliases to allow users to supply their own.
/** @deprecated Use the `pseudos` option instead. */
export { filters, pseudos, aliases } from "./pseudo-selectors/index.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC;AACrC,OAAO,QAAQ,MAAM,UAAU,CAAC;AAKhC,OAAO,EACH,OAAO,IAAI,UAAU,EACrB,aAAa,EACb,YAAY,GACf,MAAM,cAAc,CAAC;AAStB,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAInE,MAAM,aAAa,GAAG,CAAO,CAAO,EAAE,CAAO,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC;AAC1D,MAAM,cAAc,GAAuD;IACvE,OAAO,EAAE,QAAQ;IACjB,MAAM,EAAE,aAAa;CACxB,CAAC;AAEF,SAAS,oBAAoB,CACzB,OAAoC;;IAEpC;;OAEG;IACH,iFAAiF;IACjF,MAAM,IAAI,GAA+B,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,cAAc,CAAC;IACnE,kCAAkC;IAClC,MAAA,IAAI,CAAC,OAAO,oCAAZ,IAAI,CAAC,OAAO,GAAK,QAAQ,EAAC;IAC1B,wDAAwD;IACxD,MAAA,IAAI,CAAC,MAAM,oCAAX,IAAI,CAAC,MAAM,GAAK,MAAA,MAAA,IAAI,CAAC,OAAO,0CAAE,MAAM,mCAAI,aAAa,EAAC;IAEtD,OAAO,IAA0C,CAAC;AACtD,CAAC;AAED,SAAS,WAAW,CAChB,IAIqB;IAErB,OAAO,SAAS,UAAU,CACtB,QAAkB,EAClB,OAAoC,EACpC,OAAuB;QAEvB,MAAM,IAAI,GAAG,oBAAo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AAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAC3C,OAAO,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAClE,IAAI,CACP,CAAC;AACN,CAAC;AAED;;;GAGG;AACH,eAAe,SAAS,CAAC;AAEzB,0EAA0E;AAC1E,oDAAoD;AACpD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC"}

View File

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

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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["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,35 @@
/**
* Aliases are pseudos that are expressed as selectors.
*/
export const 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(
:is(button, input, select, textarea, optgroup, option)[disabled],
optgroup[disabled] > option,
fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
)`,
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])",
};
//# sourceMappingURL=aliases.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"aliases.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/aliases.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,MAAM,OAAO,GAA2B;IAC3C,QAAQ;IAER,UAAU,EAAE,0BAA0B;IACtC,IAAI,EAAE,yBAAyB;IAE/B,QAAQ;IAER,0EAA0E;IAC1E,QAAQ,EAAE;;;;MAIR;IACF,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EACH,6EAA6E;IACjF,QAAQ,EAAE,wCAAwC;IAClD,QAAQ,EAAE,8CAA8C;IAExD,oBAAoB;IAEpB,wFAAwF;IACxF,QAAQ,EACJ,8FAA8F;IAElG,QAAQ,EAAE,iBAAiB;IAC3B,IAAI,EAAE,aAAa;IACnB,QAAQ,EAAE,iBAAiB;IAC3B,KAAK,EAAE,cAAc;IACrB,KAAK,EAAE,cAAc;IACrB,KAAK,EAAE,cAAc;IACrB,MAAM,EAAE,eAAe;IAEvB,MAAM,EAAE,cAAc;IACtB,MAAM,EAAE,6BAA6B;IAErC,MAAM,EAAE,iCAAiC;IACzC,KAAK,EAAE,sCAAsC;IAC7C,IAAI,EAAE,yCAAyC;CAClD,CAAC"}

View File

@@ -0,0 +1,4 @@
import type { CompiledQuery, InternalOptions } from "../types.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/filters.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAW,MAAM,aAAa,CAAC;AAE3E,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,143 @@
import getNCheck from "nth-check";
import boolbase from "boolbase";
function getChildFunc(next, adapter) {
return (elem) => {
const parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(elem);
};
}
export const filters = {
contains(next, text, { adapter }) {
return function contains(elem) {
return next(elem) && adapter.getText(elem).includes(text);
};
},
icontains(next, text, { adapter }) {
const itext = text.toLowerCase();
return function icontains(elem) {
return (next(elem) &&
adapter.getText(elem).toLowerCase().includes(itext));
};
},
// Location specific methods
"nth-child"(next, rule, { adapter, equals }) {
const func = getNCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthChild(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let 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"(next, rule, { adapter, equals }) {
const func = getNCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthLastChild(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let 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"(next, rule, { adapter, equals }) {
const func = getNCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthOfType(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let i = 0; i < siblings.length; i++) {
const 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"(next, rule, { adapter, equals }) {
const func = getNCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthLastOfType(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let i = siblings.length - 1; i >= 0; i--) {
const 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(next, _rule, { adapter }) {
return (elem) => {
const parent = adapter.getParent(elem);
return (parent == null || !adapter.isTag(parent)) && next(elem);
};
},
scope(next, rule, options, context) {
const { equals } = options;
if (!context || context.length === 0) {
// Equivalent to :root
return filters["root"](next, rule, options);
}
if (context.length === 1) {
// NOTE: can't be unpacked, as :has uses this for side-effects
return (elem) => equals(context[0], elem) && next(elem);
}
return (elem) => 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, { adapter }) {
const func = adapter[name];
if (typeof func !== "function") {
return boolbase.falseFunc;
}
return function active(elem) {
return func(elem) && next(elem);
};
};
}
//# sourceMappingURL=filters.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
import type { CompiledQuery, InternalOptions, CompileToken } from "../types.js";
import { PseudoSelector } from "css-what";
import { filters } from "./filters.js";
import { pseudos } from "./pseudos.js";
import { aliases } from "./aliases.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/index.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EAAS,cAAc,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,OAAO,EAAoB,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,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,CA4C5B"}

View File

@@ -0,0 +1,40 @@
import { parse } from "css-what";
import { filters } from "./filters.js";
import { pseudos, verifyPseudoArgs } from "./pseudos.js";
import { aliases } from "./aliases.js";
import { subselects } from "./subselects.js";
export { filters, pseudos, aliases };
export function compilePseudoSelector(next, selector, options, context, compileToken) {
var _a;
const { name, data } = selector;
if (Array.isArray(data)) {
if (!(name in subselects)) {
throw new Error(`Unknown pseudo-class :${name}(${data})`);
}
return subselects[name](next, data, options, context, compileToken);
}
const userPseudo = (_a = options.pseudos) === null || _a === void 0 ? void 0 : _a[name];
const stringPseudo = typeof userPseudo === "string" ? userPseudo : aliases[name];
if (typeof stringPseudo === "string") {
if (data != null) {
throw new Error(`Pseudo ${name} doesn't have any arguments`);
}
// The alias has to be parsed here, to make sure options are respected.
const alias = parse(stringPseudo);
return subselects["is"](next, alias, options, context, compileToken);
}
if (typeof userPseudo === "function") {
verifyPseudoArgs(userPseudo, name, data, 1);
return (elem) => userPseudo(elem, data) && next(elem);
}
if (name in filters) {
return filters[name](next, data, options, context);
}
if (name in pseudos) {
const pseudo = pseudos[name];
verifyPseudoArgs(pseudo, name, data, 2);
return (elem) => pseudo(elem, options, data) && next(elem);
}
throw new Error(`Unknown pseudo-class :${name}`);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/index.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,KAAK,EAAkB,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,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,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;KACzD;IAED,IAAI,IAAI,IAAI,OAAO,EAAE;QACjB,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAc,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;KAChE;IAED,IAAI,IAAI,IAAI,OAAO,EAAE;QACjB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC7B,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAExC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;KAC9D;IAED,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,EAAE,CAAC,CAAC;AACrD,CAAC"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"pseudos.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/pseudos.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,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,MAAM,GAAG,IAAI,KACxB,OAAO,CAAC;AAGb,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAkF1C,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,KAAK,CAAC,OAAO,CAAC,EACrD,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,EAC7B,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,cAAc,CAAC,MAAM,CAAC,EACjC,QAAQ,EAAE,MAAM,GACjB,IAAI,CAQN"}

View File

@@ -0,0 +1,79 @@
// While filters are precompiled, pseudos get called when they are needed
export const pseudos = {
empty(elem, { adapter }) {
return !adapter.getChildren(elem).some((elem) =>
// FIXME: `getText` call is potentially expensive.
adapter.isTag(elem) || adapter.getText(elem) !== "");
},
"first-child"(elem, { adapter, equals }) {
if (adapter.prevElementSibling) {
return adapter.prevElementSibling(elem) == null;
}
const firstChild = adapter
.getSiblings(elem)
.find((elem) => adapter.isTag(elem));
return firstChild != null && equals(elem, firstChild);
},
"last-child"(elem, { adapter, equals }) {
const siblings = adapter.getSiblings(elem);
for (let 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"(elem, { adapter, equals }) {
const siblings = adapter.getSiblings(elem);
const elemName = adapter.getName(elem);
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
return true;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === elemName) {
break;
}
}
return false;
},
"last-of-type"(elem, { adapter, equals }) {
const siblings = adapter.getSiblings(elem);
const elemName = adapter.getName(elem);
for (let i = siblings.length - 1; i >= 0; i--) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
return true;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === elemName) {
break;
}
}
return false;
},
"only-of-type"(elem, { adapter, equals }) {
const elemName = adapter.getName(elem);
return adapter
.getSiblings(elem)
.every((sibling) => equals(elem, sibling) ||
!adapter.isTag(sibling) ||
adapter.getName(sibling) !== elemName);
},
"only-child"(elem, { adapter, equals }) {
return adapter
.getSiblings(elem)
.every((sibling) => equals(elem, sibling) || !adapter.isTag(sibling));
},
};
export function verifyPseudoArgs(func, name, subselect, argIndex) {
if (subselect === null) {
if (func.length > argIndex) {
throw new Error(`Pseudo-class :${name} requires an argument`);
}
}
else if (func.length === argIndex) {
throw new Error(`Pseudo-class :${name} doesn't have any arguments`);
}
}
//# sourceMappingURL=pseudos.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pseudos.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/pseudos.ts"],"names":[],"mappings":"AASA,yEAAyE;AACzE,MAAM,CAAC,MAAM,OAAO,GAA2B;IAC3C,KAAK,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE;QACnB,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,IAAI,CAClC,CAAC,IAAI,EAAE,EAAE;QACL,kDAAkD;QAClD,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,EAAE,CAC1D,CAAC;IACN,CAAC;IAED,aAAa,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE;QACnC,IAAI,OAAO,CAAC,kBAAkB,EAAE;YAC5B,OAAO,OAAO,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;SACnD;QAED,MAAM,UAAU,GAAG,OAAO;aACrB,WAAW,CAAC,IAAI,CAAC;aACjB,IAAI,CAAC,CAAC,IAAI,EAAE,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F,MAAM,UAAU,gBAAgB,CAC5B,IAA6B,EAC7B,IAAY,EACZ,SAAiC,EACjC,QAAgB;IAEhB,IAAI,SAAS,KAAK,IAAI,EAAE;QACpB,IAAI,IAAI,CAAC,MAAM,GAAG,QAAQ,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,IAAI,uBAAuB,CAAC,CAAC;SACjE;KACJ;SAAM,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,iBAAiB,IAAI,6BAA6B,CAAC,CAAC;KACvE;AACL,CAAC"}

View File

@@ -0,0 +1,9 @@
import type { Selector } from "css-what";
import type { CompiledQuery, InternalOptions, CompileToken, Adapter } from "../types.js";
/** 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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/subselects.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,KAAK,EACR,aAAa,EACb,eAAe,EACf,YAAY,EACZ,OAAO,EACV,MAAM,aAAa,CAAC;AAGrB,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;AAiCD,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAgEhD,CAAC"}

View File

@@ -0,0 +1,94 @@
import boolbase from "boolbase";
import { isTraversal } from "../sort.js";
/** Used as a placeholder for :has. Will be replaced with the actual element. */
export const PLACEHOLDER_ELEMENT = {};
export function ensureIsTag(next, adapter) {
if (next === boolbase.falseFunc)
return boolbase.falseFunc;
return (elem) => adapter.isTag(elem) && next(elem);
}
export function getNextSiblings(elem, adapter) {
const siblings = adapter.getSiblings(elem);
if (siblings.length <= 1)
return [];
const elemIndex = siblings.indexOf(elem);
if (elemIndex < 0 || elemIndex === siblings.length - 1)
return [];
return siblings.slice(elemIndex + 1).filter(adapter.isTag);
}
function copyOptions(options) {
// Not copied: context, rootFunc
return {
xmlMode: !!options.xmlMode,
lowerCaseAttributeNames: !!options.lowerCaseAttributeNames,
lowerCaseTags: !!options.lowerCaseTags,
quirksMode: !!options.quirksMode,
cacheResults: !!options.cacheResults,
pseudos: options.pseudos,
adapter: options.adapter,
equals: options.equals,
};
}
const is = (next, token, options, context, compileToken) => {
const func = compileToken(token, copyOptions(options), context);
return func === boolbase.trueFunc
? next
: func === boolbase.falseFunc
? boolbase.falseFunc
: (elem) => 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
*/
export const subselects = {
is,
/**
* `:matches` and `:where` are aliases for `:is`.
*/
matches: is,
where: is,
not(next, token, options, context, compileToken) {
const func = compileToken(token, copyOptions(options), context);
return func === boolbase.falseFunc
? next
: func === boolbase.trueFunc
? boolbase.falseFunc
: (elem) => !func(elem) && next(elem);
},
has(next, subselect, options, _context, compileToken) {
const { adapter } = options;
const opts = copyOptions(options);
opts.relativeSelector = true;
const context = subselect.some((s) => s.some(isTraversal))
? // Used as a placeholder. Will be replaced with the actual element.
[PLACEHOLDER_ELEMENT]
: undefined;
const compiled = compileToken(subselect, opts, context);
if (compiled === boolbase.falseFunc)
return boolbase.falseFunc;
const hasElement = ensureIsTag(compiled, adapter);
// If `compiled` is `trueFunc`, we can skip this.
if (context && compiled !== boolbase.trueFunc) {
/*
* `shouldTestNextSiblings` will only be true if the query starts with
* a traversal (sibling or adjacent). That means we will always have a context.
*/
const { shouldTestNextSiblings = false } = compiled;
return (elem) => {
if (!next(elem))
return false;
context[0] = elem;
const childs = adapter.getChildren(elem);
const nextElements = shouldTestNextSiblings
? [...childs, ...getNextSiblings(elem, adapter)]
: childs;
return adapter.existsOne(hasElement, nextElements);
};
}
return (elem) => next(elem) &&
adapter.existsOne(hasElement, adapter.getChildren(elem));
},
};
//# sourceMappingURL=subselects.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"subselects.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-select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SACL;QAED,OAAO,CAAC,IAAI,EAAE,EAAE,CACZ,IAAI,CAAC,IAAI,CAAC;YACV,OAAO,CAAC,SAAS,CAAC,UAAU,EAAE,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;IACjE,CAAC;CACJ,CAAC"}

View File

@@ -0,0 +1,12 @@
import type { InternalSelector } from "./types.js";
import { type Traversal } from "css-what";
export declare function isTraversal(token: InternalSelector): token is Traversal;
/**
* 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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["sort.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAiC,KAAK,SAAS,EAAE,MAAM,UAAU,CAAC;AASzE,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,KAAK,IAAI,SAAS,CAEvE;AAWD;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,GAAG,EAAE,gBAAgB,EAAE,GAAG,IAAI,CAerE"}

View File

@@ -0,0 +1,79 @@
import { AttributeAction, SelectorType } from "css-what";
const procedure = new Map([
[SelectorType.Universal, 50],
[SelectorType.Tag, 30],
[SelectorType.Attribute, 1],
[SelectorType.Pseudo, 0],
]);
export function isTraversal(token) {
return !procedure.has(token.type);
}
const attributes = new Map([
[AttributeAction.Exists, 10],
[AttributeAction.Equals, 8],
[AttributeAction.Not, 7],
[AttributeAction.Start, 6],
[AttributeAction.End, 6],
[AttributeAction.Any, 5],
]);
/**
* 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) {
const procs = arr.map(getProcedure);
for (let i = 1; i < arr.length; i++) {
const procNew = procs[i];
if (procNew < 0)
continue;
for (let j = i - 1; j >= 0 && procNew < procs[j]; j--) {
const token = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = token;
procs[j + 1] = procs[j];
procs[j] = procNew;
}
}
}
function getProcedure(token) {
var _a, _b;
let proc = (_a = procedure.get(token.type)) !== null && _a !== void 0 ? _a : -1;
if (token.type === SelectorType.Attribute) {
proc = (_b = attributes.get(token.action)) !== null && _b !== void 0 ? _b : 4;
if (token.action === AttributeAction.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 === 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)) {
// Eg. :matches, :not
proc = Math.min(...token.data.map((d) => Math.min(...d.map(getProcedure))));
// If we have traversals, try to avoid executing this selector
if (proc < 0) {
proc = 0;
}
}
else {
proc = 2;
}
}
return proc;
}
//# sourceMappingURL=sort.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"sort.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["sort.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,YAAY,EAAkB,MAAM,UAAU,CAAC;AAEzE,MAAM,SAAS,GAAG,IAAI,GAAG,CAAmC;IACxD,CAAC,YAAY,CAAC,SAAS,EAAE,EAAE,CAAC;IAC5B,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,CAAC;IACtB,CAAC,YAAY,CAAC,SAAS,EAAE,CAAC,CAAC;IAC3B,CAAC,YAAY,CAAC,MAAM,EAAE,CAAC,CAAC;CAC3B,CAAC,CAAC;AA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;YACH,IAAI,GAAG,CAAC,CAAC;SACZ;KACJ;IACD,OAAO,IAAI,CAAC;AAChB,CAAC"}

View File

@@ -0,0 +1,167 @@
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) => Node | 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;
/**
* Pseudo-classes that override the default ones.
*
* Maps from names to either strings of functions.
* - A string value is a selector that the element must match to be selected.
* - A function is called with the element as its first argument, and optional
* parameters second. If it returns true, the element is selected.
*/
pseudos?: Record<string, string | ((elem: ElementNode, value?: string | null) => boolean)> | undefined;
/**
* 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-class.
*/
context?: Node | Node[];
/**
* Indicates whether to consider the selector as a relative selector.
*
* Relative selectors that don't include a `:scope` pseudo-class behave
* as if they have a `:scope ` prefix (a `:scope` pseudo-class, followed by
* a descendant selector).
*
* If relative selectors are disabled, selectors starting with a traversal
* will lead to an error.
*
* @default true
* @see {@link https://www.w3.org/TR/selectors-4/#relative}
*/
relativeSelector?: boolean;
/**
* 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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["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,IAAI,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,IAAI,EAAE,CAAC;IAEpC;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,IAAI,EAAE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1,2 @@
export {};
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["types.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,3 @@
import type { CompiledQuery, InternalOptions, InternalSelector, CompileToken } from "./types.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["general.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAER,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,YAAY,EACf,MAAM,YAAY,CAAC;AAkBpB,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,148 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileGeneralSelector = void 0;
var attributes_js_1 = require("./attributes.js");
var index_js_1 = require("./pseudo-selectors/index.js");
var css_what_1 = require("css-what");
function getElementParent(node, adapter) {
var parent = adapter.getParent(node);
if (parent && adapter.isTag(parent)) {
return parent;
}
return null;
}
/*
* 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_js_1.attributeRules[selector.action](next, selector, options);
}
case css_what_1.SelectorType.Pseudo: {
return (0, index_js_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 = getElementParent(current, adapter))) {
if (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 = getElementParent(current, adapter))) {
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 (next(current))
return true;
} while ((current = getElementParent(current, adapter)));
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;
//# sourceMappingURL=general.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"general.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["general.ts"],"names":[],"mappings":";;;AAAA,iDAAiD;AACjD,wDAAoE;AAQpE,qCAAwC;AAExC,SAAS,gBAAgB,CACrB,IAAiB,EACjB,OAAmC;IAEnC,IAAM,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE;QACjC,OAAO,MAAM,CAAC;KACjB;IACD,OAAO,IAAI,CAAC;AAChB,CAAC;AAED;;GAEG;AAEH,SAAgB,sBAAsB,CAClC,IAAgC,EAChC,QAA0B,EAC1B,OAA2C,EAC3C,OAA2B,EAC3B,YAA6C;IAErC,IAAA,OAAO,GAAa,OAAO,QAApB,EAAE,MAAM,GAAK,OAAO,OAAZ,CAAa;IAEpC,QAAQ,QAAQ,CAAC,IAA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gBAC5B,OAAO,SAAS,QAAQ,CAAC,IAAiB;oBACtC,IAAM,QAAQ,GAAG,OAAO,CAAC,kBAAmB,CAAC,IAAI,CAAC,CAAC;oBACnD,OAAO,QAAQ,IAAI,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC;gBAC9C,CAAC,CAAC;aACL;YAED,OAAO,SAAS,QAAQ,CAAC,IAAiB;gBACtC,IAAM,QAAQ,GAAG,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;gBAC3C,IAAI,WAAW,CAAC;gBAEhB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;oBACtC,IAAM,cAAc,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;oBACnC,IAAI,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC;wBAAE,MAAM;oBACxC,IAAI,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE;wBAC/B,WAAW,GAAG,cAAc,CAAC;qBAChC;iBACJ;gBAED,OAAO,CAAC,CAAC,WAAW,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC;YAC9C,CAAC,CAAC;SACL;QACD,KAAK,uBAAY,CAAC,SAAS,CAAC,CAAC;YACzB,IAAI,QAAQ,CAAC,SAAS,IAAI,IAAI,IAAI,QAAQ,CAAC,SAAS,KAAK,GAAG,EAAE;gBAC1D,MAAM,IAAI,KAAK,CACX,oEAAoE,CACvE,CAAC;aACL;YAED,OAAO,IAAI,CAAC;SACf;KACJ;AACL,CAAC;AAvKD,wDAuKC"}

View File

@@ -0,0 +1,50 @@
import type { CompiledQuery, Options, Query, Adapter } from "./types.js";
export type { Options };
/**
* Compiles the query, returns a function.
*/
export declare const compile: <Node, ElementNode extends Node>(selector: string | import("css-what").Selector[][], options?: Options<Node, ElementNode> | undefined, context?: Node | Node[] | undefined) => CompiledQuery<Node>;
export declare const _compileUnsafe: <Node, ElementNode extends Node>(selector: string | import("css-what").Selector[][], options?: Options<Node, ElementNode> | undefined, context?: Node | Node[] | undefined) => CompiledQuery<ElementNode>;
export declare const _compileToken: <Node, ElementNode extends Node>(selector: import("./types.js").InternalSelector[][], options?: Options<Node, ElementNode> | undefined, context?: Node | Node[] | 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, ElementNode extends Node>(query: Query<ElementNode>, elements: Node | Node[], options?: Options<Node, 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, ElementNode extends Node>(query: Query<ElementNode>, elements: Node | Node[], options?: Options<Node, 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;
/** @deprecated Use the `pseudos` option instead. */
export { filters, pseudos, aliases } from "./pseudo-selectors/index.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["index.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EACR,aAAa,EACb,OAAO,EAEP,KAAK,EACL,OAAO,EAEV,MAAM,YAAY,CAAC;AAGpB,YAAY,EAAE,OAAO,EAAE,CAAC;AA0CxB;;GAEG;AACH,eAAO,MAAM,OAAO,oMAA0B,CAAC;AAC/C,eAAO,MAAM,cAAc,2MAA6B,CAAC;AACzD,eAAO,MAAM,aAAa,4MAA4B,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,yJASrB,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,SAAS,8JASrB,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,oDAAoD;AACpD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAC"}

View File

@@ -0,0 +1,154 @@
"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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
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 = __importDefault(require("boolbase"));
var compile_js_1 = require("./compile.js");
var subselects_js_1 = require("./pseudo-selectors/subselects.js");
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_js_1.compile);
exports._compileUnsafe = wrapCompile(compile_js_1.compileUnsafe);
exports._compileToken = wrapCompile(compile_js_1.compileToken);
function getSelectorFunc(searchFunc) {
return function select(query, elements, options) {
var opts = convertOptionFormats(options);
if (typeof query !== "function") {
query = (0, compile_js_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_js_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.default.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.default.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_js_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.
/** @deprecated Use the `pseudos` option instead. */
var index_js_1 = require("./pseudo-selectors/index.js");
Object.defineProperty(exports, "filters", { enumerable: true, get: function () { return index_js_1.filters; } });
Object.defineProperty(exports, "pseudos", { enumerable: true, get: function () { return index_js_1.pseudos; } });
Object.defineProperty(exports, "aliases", { enumerable: true, get: function () { return index_js_1.aliases; } });
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAqC;AACrC,sDAAgC;AAKhC,2CAIsB;AAStB,kEAAmE;AAInE,IAAM,aAAa,GAAG,UAAO,CAAO,EAAE,CAAO,IAAK,OAAA,CAAC,KAAK,CAAC,EAAP,CAAO,CAAC;AAC1D,IAAM,cAAc,GAAuD;IACvE,OAAO,EAAE,QAAQ;IACjB,MAAM,EAAE,aAAa;CACxB,CAAC;AAEF,SAAS,oBAAoB,CACzB,OAAoC;;IAEpC;;OAEG;IACH,iFAAiF;IACjF,IAAM,IAAI,GAA+B,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,cAAc,CAAC;IACnE,kCAAkC;IAClC,MAAA,IAAI,CAAC,OAAO,oCAAZ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oB,EACpB,OAA2C;IAE3C,OAAA,KAAK,KAAK,kBAAQ,CAAC,SAAS,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QACxD,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;AAF3C,CAE2C,CAClD,CAAC;AAEF;;;;;;;;;;GAUG;AACH,SAAgB,EAAE,CACd,IAAiB,EACjB,KAAyB,EACzB,OAAoC;IAEpC,IAAM,IAAI,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAC3C,OAAO,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,oBAAU,EAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAClE,IAAI,CACP,CAAC;AACN,CAAC;AATD,gBASC;AAED;;;GAGG;AACH,kBAAe,iBAAS,CAAC;AAEzB,0EAA0E;AAC1E,oDAAoD;AACpD,wDAAwE;AAA/D,mGAAA,OAAO,OAAA;AAAE,mGAAA,OAAO,OAAA;AAAE,mGAAA,OAAO,OAAA"}

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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["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,34 @@
"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])",
};
//# sourceMappingURL=aliases.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"aliases.js","sourceRoot":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/aliases.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,OAAO,GAA2B;IAC3C,QAAQ;IAER,UAAU,EAAE,0BAA0B;IACtC,IAAI,EAAE,yBAAyB;IAE/B,QAAQ;IAER,0EAA0E;IAC1E,QAAQ,EAAE,yMAIR;IACF,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EACH,6EAA6E;IACjF,QAAQ,EAAE,wCAAwC;IAClD,QAAQ,EAAE,8CAA8C;IAExD,oBAAoB;IAEpB,wFAAwF;IACxF,QAAQ,EACJ,8FAA8F;IAElG,QAAQ,EAAE,iBAAiB;IAC3B,IAAI,EAAE,aAAa;IACnB,QAAQ,EAAE,iBAAiB;IAC3B,KAAK,EAAE,cAAc;IACrB,KAAK,EAAE,cAAc;IACrB,KAAK,EAAE,cAAc;IACrB,MAAM,EAAE,eAAe;IAEvB,MAAM,EAAE,cAAc;IACtB,MAAM,EAAE,6BAA6B;IAErC,MAAM,EAAE,iCAAiC;IACzC,KAAK,EAAE,sCAAsC;IAC7C,IAAI,EAAE,yCAAyC;CAClD,CAAC"}

View File

@@ -0,0 +1,4 @@
import type { CompiledQuery, InternalOptions } from "../types.js";
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":"https://raw.githubusercontent.com/fb55/css-select/0f0725a9dfeddd2fdb54eda9656cdbab5bbf6be6/src/","sources":["pseudo-selectors/filters.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAW,MAAM,aAAa,CAAC;AAE3E,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,157 @@
"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 = __importDefault(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.default.falseFunc)
return boolbase_1.default.falseFunc;
if (func === boolbase_1.default.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.default.falseFunc)
return boolbase_1.default.falseFunc;
if (func === boolbase_1.default.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.default.falseFunc)
return boolbase_1.default.falseFunc;
if (func === boolbase_1.default.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.default.falseFunc)
return boolbase_1.default.falseFunc;
if (func === boolbase_1.default.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.default.falseFunc;
}
return function active(elem) {
return func(elem) && next(elem);
};
};
}
//# sourceMappingURL=filters.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
import type { CompiledQuery, InternalOptions, CompileToken } from "../types.js";
import { PseudoSelector } from "css-what";
import { filters } from "./filters.js";
import { pseudos } from "./pseudos.js";
import { aliases } from "./aliases.js";
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

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