svgo
Version:
611 lines • 780 kB
JavaScript
const visitSkip=Symbol()
const visit=(node,visitor,parentNode)=>{const callbacks=visitor[node.type]
if(callbacks?.enter){const symbol=callbacks.enter(node,parentNode)
if(symbol===visitSkip)return}if(node.type==="root")for(const child of node.children)visit(child,visitor,node)
if(node.type==="element"&&parentNode.children.includes(node))for(const child of node.children)visit(child,visitor,node)
callbacks?.exit&&callbacks.exit(node,parentNode)}
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)
visitor!=null&&visit(ast,visitor)}}
const createPreset=({name:name,plugins:plugins})=>({name:name,isPreset:true,plugins:Object.freeze(plugins),fn:(ast,params,info)=>{const{floatPrecision:floatPrecision,overrides:overrides}=params
const globalOverrides={}
floatPrecision!=null&&(globalOverrides.floatPrecision=floatPrecision)
if(overrides){const pluginNames=plugins.map((({name:name})=>name))
for(const pluginName of Object.keys(overrides))pluginNames.includes(pluginName)||console.warn(`You are trying to configure ${pluginName} which is not part of ${name}.\nTry to put it before or after, for example\n\nplugins: [\n {\n name: '${name}',\n },\n '${pluginName}'\n]\n`)}invokePlugins(ast,info,plugins,overrides,globalOverrides)}})
var ElementType;(function(ElementType){ElementType["Root"]="root"
ElementType["Text"]="text"
ElementType["Directive"]="directive"
ElementType["Comment"]="comment"
ElementType["Script"]="script"
ElementType["Style"]="style"
ElementType["Tag"]="tag"
ElementType["CDATA"]="cdata"
ElementType["Doctype"]="doctype"})(ElementType||(ElementType={}))
function isTag$2(elem){return elem.type===ElementType.Tag||elem.type===ElementType.Script||elem.type===ElementType.Style}const Root=ElementType.Root
const Text=ElementType.Text
const Directive=ElementType.Directive
const Comment$4=ElementType.Comment
const Script=ElementType.Script
const Style=ElementType.Style
const Tag=ElementType.Tag
const CDATA=ElementType.CDATA
const Doctype=ElementType.Doctype
function isTag$1(node){return isTag$2(node)}function isCDATA(node){return node.type===ElementType.CDATA}function isText(node){return node.type===ElementType.Text}function isComment(node){return node.type===ElementType.Comment}function isDocument(node){return node.type===ElementType.Root}function hasChildren(node){return Object.prototype.hasOwnProperty.call(node,"children")}const xmlReplacer=/["&'<>$\x80-\uFFFF]/g
const xmlCodeMap=new Map([[34,"""],[38,"&"],[39,"'"],[60,"<"],[62,">"]])
const getCodePoint=String.prototype.codePointAt!=null?(str,index)=>str.codePointAt(index):(c,index)=>(c.charCodeAt(index)&0xfc00)===0xd800?0x400*(c.charCodeAt(index)-0xd800)+c.charCodeAt(index+1)-0xdc00+0x10000:c.charCodeAt(index)
function encodeXML(str){let ret=""
let lastIdx=0
let match
while((match=xmlReplacer.exec(str))!==null){const i=match.index
const char=str.charCodeAt(i)
const next=xmlCodeMap.get(char)
if(next!==void 0){ret+=str.substring(lastIdx,i)+next
lastIdx=i+1}else{ret+=`${str.substring(lastIdx,i)}&#x${getCodePoint(str,i).toString(16)};`
lastIdx=xmlReplacer.lastIndex+=Number((char&0xfc00)===0xd800)}}return ret+str.substr(lastIdx)}function getEscaper(regex,map){return function escape(data){let match
let lastIdx=0
let result=""
while(match=regex.exec(data)){lastIdx!==match.index&&(result+=data.substring(lastIdx,match.index))
result+=map.get(match[0].charCodeAt(0))
lastIdx=match.index+1}return result+data.substring(lastIdx)}}const escapeAttribute=getEscaper(/["&\u00A0]/g,new Map([[34,"""],[38,"&"],[160," "]]))
const escapeText=getEscaper(/[&<>\u00A0]/g,new Map([[38,"&"],[60,"<"],[62,">"],[160," "]]))
const elementNames=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map((val=>[val.toLowerCase(),val])))
const attributeNames=new Map(["definitionURL","attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map((val=>[val.toLowerCase(),val])))
const unencodedElements=new Set(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])
function replaceQuotes(value){return value.replace(/"/g,""")}function formatAttributes(attributes,opts){var _a
if(!attributes)return
const encode=((_a=opts.encodeEntities)!==null&&_a!==void 0?_a:opts.decodeEntities)===false?replaceQuotes:opts.xmlMode||opts.encodeEntities!=="utf8"?encodeXML:escapeAttribute
return Object.keys(attributes).map((key=>{var _a,_b
const value=(_a=attributes[key])!==null&&_a!==void 0?_a:""
opts.xmlMode==="foreign"&&(key=(_b=attributeNames.get(key))!==null&&_b!==void 0?_b:key)
if(!opts.emptyAttrs&&!opts.xmlMode&&value==="")return key
return`${key}="${encode(value)}"`})).join(" ")}const singleTag=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"])
function render(node,options={}){const nodes="length"in node?node:[node]
let output=""
for(let i=0;i<nodes.length;i++)output+=renderNode(nodes[i],options)
return output}function renderNode(node,options){switch(node.type){case Root:return render(node.children,options)
case Doctype:case Directive:return renderDirective(node)
case Comment$4:return renderComment(node)
case CDATA:return renderCdata(node)
case Script:case Style:case Tag:return renderTag(node,options)
case Text:return renderText(node,options)}}const foreignModeIntegrationPoints=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"])
const foreignElements=new Set(["svg","math"])
function renderTag(elem,opts){var _a
if(opts.xmlMode==="foreign"){elem.name=(_a=elementNames.get(elem.name))!==null&&_a!==void 0?_a:elem.name
elem.parent&&foreignModeIntegrationPoints.has(elem.parent.name)&&(opts={...opts,xmlMode:false})}!opts.xmlMode&&foreignElements.has(elem.name)&&(opts={...opts,xmlMode:"foreign"})
let tag=`<${elem.name}`
const attribs=formatAttributes(elem.attribs,opts)
attribs&&(tag+=` ${attribs}`)
if(elem.children.length===0&&(opts.xmlMode?opts.selfClosingTags!==false:opts.selfClosingTags&&singleTag.has(elem.name))){opts.xmlMode||(tag+=" ")
tag+="/>"}else{tag+=">"
elem.children.length>0&&(tag+=render(elem.children,opts))
!opts.xmlMode&&singleTag.has(elem.name)||(tag+=`</${elem.name}>`)}return tag}function renderDirective(elem){return`<${elem.data}>`}function renderText(elem,opts){var _a
let data=elem.data||"";((_a=opts.encodeEntities)!==null&&_a!==void 0?_a:opts.decodeEntities)===false||!opts.xmlMode&&elem.parent&&unencodedElements.has(elem.parent.name)||(data=opts.xmlMode||opts.encodeEntities!=="utf8"?encodeXML(data):escapeText(data))
return data}function renderCdata(elem){return`<![CDATA[${elem.children[0].data}]]>`}function renderComment(elem){return`\x3c!--${elem.data}--\x3e`}function getOuterHTML(node,options){return render(node,options)}function getInnerHTML(node,options){return hasChildren(node)?node.children.map((node=>getOuterHTML(node,options))).join(""):""}function getText$1(node){if(Array.isArray(node))return node.map(getText$1).join("")
if(isTag$1(node))return node.name==="br"?"\n":getText$1(node.children)
if(isCDATA(node))return getText$1(node.children)
if(isText(node))return node.data
return""}function textContent(node){if(Array.isArray(node))return node.map(textContent).join("")
if(hasChildren(node)&&!isComment(node))return textContent(node.children)
if(isText(node))return node.data
return""}function innerText(node){if(Array.isArray(node))return node.map(innerText).join("")
if(hasChildren(node)&&(node.type===ElementType.Tag||isCDATA(node)))return innerText(node.children)
if(isText(node))return node.data
return""}function getChildren$1(elem){return hasChildren(elem)?elem.children:[]}function getParent(elem){return elem.parent||null}function getSiblings(elem){const parent=getParent(elem)
if(parent!=null)return getChildren$1(parent)
const siblings=[elem]
let{prev:prev,next:next}=elem
while(prev!=null){siblings.unshift(prev);({prev:prev}=prev)}while(next!=null){siblings.push(next);({next:next}=next)}return siblings}function getAttributeValue$1(elem,name){var _a
return(_a=elem.attribs)===null||_a===void 0?void 0:_a[name]}function hasAttrib$1(elem,name){return elem.attribs!=null&&Object.prototype.hasOwnProperty.call(elem.attribs,name)&&elem.attribs[name]!=null}function getName$1(elem){return elem.name}function nextElementSibling(elem){let{next:next}=elem
while(next!==null&&!isTag$1(next))({next:next}=next)
return next}function prevElementSibling(elem){let{prev:prev}=elem
while(prev!==null&&!isTag$1(prev))({prev:prev}=prev)
return prev}function removeElement(elem){elem.prev&&(elem.prev.next=elem.next)
elem.next&&(elem.next.prev=elem.prev)
if(elem.parent){const childs=elem.parent.children
const childsIndex=childs.lastIndexOf(elem)
childsIndex>=0&&childs.splice(childsIndex,1)}elem.next=null
elem.prev=null
elem.parent=null}function replaceElement(elem,replacement){const prev=replacement.prev=elem.prev
prev&&(prev.next=replacement)
const next=replacement.next=elem.next
next&&(next.prev=replacement)
const parent=replacement.parent=elem.parent
if(parent){const childs=parent.children
childs[childs.lastIndexOf(elem)]=replacement
elem.parent=null}}function appendChild(parent,child){removeElement(child)
child.next=null
child.parent=parent
if(parent.children.push(child)>1){const sibling=parent.children[parent.children.length-2]
sibling.next=child
child.prev=sibling}else child.prev=null}function append$1(elem,next){removeElement(next)
const{parent:parent}=elem
const currNext=elem.next
next.next=currNext
next.prev=elem
elem.next=next
next.parent=parent
if(currNext){currNext.prev=next
if(parent){const childs=parent.children
childs.splice(childs.lastIndexOf(currNext),0,next)}}else parent&&parent.children.push(next)}function prependChild(parent,child){removeElement(child)
child.parent=parent
child.prev=null
if(parent.children.unshift(child)!==1){const sibling=parent.children[1]
sibling.prev=child
child.next=sibling}else child.next=null}function prepend(elem,prev){removeElement(prev)
const{parent:parent}=elem
if(parent){const childs=parent.children
childs.splice(childs.indexOf(elem),0,prev)}elem.prev&&(elem.prev.next=prev)
prev.parent=parent
prev.prev=elem.prev
prev.next=elem
elem.prev=prev}function filter(test,node,recurse=true,limit=1/0){return find$3(test,Array.isArray(node)?node:[node],recurse,limit)}function find$3(test,nodes,recurse,limit){const result=[]
const nodeStack=[nodes]
const indexStack=[0]
for(;;){if(indexStack[0]>=nodeStack[0].length){if(indexStack.length===1)return result
nodeStack.shift()
indexStack.shift()
continue}const elem=nodeStack[0][indexStack[0]++]
if(test(elem)){result.push(elem)
if(--limit<=0)return result}if(recurse&&hasChildren(elem)&&elem.children.length>0){indexStack.unshift(0)
nodeStack.unshift(elem.children)}}}function findOneChild(test,nodes){return nodes.find(test)}function findOne$1(test,nodes,recurse=true){let elem=null
for(let i=0;i<nodes.length&&!elem;i++){const node=nodes[i]
if(!isTag$1(node))continue
test(node)?elem=node:recurse&&node.children.length>0&&(elem=findOne$1(test,node.children,true))}return elem}function existsOne$1(test,nodes){return nodes.some((checked=>isTag$1(checked)&&(test(checked)||existsOne$1(test,checked.children))))}function findAll$4(test,nodes){const result=[]
const nodeStack=[nodes]
const indexStack=[0]
for(;;){if(indexStack[0]>=nodeStack[0].length){if(nodeStack.length===1)return result
nodeStack.shift()
indexStack.shift()
continue}const elem=nodeStack[0][indexStack[0]++]
if(!isTag$1(elem))continue
test(elem)&&result.push(elem)
if(elem.children.length>0){indexStack.unshift(0)
nodeStack.unshift(elem.children)}}}const Checks={tag_name(name){if(typeof name==="function")return elem=>isTag$1(elem)&&name(elem.name)
if(name==="*")return isTag$1
return elem=>isTag$1(elem)&&elem.name===name},tag_type(type){if(typeof type==="function")return elem=>type(elem.type)
return elem=>elem.type===type},tag_contains(data){if(typeof data==="function")return elem=>isText(elem)&&data(elem.data)
return elem=>isText(elem)&&elem.data===data}}
function getAttribCheck(attrib,value){if(typeof value==="function")return elem=>isTag$1(elem)&&value(elem.attribs[attrib])
return elem=>isTag$1(elem)&&elem.attribs[attrib]===value}function combineFuncs(a,b){return elem=>a(elem)||b(elem)}function compileTest(options){const funcs=Object.keys(options).map((key=>{const value=options[key]
return Object.prototype.hasOwnProperty.call(Checks,key)?Checks[key](value):getAttribCheck(key,value)}))
return funcs.length===0?null:funcs.reduce(combineFuncs)}function testElement(options,node){const test=compileTest(options)
return!test||test(node)}function getElements(options,nodes,recurse,limit=1/0){const test=compileTest(options)
return test?filter(test,nodes,recurse,limit):[]}function getElementById(id,nodes,recurse=true){Array.isArray(nodes)||(nodes=[nodes])
return findOne$1(getAttribCheck("id",id),nodes,recurse)}function getElementsByTagName(tagName,nodes,recurse=true,limit=1/0){return filter(Checks["tag_name"](tagName),nodes,recurse,limit)}function getElementsByTagType(type,nodes,recurse=true,limit=1/0){return filter(Checks["tag_type"](type),nodes,recurse,limit)}function removeSubsets(nodes){let idx=nodes.length
while(--idx>=0){const node=nodes[idx]
if(idx>0&&nodes.lastIndexOf(node,idx-1)>=0){nodes.splice(idx,1)
continue}for(let ancestor=node.parent;ancestor;ancestor=ancestor.parent)if(nodes.includes(ancestor)){nodes.splice(idx,1)
break}}return nodes}var DocumentPosition;(function(DocumentPosition){DocumentPosition[DocumentPosition["DISCONNECTED"]=1]="DISCONNECTED"
DocumentPosition[DocumentPosition["PRECEDING"]=2]="PRECEDING"
DocumentPosition[DocumentPosition["FOLLOWING"]=4]="FOLLOWING"
DocumentPosition[DocumentPosition["CONTAINS"]=8]="CONTAINS"
DocumentPosition[DocumentPosition["CONTAINED_BY"]=16]="CONTAINED_BY"})(DocumentPosition||(DocumentPosition={}))
function compareDocumentPosition(nodeA,nodeB){const aParents=[]
const bParents=[]
if(nodeA===nodeB)return 0
let current=hasChildren(nodeA)?nodeA:nodeA.parent
while(current){aParents.unshift(current)
current=current.parent}current=hasChildren(nodeB)?nodeB:nodeB.parent
while(current){bParents.unshift(current)
current=current.parent}const maxIdx=Math.min(aParents.length,bParents.length)
let idx=0
while(idx<maxIdx&&aParents[idx]===bParents[idx])idx++
if(idx===0)return DocumentPosition.DISCONNECTED
const sharedParent=aParents[idx-1]
const siblings=sharedParent.children
const aSibling=aParents[idx]
const bSibling=bParents[idx]
if(siblings.indexOf(aSibling)>siblings.indexOf(bSibling)){if(sharedParent===nodeB)return DocumentPosition.FOLLOWING|DocumentPosition.CONTAINED_BY
return DocumentPosition.FOLLOWING}if(sharedParent===nodeA)return DocumentPosition.PRECEDING|DocumentPosition.CONTAINS
return DocumentPosition.PRECEDING}function uniqueSort(nodes){nodes=nodes.filter(((node,i,arr)=>!arr.includes(node,i+1)))
nodes.sort(((a,b)=>{const relative=compareDocumentPosition(a,b)
if(relative&DocumentPosition.PRECEDING)return-1
if(relative&DocumentPosition.FOLLOWING)return 1
return 0}))
return nodes}function getFeed(doc){const feedRoot=getOneElement(isValidFeed,doc)
return feedRoot?feedRoot.name==="feed"?getAtomFeed(feedRoot):getRssFeed(feedRoot):null}function getAtomFeed(feedRoot){var _a
const childs=feedRoot.children
const feed={type:"atom",items:getElementsByTagName("entry",childs).map((item=>{var _a
const{children:children}=item
const entry={media:getMediaElements(children)}
addConditionally(entry,"id","id",children)
addConditionally(entry,"title","title",children)
const href=(_a=getOneElement("link",children))===null||_a===void 0?void 0:_a.attribs["href"]
href&&(entry.link=href)
const description=fetch("summary",children)||fetch("content",children)
description&&(entry.description=description)
const pubDate=fetch("updated",children)
pubDate&&(entry.pubDate=new Date(pubDate))
return entry}))}
addConditionally(feed,"id","id",childs)
addConditionally(feed,"title","title",childs)
const href=(_a=getOneElement("link",childs))===null||_a===void 0?void 0:_a.attribs["href"]
href&&(feed.link=href)
addConditionally(feed,"description","subtitle",childs)
const updated=fetch("updated",childs)
updated&&(feed.updated=new Date(updated))
addConditionally(feed,"author","email",childs,true)
return feed}function getRssFeed(feedRoot){var _a,_b
const childs=(_b=(_a=getOneElement("channel",feedRoot.children))===null||_a===void 0?void 0:_a.children)!==null&&_b!==void 0?_b:[]
const feed={type:feedRoot.name.substr(0,3),id:"",items:getElementsByTagName("item",feedRoot.children).map((item=>{const{children:children}=item
const entry={media:getMediaElements(children)}
addConditionally(entry,"id","guid",children)
addConditionally(entry,"title","title",children)
addConditionally(entry,"link","link",children)
addConditionally(entry,"description","description",children)
const pubDate=fetch("pubDate",children)||fetch("dc:date",children)
pubDate&&(entry.pubDate=new Date(pubDate))
return entry}))}
addConditionally(feed,"title","title",childs)
addConditionally(feed,"link","link",childs)
addConditionally(feed,"description","description",childs)
const updated=fetch("lastBuildDate",childs)
updated&&(feed.updated=new Date(updated))
addConditionally(feed,"author","managingEditor",childs,true)
return feed}const MEDIA_KEYS_STRING=["url","type","lang"]
const MEDIA_KEYS_INT=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]
function getMediaElements(where){return getElementsByTagName("media:content",where).map((elem=>{const{attribs:attribs}=elem
const media={medium:attribs["medium"],isDefault:!!attribs["isDefault"]}
for(const attrib of MEDIA_KEYS_STRING)attribs[attrib]&&(media[attrib]=attribs[attrib])
for(const attrib of MEDIA_KEYS_INT)attribs[attrib]&&(media[attrib]=parseInt(attribs[attrib],10))
attribs["expression"]&&(media.expression=attribs["expression"])
return media}))}function getOneElement(tagName,node){return getElementsByTagName(tagName,node,true,1)[0]}function fetch(tagName,where,recurse=false){return textContent(getElementsByTagName(tagName,where,recurse,1)).trim()}function addConditionally(obj,prop,tagName,where,recurse=false){const val=fetch(tagName,where,recurse)
val&&(obj[prop]=val)}function isValidFeed(value){return value==="rss"||value==="feed"||value==="rdf:RDF"}var DomUtils=Object.freeze({__proto__:null,get DocumentPosition(){return DocumentPosition},append:append$1,appendChild:appendChild,compareDocumentPosition:compareDocumentPosition,existsOne:existsOne$1,filter:filter,find:find$3,findAll:findAll$4,findOne:findOne$1,findOneChild:findOneChild,getAttributeValue:getAttributeValue$1,getChildren:getChildren$1,getElementById:getElementById,getElements:getElements,getElementsByTagName:getElementsByTagName,getElementsByTagType:getElementsByTagType,getFeed:getFeed,getInnerHTML:getInnerHTML,getName:getName$1,getOuterHTML:getOuterHTML,getParent:getParent,getSiblings:getSiblings,getText:getText$1,hasAttrib:hasAttrib$1,hasChildren:hasChildren,innerText:innerText,isCDATA:isCDATA,isComment:isComment,isDocument:isDocument,isTag:isTag$1,isText:isText,nextElementSibling:nextElementSibling,prepend:prepend,prependChild:prependChild,prevElementSibling:prevElementSibling,removeElement:removeElement,removeSubsets:removeSubsets,replaceElement:replaceElement,testElement:testElement,textContent:textContent,uniqueSort:uniqueSort})
function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}var boolbase={trueFunc:function trueFunc(){return true},falseFunc:function falseFunc(){return false}}
var boolbase$1=getDefaultExportFromCjs(boolbase)
var SelectorType;(function(SelectorType){SelectorType["Attribute"]="attribute"
SelectorType["Pseudo"]="pseudo"
SelectorType["PseudoElement"]="pseudo-element"
SelectorType["Tag"]="tag"
SelectorType["Universal"]="universal"
SelectorType["Adjacent"]="adjacent"
SelectorType["Child"]="child"
SelectorType["Descendant"]="descendant"
SelectorType["Parent"]="parent"
SelectorType["Sibling"]="sibling"
SelectorType["ColumnCombinator"]="column-combinator"})(SelectorType||(SelectorType={}))
var AttributeAction;(function(AttributeAction){AttributeAction["Any"]="any"
AttributeAction["Element"]="element"
AttributeAction["End"]="end"
AttributeAction["Equals"]="equals"
AttributeAction["Exists"]="exists"
AttributeAction["Hyphen"]="hyphen"
AttributeAction["Not"]="not"
AttributeAction["Start"]="start"})(AttributeAction||(AttributeAction={}))
const reName=/^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/
const reEscape=/\\([\da-f]{1,6}\s?|(\s)|.)/gi
const actionTypes=new Map([[126,AttributeAction.Element],[94,AttributeAction.Start],[36,AttributeAction.End],[42,AttributeAction.Any],[33,AttributeAction.Not],[124,AttributeAction.Hyphen]])
const unpackPseudos=new Set(["has","not","matches","is","where","host","host-context"])
function isTraversal$1(selector){switch(selector.type){case SelectorType.Adjacent:case SelectorType.Child:case SelectorType.Descendant:case SelectorType.Parent:case SelectorType.Sibling:case SelectorType.ColumnCombinator:return true
default:return false}}const stripQuotesFromPseudos=new Set(["contains","icontains"])
function funescape(_,escaped,escapedWhitespace){const high=parseInt(escaped,16)-0x10000
return high!==high||escapedWhitespace?escaped:high<0?String.fromCharCode(high+0x10000):String.fromCharCode(high>>10|0xd800,high&0x3ff|0xdc00)}function unescapeCSS(str){return str.replace(reEscape,funescape)}function isQuote(c){return c===39||c===34}function isWhitespace(c){return c===32||c===9||c===10||c===12||c===13}function parse$1w(selector){const subselects=[]
const endIndex=parseSelector(subselects,`${selector}`,0)
if(endIndex<selector.length)throw new Error(`Unmatched selector: ${selector.slice(endIndex)}`)
return subselects}function parseSelector(subselects,selector,selectorIndex){let tokens=[]
function getName(offset){const match=selector.slice(selectorIndex+offset).match(reName)
if(!match)throw new Error(`Expected name, found ${selector.slice(selectorIndex)}`)
const[name]=match
selectorIndex+=offset+name.length
return unescapeCSS(name)}function stripWhitespace(offset){selectorIndex+=offset
while(selectorIndex<selector.length&&isWhitespace(selector.charCodeAt(selectorIndex)))selectorIndex++}function readValueWithParenthesis(){selectorIndex+=1
const start=selectorIndex
let counter=1
for(;counter>0&&selectorIndex<selector.length;selectorIndex++)selector.charCodeAt(selectorIndex)!==40||isEscaped(selectorIndex)?selector.charCodeAt(selectorIndex)!==41||isEscaped(selectorIndex)||counter--:counter++
if(counter)throw new Error("Parenthesis not matched")
return unescapeCSS(selector.slice(start,selectorIndex-1))}function isEscaped(pos){let slashCount=0
while(selector.charCodeAt(--pos)===92)slashCount++
return(slashCount&1)===1}function ensureNotTraversal(){if(tokens.length>0&&isTraversal$1(tokens[tokens.length-1]))throw new Error("Did not expect successive traversals.")}function addTraversal(type){if(tokens.length>0&&tokens[tokens.length-1].type===SelectorType.Descendant){tokens[tokens.length-1].type=type
return}ensureNotTraversal()
tokens.push({type:type})}function addSpecialAttribute(name,action){tokens.push({type:SelectorType.Attribute,name:name,action:action,value:getName(1),namespace:null,ignoreCase:"quirks"})}function finalizeSubselector(){tokens.length&&tokens[tokens.length-1].type===SelectorType.Descendant&&tokens.pop()
if(tokens.length===0)throw new Error("Empty sub-selector")
subselects.push(tokens)}stripWhitespace(0)
if(selector.length===selectorIndex)return selectorIndex
loop:while(selectorIndex<selector.length){const firstChar=selector.charCodeAt(selectorIndex)
switch(firstChar){case 32:case 9:case 10:case 12:case 13:if(tokens.length===0||tokens[0].type!==SelectorType.Descendant){ensureNotTraversal()
tokens.push({type:SelectorType.Descendant})}stripWhitespace(1)
break
case 62:addTraversal(SelectorType.Child)
stripWhitespace(1)
break
case 60:addTraversal(SelectorType.Parent)
stripWhitespace(1)
break
case 126:addTraversal(SelectorType.Sibling)
stripWhitespace(1)
break
case 43:addTraversal(SelectorType.Adjacent)
stripWhitespace(1)
break
case 46:addSpecialAttribute("class",AttributeAction.Element)
break
case 35:addSpecialAttribute("id",AttributeAction.Equals)
break
case 91:{stripWhitespace(1)
let name
let namespace=null
if(selector.charCodeAt(selectorIndex)===124)name=getName(1)
else if(selector.startsWith("*|",selectorIndex)){namespace="*"
name=getName(2)}else{name=getName(0)
if(selector.charCodeAt(selectorIndex)===124&&selector.charCodeAt(selectorIndex+1)!==61){namespace=name
name=getName(1)}}stripWhitespace(0)
let action=AttributeAction.Exists
const possibleAction=actionTypes.get(selector.charCodeAt(selectorIndex))
if(possibleAction){action=possibleAction
if(selector.charCodeAt(selectorIndex+1)!==61)throw new Error("Expected `=`")
stripWhitespace(2)}else if(selector.charCodeAt(selectorIndex)===61){action=AttributeAction.Equals
stripWhitespace(1)}let value=""
let ignoreCase=null
if(action!=="exists"){if(isQuote(selector.charCodeAt(selectorIndex))){const quote=selector.charCodeAt(selectorIndex)
let sectionEnd=selectorIndex+1
while(sectionEnd<selector.length&&(selector.charCodeAt(sectionEnd)!==quote||isEscaped(sectionEnd)))sectionEnd+=1
if(selector.charCodeAt(sectionEnd)!==quote)throw new Error("Attribute value didn't end")
value=unescapeCSS(selector.slice(selectorIndex+1,sectionEnd))
selectorIndex=sectionEnd+1}else{const valueStart=selectorIndex
while(selectorIndex<selector.length&&(!isWhitespace(selector.charCodeAt(selectorIndex))&&selector.charCodeAt(selectorIndex)!==93||isEscaped(selectorIndex)))selectorIndex+=1
value=unescapeCSS(selector.slice(valueStart,selectorIndex))}stripWhitespace(0)
const forceIgnore=selector.charCodeAt(selectorIndex)|0x20
if(forceIgnore===115){ignoreCase=false
stripWhitespace(1)}else if(forceIgnore===105){ignoreCase=true
stripWhitespace(1)}}if(selector.charCodeAt(selectorIndex)!==93)throw new Error("Attribute selector didn't terminate")
selectorIndex+=1
const attributeSelector={type:SelectorType.Attribute,name:name,action:action,value:value,namespace:namespace,ignoreCase:ignoreCase}
tokens.push(attributeSelector)
break}case 58:{if(selector.charCodeAt(selectorIndex+1)===58){tokens.push({type:SelectorType.PseudoElement,name:getName(2).toLowerCase(),data:selector.charCodeAt(selectorIndex)===40?readValueWithParenthesis():null})
continue}const name=getName(1).toLowerCase()
let data=null
if(selector.charCodeAt(selectorIndex)===40)if(unpackPseudos.has(name)){if(isQuote(selector.charCodeAt(selectorIndex+1)))throw new Error(`Pseudo-selector ${name} cannot be quoted`)
data=[]
selectorIndex=parseSelector(data,selector,selectorIndex+1)
if(selector.charCodeAt(selectorIndex)!==41)throw new Error(`Missing closing parenthesis in :${name} (${selector})`)
selectorIndex+=1}else{data=readValueWithParenthesis()
if(stripQuotesFromPseudos.has(name)){const quot=data.charCodeAt(0)
quot===data.charCodeAt(data.length-1)&&isQuote(quot)&&(data=data.slice(1,-1))}data=unescapeCSS(data)}tokens.push({type:SelectorType.Pseudo,name:name,data:data})
break}case 44:finalizeSubselector()
tokens=[]
stripWhitespace(1)
break
default:{if(selector.startsWith("/*",selectorIndex)){const endIndex=selector.indexOf("*/",selectorIndex+2)
if(endIndex<0)throw new Error("Comment was not terminated")
selectorIndex=endIndex+2
tokens.length===0&&stripWhitespace(0)
break}let namespace=null
let name
if(firstChar===42){selectorIndex+=1
name="*"}else if(firstChar===124){name=""
if(selector.charCodeAt(selectorIndex+1)===124){addTraversal(SelectorType.ColumnCombinator)
stripWhitespace(2)
break}}else{if(!reName.test(selector.slice(selectorIndex)))break loop
name=getName(0)}if(selector.charCodeAt(selectorIndex)===124&&selector.charCodeAt(selectorIndex+1)!==124){namespace=name
if(selector.charCodeAt(selectorIndex+1)===42){name="*"
selectorIndex+=2}else name=getName(1)}tokens.push(name==="*"?{type:SelectorType.Universal,namespace:namespace}:{type:SelectorType.Tag,name:name,namespace:namespace})}}}finalizeSubselector()
return selectorIndex}const procedure=new Map([[SelectorType.Universal,50],[SelectorType.Tag,30],[SelectorType.Attribute,1],[SelectorType.Pseudo,0]])
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]])
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
token.action===AttributeAction.Equals&&token.name==="id"&&(proc=9)
token.ignoreCase&&(proc>>=1)}else if(token.type===SelectorType.Pseudo)if(token.data)if(token.name==="has"||token.name==="contains")proc=0
else if(Array.isArray(token.data)){proc=Math.min(...token.data.map((d=>Math.min(...d.map(getProcedure)))))
proc<0&&(proc=0)}else proc=2
else proc=3
return proc}const reChars=/[-[\]{}()*+?.,\\^$|#\s]/g
function escapeRegex(value){return value.replace(reChars,"\\$&")}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)}const attributeRules={equals(next,data,options){const{adapter:adapter}=options
const{name:name}=data
let{value: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:adapter}=options
const{name:name}=data
let{value: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:adapter}=options
const{name:name,value:value}=data
if(/\s/.test(value))return boolbase$1.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&®ex.test(attr)&&next(elem)}},exists:(next,{name:name},{adapter:adapter})=>elem=>adapter.hasAttrib(elem,name)&&next(elem),start(next,data,options){const{adapter:adapter}=options
const{name:name}=data
let{value:value}=data
const len=value.length
if(len===0)return boolbase$1.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:adapter}=options
const{name:name}=data
let{value:value}=data
const len=-value.length
if(len===0)return boolbase$1.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:adapter}=options
const{name:name,value:value}=data
if(value==="")return boolbase$1.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&®ex.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:adapter}=options
const{name:name}=data
let{value:value}=data
if(value==="")return elem=>!!adapter.getAttributeValue(elem,name)&&next(elem)
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)}}
const whitespace=new Set([9,10,12,13,32])
const ZERO="0".charCodeAt(0)
const NINE="9".charCodeAt(0)
function parse$1v(formula){formula=formula.trim().toLowerCase()
if(formula==="even")return[2,0]
if(formula==="odd")return[2,1]
let idx=0
let a=0
let sign=readSign()
let number=readNumber()
if(idx<formula.length&&formula.charAt(idx)==="n"){idx++
a=sign*(number!==null&&number!==void 0?number:1)
skipWhitespace()
if(idx<formula.length){sign=readSign()
skipWhitespace()
number=readNumber()}else sign=number=0}if(number===null||idx<formula.length)throw new Error(`n-th rule couldn't be parsed ('${formula}')`)
return[a,sign*number]
function readSign(){if(formula.charAt(idx)==="-"){idx++
return-1}formula.charAt(idx)==="+"&&idx++
return 1}function readNumber(){const start=idx
let value=0
while(idx<formula.length&&formula.charCodeAt(idx)>=ZERO&&formula.charCodeAt(idx)<=NINE){value=value*10+(formula.charCodeAt(idx)-ZERO)
idx++}return idx===start?null:value}function skipWhitespace(){while(idx<formula.length&&whitespace.has(formula.charCodeAt(idx)))idx++}}function compile$1(parsed){const a=parsed[0]
const b=parsed[1]-1
if(b<0&&a<=0)return boolbase$1.falseFunc
if(a===-1)return index=>index<=b
if(a===0)return index=>index===b
if(a===1)return b<0?boolbase$1.trueFunc:index=>index>=b
const absA=Math.abs(a)
const bMod=(b%absA+absA)%absA
return a>1?index=>index>=b&&index%absA===bMod:index=>index<=b&&index%absA===bMod}function nthCheck(formula){return compile$1(parse$1v(formula))}function getChildFunc(next,adapter){return elem=>{const parent=adapter.getParent(elem)
return parent!=null&&adapter.isTag(parent)&&next(elem)}}const filters$1={contains:(next,text,{adapter:adapter})=>function contains(elem){return next(elem)&&adapter.getText(elem).includes(text)},icontains(next,text,{adapter:adapter}){const itext=text.toLowerCase()
return function icontains(elem){return next(elem)&&adapter.getText(elem).toLowerCase().includes(itext)}},"nth-child"(next,rule,{adapter:adapter,equals:equals}){const func=nthCheck(rule)
if(func===boolbase$1.falseFunc)return boolbase$1.falseFunc
if(func===boolbase$1.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
adapter.isTag(siblings[i])&&pos++}return func(pos)&&next(elem)}},"nth-last-child"(next,rule,{adapter:adapter,equals:equals}){const func=nthCheck(rule)
if(func===boolbase$1.falseFunc)return boolbase$1.falseFunc
if(func===boolbase$1.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
adapter.isTag(siblings[i])&&pos++}return func(pos)&&next(elem)}},"nth-of-type"(next,rule,{adapter:adapter,equals:equals}){const func=nthCheck(rule)
if(func===boolbase$1.falseFunc)return boolbase$1.falseFunc
if(func===boolbase$1.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
adapter.isTag(currentSibling)&&adapter.getName(currentSibling)===adapter.getName(elem)&&pos++}return func(pos)&&next(elem)}},"nth-last-of-type"(next,rule,{adapter:adapter,equals:equals}){const func=nthCheck(rule)
if(func===boolbase$1.falseFunc)return boolbase$1.falseFunc
if(func===boolbase$1.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
adapter.isTag(currentSibling)&&adapter.getName(currentSibling)===adapter.getName(elem)&&pos++}return func(pos)&&next(elem)}},root:(next,_rule,{adapter:adapter})=>elem=>{const parent=adapter.getParent(elem)
return(parent==null||!adapter.isTag(parent))&&next(elem)},scope(next,rule,options,context){const{equals:equals}=options
if(!context||context.length===0)return filters$1["root"](next,rule,options)
if(context.length===1)return elem=>equals(context[0],elem)&&next(elem)
return elem=>context.includes(elem)&&next(elem)},hover:dynamicStatePseudo("isHovered"),visited:dynamicStatePseudo("isVisited"),active:dynamicStatePseudo("isActive")}
function dynamicStatePseudo(name){return function dynamicPseudo(next,_rule,{adapter:adapter}){const func=adapter[name]
if(typeof func!=="function")return boolbase$1.falseFunc
return function active(elem){return func(elem)&&next(elem)}}}const pseudos={empty:(elem,{adapter:adapter})=>!adapter.getChildren(elem).some((elem=>adapter.isTag(elem)||adapter.getText(elem)!=="")),"first-child"(elem,{adapter:adapter,equals: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:adapter,equals: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:adapter,equals: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:adapter,equals: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:adapter,equals: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:adapter,equals:equals})=>adapter.getSiblings(elem).every((sibling=>equals(elem,sibling)||!adapter.isTag(sibling)))}
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`)}const aliases={"any-link":":is(a, area, link)[href]",link:":any-link:not(:visited)",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])",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])"}
const PLACEHOLDER_ELEMENT={}
function ensureIsTag(next,adapter){if(next===boolbase$1.falseFunc)return boolbase$1.falseFunc
return elem=>adapter.isTag(elem)&&next(elem)}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){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$1=(next,token,options,context,compileToken)=>{const func=compileToken(token,copyOptions(options),context)
return func===boolbase$1.trueFunc?next:func===boolbase$1.falseFunc?boolbase$1.falseFunc:elem=>func(elem)&&next(elem)}
const subselects={is:is$1,matches:is$1,where:is$1,not(next,token,options,context,compileToken){const func=compileToken(token,copyOptions(options),context)
return func===boolbase$1.falseFunc?next:func===boolbase$1.trueFunc?boolbase$1.falseFunc:elem=>!func(elem)&&next(elem)},has(next,subselect,options,_context,compileToken){const{adapter:adapter}=options
const opts=copyOptions(options)
opts.relativeSelector=true
const context=subselect.some((s=>s.some(isTraversal)))?[PLACEHOLDER_ELEMENT]:void 0
const compiled=compileToken(subselect,opts,context)
if(compiled===boolbase$1.falseFunc)return boolbase$1.falseFunc
const hasElement=ensureIsTag(compiled,adapter)
if(context&&compiled!==boolbase$1.trueFunc){const{shouldTestNextSiblings: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))}}
function compilePseudoSelector(next,selector,options,context,compileToken){var _a
const{name:name,data: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`)
const alias=parse$1w(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$1)return filters$1[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}`)}function getElementParent(node,adapter){const parent=adapter.getParent(node)
if(parent&&adapter.isTag(parent))return parent
return null}function compileGeneralSelector(next,selector,options,context,compileToken){const{adapter:adapter,equals: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")
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)
case SelectorType.Tag:{if(selector.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select")
let{name:name}=selector
options.xmlMode&&!options.lowerCaseTags||(name=name.toLowerCase())
return function tag(elem){return adapter.getName(elem)===name&&next(elem)}}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}
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":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
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}}function compile(selector,options,context){const next=compileUnsafe(selector,options,context)
return ensureIsTag(next,options.adapter)}function compileUnsafe(selector,options,context){const token=typeof selector==="string"?parse$1w(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}
function absolutize(token,{adapter:adapter},context){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);else{if(!hasContext||t.some(includesScopePseudo))continue
t.unshift(DESCENDANT_TOKEN)}t.unshift(SCOPE_TOKEN)}}function compileToken(token,options,context){var _a
token.forEach(sortByProcedure)
context=(_a=options.context)!==null&&_a!==void 0?_a:context
const isArrayContext=Array.isArray(context)
const finalContext=context&&(Array.isArray(context)?context:[context])
if(options