@asamuzakjp/dom-selector 6.4.7 → 6.5.0-a.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4399 @@
1
- var ut=Object.create;var ie=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var mt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var Et=(c,t)=>{for(var e in t)ie(c,e,{get:t[e],enumerable:!0})},Pe=(c,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!bt.call(c,s)&&s!==e&&ie(c,s,{get:()=>t[s],enumerable:!(o=pt(t,s))||o.enumerable});return c};var we=(c,t,e)=>(e=c!=null?ut(mt(c)):{},Pe(t||!c||!c.__esModule?ie(e,"default",{value:c,enumerable:!0}):e,c)),xt=c=>Pe(ie({},"__esModule",{value:!0}),c);var Bt={};Et(Bt,{DOMSelector:()=>Re});module.exports=xt(Bt);var U=require("css-tree");var Qe=we(require("@asamuzakjp/nwsapi"),1),Ze=we(require("bidi-js"),1),Oe=require("css-tree"),Se=we(require("is-potential-custom-element-name"),1);var B="AttributeSelector",j="ClassSelector",v="Combinator",We="Identifier",R="IdSelector",C="NotSupportedError",ne="Nth";var k="PseudoClassSelector",O="PseudoElementSelector";var Ye="Selector";var Ke="String",N="SyntaxError",L="all",S="first",$="lineal",D="self",F="TypeSelector";var ae="[A-Z\\d]+",wt="(?:first|last|only)-(?:child|of-type)",ye="(?:0|[1-9]\\d*)",G=`(?:-${ae})*`,V=`(?:any-)?link|${wt}|checked|empty|indeterminate|read-(?:only|write)|root|target`,yt=`[+-]?(?:${ye}n?|n)|(?:[+-]?${ye})?n\\s*[+-]\\s*${ye}`,X=`nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|${yt})\\s*\\)`,oe="\\[[^|\\]]+\\]|[#.:][\\w-]+",Nt="\\[[^|\\]]+\\]|[#.][\\w-]+",ze="(?:[A-Za-z][\\w-]*|[#.][\\w-]+)",I="\\*|[A-Za-z][\\w-]*",Ue="\\*|[A-Z][\\w-]*",re=`(?:${I}|(?:${I})?(?:${oe})+)`,Tt=`(?:${I}|(?:${I})?(?:${Nt})+)`,le="\\s?[\\s>~+]\\s?",Me=`${re}(?:${le}${re})*`,Be="\\s?[\\s>]\\s?",_t=`:is\\(\\s*${re}(?:\\s*,\\s*${re})*\\s*\\)`,gt=`:is\\(\\s*${Me}(?:\\s*,\\s*${Me})*\\s*\\)`,Fe=`(?:${I}|(?:${I})?(?:${oe}|${_t})+)`,Ge=`(?:${I}|(?:${I})?(?:${oe}|${gt})+)`,q=`(?:${Ue}|(?:${Ue})?(?:${oe})+)`,He=`${Ge}(?:${le}${Ge})*`,je=`(?:is|not)\\(\\s*${He}(?:\\s*,\\s*${He})*\\s*\\)`,Ne=`(?:is|not)\\(\\s*${Fe}(?:\\s*,\\s*${Fe})*\\s*\\)`,Te=`has\\([\\s>]?\\s*${Tt}\\s*\\)`,ce=Object.freeze(["button","input","select","textarea"]),Ve=Object.freeze(["button","reset","submit"]),_e=Object.freeze(["date","datetime-local","month","time","week"]),Q=Object.freeze(["email","password","search","tel","text","url"]),Z=Object.freeze([..._e,...Q,"number"]),Vt=Object.freeze(["checkbox","color","date","image","number","range","radio","time"]),P=Object.freeze(["has","is","not","where"]),Xe=Object.freeze(["Alt","AltGraph","CapsLock","Control","Fn","FnLock","Hyper","Meta","NumLock","ScrollLock","Shift","Super","Symbol","SymbolLock"]),qe=Object.freeze(["enabled","disabled","valid","invalid","in-range","out-of-range","checked","indeterminate","read-only","read-write","open","closed","placeholder-shown"]),fe=Object.freeze(["host","host-context"]);var Ct=new RegExp(`:(?!${V}|${X}|${je})`),Lt=new RegExp(`:(?!${V}|${X}|${Ne})`),$t=new RegExp(`:(?!${V}|${X}|${Ne}|${Te})`),vt=new RegExp(`:${Te}$`),Dt=new RegExp(`:(?!${V}|${X})`),T=c=>Object.prototype.toString.call(c).slice(8,-1);var Je=c=>{if(!c?.nodeType)throw new TypeError(`Unexpected type ${T(c)}`);let t,e,o;switch(c.nodeType){case 9:{t=c,e=c;break}case 11:{let{host:s,mode:a,ownerDocument:r}=c;t=r,e=c,o=s&&(a==="close"||a==="open");break}case 1:{t=c.ownerDocument;let s=c;for(;s;){let{host:a,mode:r,nodeType:f,parentNode:u}=s;if(f===11){o=a&&(r==="close"||r==="open");break}else if(u)s=u;else break}e=s;break}default:throw new TypeError(`Unexpected node ${c.nodeName}`)}return[t,e,!!o]},g=(c,t,e=!1)=>{if(!c?.nodeType)throw new TypeError(`Unexpected type ${T(c)}`);if(!t)return null;let o=t.currentNode;if(o===c)return o;if(e||o.contains(c)){for(o=t.nextNode();o&&o!==c;)o=t.nextNode();return o}else{if(o!==t.root){let s;for(;o;){if(o===c){s=!0;break}else if(o===t.root||o.contains(c))break;o=t.parentNode()}if(s)return o}if(c.nodeType===1){let s;for(;o;){if(o===c){s=!0;break}o=t.nextNode()}if(s)return o}}return null},ue=(c,t={})=>{if(!c?.nodeType)throw new TypeError(`Unexpected type ${T(c)}`);if(c.nodeType!==1)return!1;let{localName:e,ownerDocument:o}=c,{formAssociated:s}=t,a=o.defaultView,r,f=c.getAttribute("is");return f?r=(0,Se.default)(f)&&a.customElements.get(f):r=(0,Se.default)(e)&&a.customElements.get(e),r?s?!!r.formAssociated:!0:!1},ge=c=>{if(!c?.nodeType)throw new TypeError(`Unexpected type ${T(c)}`);if(typeof c.assignedNodes!="function")return null;let t=c.assignedNodes();if(t.length){let e;for(let o of t)if(e=o.textContent.trim(),e)break;return e}return c.textContent.trim()},he=c=>{if(!c?.nodeType)throw new TypeError(`Unexpected type ${T(c)}`);if(c.nodeType!==1)return null;let{dir:t,localName:e,parentNode:o}=c,{getEmbeddingLevels:s}=(0,Ze.default)();if(t==="ltr"||t==="rtl")return t;if(t==="auto"){let a;switch(e){case"input":{let r=[...Ve,...Q,"hidden"];if(!c.type||r.includes(c.type))a=c.value;else if(["checkbox","color","date","image","number","range","radio","time"].includes(c.type))return"ltr";break}case"slot":{a=ge(c);break}case"textarea":{a=c.value;break}default:{let r=[].slice.call(c.childNodes);for(let f of r){let{dir:u,localName:h,nodeType:n,textContent:i}=f;if(n===3?a=i.trim():n===1&&!["bdi","script","style","textarea"].includes(h)&&(!u||u!=="ltr"&&u!=="rtl")&&(h==="slot"?a=ge(f):a=i.trim()),a)break}}}if(a){let{paragraphs:[{level:r}]}=s(a);if(r%2===1)return"rtl"}else if(o){let{nodeType:r}=o;if(r===1)return he(o)}}else{if(e==="input"&&c.type==="tel")return"ltr";if(e==="bdi"){let a=c.textContent.trim();if(a){let{paragraphs:[{level:r}]}=s(a);if(r%2===1)return"rtl"}}else if(o){if(e==="slot"){let r=ge(c);if(r){let{paragraphs:[{level:f}]}=s(r);return f%2===1?"rtl":"ltr"}}let{nodeType:a}=o;if(a===1)return he(o)}}return"ltr"},ee=c=>{if(!c?.nodeType)throw new TypeError(`Unexpected type ${T(c)}`);if(c.nodeType!==1)return!1;if(typeof c.isContentEditable=="boolean")return c.isContentEditable;if(c.ownerDocument.designMode==="on")return!0;{let t;switch(c.hasAttribute("contenteditable")?t=c.getAttribute("contenteditable"):t="inherit",t){case"":case"true":return!0;case"plaintext-only":return!0;case"false":return!1;default:return c?.parentNode?.nodeType===1?ee(c.parentNode):!1}}},Ae=c=>{if(c?.nodeType!==1)return!1;let t=c.ownerDocument.defaultView,{display:e,visibility:o}=t.getComputedStyle(c);return e!=="none"&&o==="visible"},Ce=c=>{if(c?.nodeType!==1)return!1;let{localName:t,type:e}=c;switch(t){case"input":return!!(!e||Z.includes(e));case"textarea":return!0;default:return ee(c)}},pe=c=>{if(c?.nodeType!==1||!c.isConnected)return!1;let t=c.ownerDocument.defaultView;if(c instanceof t.HTMLElement){if(Number.isInteger(parseInt(c.getAttribute("tabindex")))||ee(c))return!0;let{localName:e,parentNode:o}=c;switch(e){case"a":return!!(c.href||c.hasAttribute("href"));case"iframe":return!0;case"input":return!(c.disabled||c.hasAttribute("disabled")||c.hidden||c.hasAttribute("hidden"));case"summary":{if(o.localName==="details"){let s=o.firstElementChild,a=!1;for(;s;){if(s.localName==="summary"){a=s===c;break}s=s.nextElementSibling}return a}return!1}default:if(["button","select","textarea"].includes(e)&&!(c.disabled||c.hasAttribute("disabled")))return!0}}else if(c instanceof t.SVGElement){if(Number.isInteger(parseInt(c.getAttributeNS(null,"tabindex")))){let e=["clipPath","defs","desc","linearGradient","marker","mask","metadata","pattern","radialGradient","script","style","symbol","title"],o="http://www.w3.org/2000/svg",s,a=c;for(;a.namespaceURI===o&&(s=e.includes(a.localName),!s);)if(a?.parentNode?.namespaceURI===o)a=a.parentNode;else break;return!s}if(c.localName==="a"&&(c.href||c.hasAttributeNS(null,"href")))return!0}return!1};var It=(c,t)=>{if(typeof c!="string")throw new TypeError(`Unexpected type ${T(c)}`);if(!t?.nodeType)throw new TypeError(`Unexpected type ${T(t)}`);if(!c||t.nodeType!==1)return null;let{attributes:e}=t,o;for(let s of e){let{name:a,namespaceURI:r,prefix:f,value:u}=s;if(a===`xmlns:${c}`?o=u:f===c&&(o=r),o)break}return o??null},et=(c="",t={})=>{if(!c||typeof c!="string"||t?.nodeType!==1)return!1;if(t.lookupNamespaceURI(c))return!0;let e=t.ownerDocument.documentElement,o=t,s;for(;o&&(s=It(c,o),!(s||o===e));)o=o.parentNode;return!!s},Rt=(c,t)=>{if(c?.nodeType){if(!t?.nodeType)throw new TypeError(`Unexpected type ${T(t)}`)}else throw new TypeError(`Unexpected type ${T(c)}`);if(c.nodeType!==1||t.nodeType!==1)return!1;let e=t.compareDocumentPosition(c);return!!(e&2||e&8)},de=(c=[])=>{let t=[...c];return t.length>1&&t.sort((e,o)=>{let s;return Rt(o,e)?s=1:s=-1,s}),t};var tt=(c,t)=>{if(!c?.DOMException)throw new TypeError(`Unexpected global object ${T(c)}`);t?.nodeType!==9&&(t=c.document);let e=(0,Qe.default)({document:t,DOMException:c.DOMException});return e.configure({LOGERRORS:!1}),e},te=(c,t={})=>{if(!c||typeof c!="string")return!1;let{complex:e,compound:o,descend:s,simple:a,target:r}=t;if(a||o)return!1;if(c.includes("[")){let f=c.lastIndexOf("[");if(c.substring(f).indexOf("]")<0)return!1}return/[|\\]|::|[^\u0021-\u007F\s]|\[\s*[\w$*=^|~-]+(?:(?:"[\w$*=^|~\s'-]+"|'[\w$*=^|~\s"-]+')?(?:\s+[\w$*=^|~-]+)+|"[^"\]]{1,255}|'[^'\]]{1,255})\s*\]|:(?:is|where)\(\s*\)/.test(c)?!1:c.includes(":")?s?!1:(r===D||r===$)&&/:has\(/.test(c)?!e||$t.test(c)?!1:vt.test(c):/:(?:is|not)\(/.test(c)?e?!Ct.test(c):!Lt.test(c):!Dt.test(c):!0};var _=require("css-tree"),it=/(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\(\s+\)/g,Le=/^part|slotted$/,be="\uFFFD",M=(c="")=>{if(typeof c=="string"&&c.indexOf("\\",0)>=0){let t=c.split("\\"),e=t.length;for(let o=1;o<e;o++){let s=t[o];if(s===""&&o===e-1)s=be;else{let a=/^([\da-f]{1,6}\s?)/i.exec(s);if(a){let[,r]=a,f;try{let h=parseInt("D800",16),n=parseInt("DFFF",16),i=parseInt(r,16);i===0||i>=h&&i<=n?f=be:f=String.fromCodePoint(i)}catch{f=be}let u="";s.length>r.length&&(u=s.substring(r.length)),s=`${f}${u}`}else/^[\n\r\f]/.test(s)&&(s="\\"+s)}t[o]=s}c=t.join("")}return c},Yt=(...c)=>{if(!c.length)throw new TypeError("1 argument required, but only 0 present.");let[t]=c;if(typeof t=="string"){let e=0;for(;e>=0&&(e=t.indexOf("#",e),!(e<0));){let o=t.substring(0,e+1),s=t.substring(e+1);if(/^\d$/.test(s.substring(0,1)))throw new DOMException(`Invalid selector ${t}`,N);let a=s.codePointAt(0);if(a===45){if(/^\d$/.test(s.substring(1,2)))throw new DOMException(`Invalid selector ${t}`,N)}else if(a>65535){let r=`\\${a.toString(16)} `;s.length===2?s=r:s=`${r}${s.substring(2)}`}t=`${o}${s}`,e++}t=t.replace(/\f|\r\n?/g,`
2
- `).replace(/[\0\uD800-\uDFFF]|\\$/g,be)}else if(t==null)t=T(t).toLowerCase();else if(Array.isArray(t))t=t.join(",");else if(Object.prototype.hasOwnProperty.call(t,"toString"))t=t.toString();else throw new DOMException(`Invalid selector ${t}`,N);return t.replace(/\x26/g,":scope")},H=c=>{if(c=Yt(c),/^$|^\s*>|,\s*$/.test(c))throw new DOMException(`Invalid selector ${c}`,N);let t;try{let e=(0,U.parse)(c,{context:"selectorList",parseCustomProperty:!0});t=(0,U.toPlainObject)(e)}catch(e){let{message:o}=e;if(/^(?:"\]"|Attribute selector [()\s,=~^$*|]+) is expected$/.test(o)&&!c.endsWith("]")){let s=c.lastIndexOf("["),a=c.substring(s);a.includes('"')?a.match(/"/g).length%2?t=H(`${c}"]`):t=H(`${c}]`):t=H(`${c}]`)}else if(o==='")" is expected')if(it.test(c))t=H(`${c.replaceAll(it,"()")}`);else if(!c.endsWith(")"))t=H(`${c})`);else throw new DOMException(`Invalid selector ${c}`,N);else throw new DOMException(`Invalid selector ${c}`,N)}return t},z=(c={})=>{let t=new Set,e=new Map;return(0,U.walk)(c,{enter:s=>{switch(s.type){case Ye:{t.add(s.children);break}case k:{P.includes(s.name)?(e.set("hasNestedSelector",!0),e.set("hasLogicalPseudoFunc",!0),s.name==="has"&&e.set("hasHasPseudoFunc",!0)):qe.includes(s.name)?e.set("hasStatePseudoClass",!0):fe.includes(s.name)&&Array.isArray(s.children)&&s.children.length&&e.set("hasNestedSelector",!0);break}case O:{Le.test(s.name)&&e.set("hasNestedSelector",!0);break}case ne:{s.selector&&(e.set("hasNestedSelector",!0),e.set("hasNthChildOfSelector",!0));break}default:}}}),e.get("hasNestedSelector")&&(0,U.findAll)(c,(s,a,r)=>{if(r){if(s.type===k&&P.includes(s.name)){let f=r.filter(u=>{let{name:h,type:n}=u;return n===k&&P.includes(h)});for(let{children:u}of f)for(let{children:h}of u)for(let{children:n}of h)t.has(n)&&t.delete(n)}else if(s.type===k&&fe.includes(s.name)&&Array.isArray(s.children)&&s.children.length){let f=r.filter(u=>{let{children:h,name:n,type:i}=u;return i===k&&fe.includes(n)&&Array.isArray(h)&&h.length});for(let{children:u}of f)for(let{children:h}of u)t.has(h)&&t.delete(h)}else if(s.type===O&&Le.test(s.name)){let f=r.filter(u=>{let{name:h,type:n}=u;return n===O&&Le.test(h)});for(let{children:u}of f)for(let{children:h}of u)t.has(h)&&t.delete(h)}else if(s.type===ne&&s.selector){let f=r.filter(u=>{let{selector:h,type:n}=u;return n===ne&&h});for(let{selector:u}of f){let{children:h}=u;for(let{children:n}of h)t.has(n)&&t.delete(n)}}}}),{branches:[...t],info:Object.fromEntries(e)}},ve=c=>{let t=[...c];if(t.length>1){let e=new Map([[O,1],[R,2],[j,4],[F,8],[B,16],[k,32]]);t.sort((o,s)=>{let{type:a}=o,{type:r}=s,f=e.get(a),u=e.get(r),h;return f===u?h=0:f>u?h=1:h=-1,h})}return t},De=c=>{let t,e;if(c&&typeof c=="string")c.indexOf("|")>-1?[t,e]=c.split("|"):(t="*",e=c);else throw new DOMException(`Invalid selector ${c}`,N);return{prefix:t,localName:e}};var Ee=(c,t,e={})=>{let{forgive:o,warn:s}=e;if(t===O)switch(c){case"after":case"backdrop":case"before":case"cue":case"cue-region":case"first-letter":case"first-line":case"file-selector-button":case"marker":case"placeholder":case"selection":case"target-text":{if(s)throw new DOMException(`Unsupported pseudo-element ::${c}`,C);break}case"part":case"slotted":{if(s)throw new DOMException(`Unsupported pseudo-element ::${c}()`,C);break}default:if(c.startsWith("-webkit-")){if(s)throw new DOMException(`Unsupported pseudo-element ::${c}`,C)}else if(!o)throw new DOMException(`Unknown pseudo-element ::${c}`,N)}else throw new TypeError(`Unexpected ast type ${T(t)}`)},rt=(c,t)=>{let{name:e}=c;if(!e){let s;throw e===""?s="(empty String)":s=T(e),new TypeError(`Unexpected ast type ${s}`)}let o=he(t);return e===o},nt=(c,t)=>{let{name:e,type:o,value:s}=c,a;o===Ke&&s?a=s:o===We&&e&&(a=M(e));let{contentType:r}=t.ownerDocument,f=/^(?:application\/xhtml\+x|text\/ht)ml$/.test(r),u=/^(?:application\/(?:[\w\-.]+\+)?|image\/[\w\-.]+\+|text\/)xml$/.test(r);if(a==="*")if(f&&t.hasAttribute("lang")||u&&t.hasAttribute("xml:lang")){if(f&&t.getAttribute("lang")||u&&t.getAttribute("xml:lang"))return!0}else{let h=t.parentNode,n;for(;h&&h.nodeType===1;){if(f&&h.hasAttribute("lang")||u&&h.hasAttribute("xml:lang")){(f&&h.hasAttribute("lang")||u&&h.hasAttribute("xml:lang"))&&(n=!0);break}h=h.parentNode}return!!n}else if(a&&new RegExp(`^(?:\\*-)?${ae}${G}$`,"i").test(a)){let n;if(a.indexOf("-")>-1){let[i,l,...p]=a.split("-"),m;i==="*"?m=`${ae}${G}`:m=`${i}${G}`;let d=`-${l}${G}`,E=p.length,b="";if(E)for(let x=0;x<E;x++)b+=`-${p[x]}${G}`;n=new RegExp(`^${m}${d}${b}$`,"i")}else n=new RegExp(`^${a}${G}$`,"i");if(f&&t.hasAttribute("lang")||u&&t.hasAttribute("xml:lang")){let i=f&&t.getAttribute("lang")||u&&t.getAttribute("xml:lang")||"";return n.test(i)}else{let i=t.parentNode,l;for(;i&&i.nodeType===1;){if(f&&i.hasAttribute("lang")||u&&i.hasAttribute("xml:lang")){let p=f&&i.getAttribute("lang")||u&&i.getAttribute("xml:lang")||"";l=n.test(p);break}i=i.parentNode}return!!l}}return!1},at=(c,t)=>{let{flags:e,matcher:o,name:s,value:a}=c;if(typeof e=="string"&&!/^[is]$/i.test(e)){let f=(0,_.generate)(c);throw new DOMException(`Invalid selector ${f}`,N)}let{attributes:r}=t;if(r?.length){let f=t.ownerDocument.contentType,u;f==="text/html"?typeof e=="string"&&/^s$/i.test(e)?u=!1:u=!0:typeof e=="string"&&/^i$/i.test(e)?u=!0:u=!1;let h=M(s.name);u&&(h=h.toLowerCase());let n=new Set;if(h.indexOf("|")>-1){let{prefix:i,localName:l}=De(h);for(let p of r){let{name:m,value:d}=p;switch(u&&(m=m.toLowerCase(),d=d.toLowerCase()),i){case"":{l===m&&n.add(d);break}case"*":{m.indexOf(":")>-1?m.endsWith(`:${l}`)&&n.add(d):l===m&&n.add(d);break}default:if(m.indexOf(":")>-1){let[E,b]=m.split(":");if(E==="xml"&&b==="lang")continue;i===E&&l===b&&et(i,t)&&n.add(d)}}}}else for(let{name:i,value:l}of r)if(u&&(i=i.toLowerCase(),l=l.toLowerCase()),i.indexOf(":")>-1){let[p,m]=i.split(":");if(p==="xml"&&m==="lang")continue;h===m&&n.add(l)}else h===i&&n.add(l);if(n.size){let{name:i,value:l}=a??{},p;switch(i?u?p=i.toLowerCase():p=i:l?u?p=l.toLowerCase():p=l:l===""&&(p=l),o){case"=":return typeof p=="string"&&n.has(p);case"~=":{if(p&&typeof p=="string"){let m;for(let d of n)if(new Set(d.split(/\s+/)).has(p)){m=!0;break}return!!m}return!1}case"|=":{if(p&&typeof p=="string"){let m;for(let d of n)if(d===p||d.startsWith(`${p}-`)){m=d;break}return!!m}return!1}case"^=":{if(p&&typeof p=="string"){let m;for(let d of n)if(d.startsWith(`${p}`)){m=d;break}return!!m}return!1}case"$=":{if(p&&typeof p=="string"){let m;for(let d of n)if(d.endsWith(`${p}`)){m=d;break}return!!m}return!1}case"*=":{if(p&&typeof p=="string"){let m;for(let d of n)if(d.includes(`${p}`)){m=d;break}return!!m}return!1}case null:default:return!0}}}return!1},ot=(c,t,e={})=>{let o=M(c.name),{localName:s,namespaceURI:a,prefix:r}=t,{forgive:f}=e,{prefix:u,localName:h}=De(o,t);t.ownerDocument.contentType==="text/html"&&/[A-Z][\\w-]*/i.test(s)&&(u=u.toLowerCase(),h=h.toLowerCase());let n,i;switch(s.indexOf(":")>-1?[n,i]=s.split(":"):(n=r||"",i=s),u){case"":return!n&&!a&&(h==="*"||h===i);case"*":return h==="*"||h===i;default:{let l=t.lookupNamespaceURI(u),p=t.lookupNamespaceURI(n);if(l===p&&u===n)return h==="*"||h===i;if(!f&&!l)throw new DOMException(`Undeclared namespace ${u}`,N);return!1}}};var W="next",Y="prev",xe=class{#r;#a;#i;#s;#h;#c;#d;#f;#m;#l;#e;#p;#y;#b;#x;#n;#N;#u;#w;#E;#o;#t;constructor(t){this.#t=t,this.#a=new WeakMap,this.#h=new WeakMap,this.#m=new WeakMap,this.#x=new WeakMap,this.#c=null,this.#d=null,this.#l=null,this._registerEventListeners()}onError(t,e={}){if(!(e.noexcept??this.#y))if(t instanceof DOMException||t instanceof this.#t.DOMException)if(t.name===C)this.#o&&console.warn(t.message);else throw new this.#t.DOMException(t.message,t.name);else throw t.name in this.#t?new this.#t[t.name](t.message):t}setup(t,e,o={}){let{noexcept:s,warn:a}=o;return this.#y=!!s,this.#o=!!a,this.#e=e,[this.#s,this.#n,this.#u]=Je(e),this.#N=t,[this.#r,this.#p]=this._correspond(t),this.#m=new WeakMap,this.#E=new WeakMap,this.#w=null,this}_registerEventListeners(){let t={capture:!0,passive:!0},e=[],o=["focus","focusin"];for(let r of o)e.push(this.#t.addEventListener(r,f=>{this.#d=f},t));let s=["keydown","keyup"];for(let r of s)e.push(this.#t.addEventListener(r,f=>{let{key:u}=f;Xe.includes(u)||(this.#c=f)},t));let a=["mouseover","mousedown","mouseup","click","mouseout"];for(let r of a)e.push(this.#t.addEventListener(r,f=>{this.#c=f},t));return e}_correspond(t){let e=[];this.#i=!1,this.#f=!1;let o;if(this.#h.has(this.#s)){let s=this.#h.get(this.#s);if(s&&s.has(`${t}`)){let a=s.get(`${t}`);o=a.ast,this.#i=a.descendant,this.#f=a.invalidate}}if(o){let s=o.length;for(let a=0;a<s;a++)o[a].dir=null,o[a].filtered=!1,o[a].find=!1,e[a]=[]}else{let s;try{s=H(t)}catch(d){return this.onError(d)}let{branches:a,info:r}=z(s),{hasHasPseudoFunc:f,hasLogicalPseudoFunc:u,hasNthChildOfSelector:h,hasStatePseudoClass:n}=r,i=f||n||!!(u&&h),l=!1,p=0;o=[];for(let[...d]of a){let E=[],b=d.shift();if(b&&b.type!==v){let x=new Set;for(;b;){let y=b.name;if(b.type===v){let[A]=d;if(A.type===v)return this.onError(new this.#t.DOMException(`Invalid selector ${t}`,N));y==="+"||y==="~"?i=!0:l=!0,E.push({combo:b,leaves:ve(x)}),x.clear()}else b&&(y&&typeof y=="string"&&(y=M(y),typeof y=="string"&&y!==b.name&&(b.name=y),/[|:]/.test(y)&&(b.namespace=!0)),x.add(b));if(d.length)b=d.shift();else{E.push({combo:null,leaves:ve(x)}),x.clear();break}}}o.push({branch:E,dir:null,filtered:!1,find:!1}),e[p]=[],p++}let m;this.#h.has(this.#s)?m=this.#h.get(this.#s):m=new Map,m.set(`${t}`,{ast:o,descendant:l,invalidate:i}),this.#h.set(this.#s,m),this.#i=l,this.#f=i}return[o,e]}_createTreeWalker(t,e={}){let{force:o=!1,whatToShow:s=1281}=e,a;return o?a=this.#s.createTreeWalker(t,s):this.#E.has(t)?a=this.#E.get(t):(a=this.#s.createTreeWalker(t,s),this.#E.set(t,a)),a}_prepareQuerySelectorWalker(){return this.#b=this._createTreeWalker(this.#e),this.#b}_collectNthChild(t,e,o={}){let{a:s,b:a,reverse:r,selector:f}=t,{parentNode:u}=e,h=new Set,n;if(f){if(this.#a.has(f))n=this.#a.get(f);else{let{branches:l}=z(f);n=l,this.#f||this.#a.set(f,n)}let{branches:i}=z(f);n=i}if(u){let i=this._createTreeWalker(u,{force:!0}),l=i.firstChild(),p=new Set,m=0;if(n)for(;l;){if(Ae(l)){let d;for(let E of n)if(d=this._matchLeaves(E,l,o),!d)break;d&&p.add(l)}m++,l=i.nextSibling()}else for(;l;)m++,l=i.nextSibling();if(s===0){if(a>0&&a<=m){if(p.size){l=g(u,i),r?l=i.lastChild():l=i.firstChild();let d=0;for(;l;){if(p.has(l)){if(d===a-1){h.add(l);break}d++}r?l=i.previousSibling():l=i.nextSibling()}}else if(!f){l=g(u,i),r?l=i.lastChild():l=i.firstChild();let d=0;for(;l;){if(d===a-1){h.add(l);break}r?l=i.previousSibling():l=i.nextSibling(),d++}}}}else{let d=a-1;if(s>0)for(;d<0;)d+=s;if(d>=0&&d<m){l=g(u,i),r?l=i.lastChild():l=i.firstChild();let E=0,b=s>0?0:a-1;for(;l&&(l&&d>=0&&d<m);)p.size?p.has(l)&&(b===d&&(h.add(l),d+=s),s>0?b++:b--):E===d&&(f||h.add(l),d+=s),r?l=i.previousSibling():l=i.nextSibling(),E++}}if(r&&h.size>1){let d=[...h];return new Set(d.reverse())}}else if(e===this.#n&&s+a===1)if(n){let i;for(let l of n)if(i=this._matchLeaves(l,e,o),i)break;i&&h.add(e)}else h.add(e);return h}_collectNthOfType(t,e){let{a:o,b:s,reverse:a}=t,{localName:r,namespaceURI:f,parentNode:u,prefix:h}=e,n=new Set;if(u){let i=this._createTreeWalker(u,{force:!0}),l=g(u,i);l=i.firstChild();let p=0;for(;l;)p++,l=i.nextSibling();if(o===0){if(s>0&&s<=p){l=g(u,i),a?l=i.lastChild():l=i.firstChild();let m=0;for(;l;){let{localName:d,namespaceURI:E,prefix:b}=l;if(d===r&&b===h&&E===f){if(m===s-1){n.add(l);break}m++}a?l=i.previousSibling():l=i.nextSibling()}}}else{let m=s-1;if(o>0)for(;m<0;)m+=o;if(m>=0&&m<p){l=g(u,i),a?l=i.lastChild():l=i.firstChild();let d=o>0?0:s-1;for(;l;){let{localName:E,namespaceURI:b,prefix:x}=l;if(E===r&&x===h&&b===f){if(d===m&&(n.add(l),m+=o),m<0||m>=p)break;o>0?d++:d--}a?l=i.previousSibling():l=i.nextSibling()}}}if(a&&n.size>1){let m=[...n];return new Set(m.reverse())}}else e===this.#n&&o+s===1&&n.add(e);return n}_matchAnPlusB(t,e,o,s={}){let{nth:{a,b:r,name:f},selector:u}=t,h=new Map;if(f?(f==="even"?(h.set("a",2),h.set("b",0)):f==="odd"&&(h.set("a",2),h.set("b",1)),o.indexOf("last")>-1&&h.set("reverse",!0)):(typeof a=="string"&&/-?\d+/.test(a)?h.set("a",a*1):h.set("a",0),typeof r=="string"&&/-?\d+/.test(r)?h.set("b",r*1):h.set("b",0),o.indexOf("last")>-1&&h.set("reverse",!0)),o==="nth-child"||o==="nth-last-child"){u&&h.set("selector",u);let n=Object.fromEntries(h);return this._collectNthChild(n,e,s)}else if(o==="nth-of-type"||o==="nth-last-of-type"){let n=Object.fromEntries(h);return this._collectNthOfType(n,e)}return new Set}_matchHasPseudoFunc(t,e,o={}){if(Array.isArray(t)&&t.length){let s=[...t],[a]=s,{type:r}=a,f;r===v?f=s.shift():f={name:" ",type:v};let u=[];for(;s.length;){let[i]=s,{type:l}=i;if(l===v)break;u.push(s.shift())}let h={combo:f,leaves:u};o.dir=W;let n=this._matchCombinator(h,e,o);if(n.size){if(s.length){let i=!1;for(let l of n)if(i=this._matchHasPseudoFunc(s,l,o),i)break;return i}return!0}}return!1}_matchLogicalPseudoFunc(t,e,o={}){let{astName:s,branches:a,twigBranches:r}=t,f=(o.isShadowRoot||this.#u)&&e.nodeType===11;if(s==="has"){let u;for(let h of a)if(u=this._matchHasPseudoFunc(h,e,o),u)break;if(u)if(f){if(this.#w)return e}else return e}else{if(f){let n;for(let i of a)if(i.length>1){n=!0;break}else if(s==="not"){let[{type:l}]=i;if(l!==k){n=!0;break}}if(n)return null}o.forgive=s==="is"||s==="where";let u=r.length,h;for(let n=0;n<u;n++){let i=r[n],l=i.length-1,{leaves:p}=i[l];if(h=this._matchLeaves(p,e,o),h&&l>0){let m=new Set([e]);for(let d=l-1;d>=0;d--){let E=i[d],b=[];o.dir=Y;for(let x of m){let y=this._matchCombinator(E,x,o);y.size&&b.push(...y)}if(b.length)d===0?h=!0:m=new Set(b);else{h=!1;break}}}if(h)break}if(s==="not")return h?null:e;if(h)return e}return null}_matchPseudoClassSelector(t,e,o={}){let{children:s,name:a}=t,{localName:r,parentNode:f}=e,{forgive:u,warn:h=this.#o}=o,n=new Set;if(Array.isArray(s)&&P.includes(a)){if(!s.length&&a!=="is"&&a!=="where"){let p=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${p}`,N))}let i;if(this.#a.has(t))i=this.#a.get(t);else{let{branches:p}=z(t);if(a==="has"){let m;for(let d of s){let E=(0,_.find)(d,b=>P.includes(b.name)&&(0,_.find)(b,x=>x.name==="has")?b:null);if(E){let b=E.name;if(b==="is"||b==="where"){m=!0;break}else{let x=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${x}`,N))}}}if(m)return n;i={astName:a,branches:p}}else{let m=[];for(let[...d]of p){let E=[],b=new Set,x=d.shift();for(;x;)if(x.type===v?(E.push({combo:x,leaves:[...b]}),b.clear()):x&&b.add(x),d.length)x=d.shift();else{E.push({combo:null,leaves:[...b]}),b.clear();break}m.push(E)}i={astName:a,branches:p,twigBranches:m},this.#f||this.#a.set(t,i)}}let l=this._matchLogicalPseudoFunc(i,e,o);l&&n.add(l)}else if(Array.isArray(s))if(/^nth-(?:last-)?(?:child|of-type)$/.test(a)){if(s.length!==1){let p=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${p}`,N))}let[i]=s;return this._matchAnPlusB(i,e,a,o)}else switch(a){case"dir":{if(s.length!==1){let p=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${p}`,N))}let[i]=s;rt(i,e)&&n.add(e);break}case"lang":{if(!s.length){let l=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${l}`,N))}let i;for(let l of s)if(i=nt(l,e),i)break;i&&n.add(e);break}case"state":{if(ue(e)){let[{value:i}]=s;if(i)if(e[i])n.add(e);else for(let l in e){let p=e[l];if(p instanceof this.#t.ElementInternals){p?.states?.has(i)&&n.add(e);break}}}break}case"current":case"nth-col":case"nth-last-col":{h&&this.onError(new this.#t.DOMException(`Unsupported pseudo-class :${a}()`,C));break}case"host":case"host-context":break;case"contains":{h&&this.onError(new this.#t.DOMException(`Unknown pseudo-class :${a}()`,C));break}default:u||this.onError(new this.#t.DOMException(`Unknown pseudo-class :${a}()`,N))}else switch(a){case"any-link":case"link":{(r==="a"||r==="area")&&e.hasAttribute("href")&&n.add(e);break}case"local-link":{if((r==="a"||r==="area")&&e.hasAttribute("href")){let{href:i,origin:l,pathname:p}=new URL(this.#s.URL),m=new URL(e.getAttribute("href"),i);m.origin===l&&m.pathname===p&&n.add(e)}break}case"visited":break;case"hover":{let{target:i,type:l}=this.#c??{};/^(?:click|mouse(?:down|over|up))$/.test(l)&&e.contains(i)&&n.add(e);break}case"active":{let{buttons:i,target:l,type:p}=this.#c??{};p==="mousedown"&&i&1&&e.contains(l)&&n.add(e);break}case"target":{let{hash:i}=new URL(this.#s.URL);e.id&&i===`#${e.id}`&&this.#s.contains(e)&&n.add(e);break}case"target-within":{let{hash:i}=new URL(this.#s.URL);if(i){let l=i.replace(/^#/,""),p=this.#s.getElementById(l);for(;p;){if(p===e){n.add(e);break}p=p.parentNode}}break}case"scope":{this.#e.nodeType===1?!this.#u&&e===this.#e&&n.add(e):e===this.#s.documentElement&&n.add(e);break}case"focus":{e===this.#s.activeElement&&pe(e)&&n.add(e);break}case"focus-visible":{if(e===this.#s.activeElement&&pe(e)){let i;if(Ce(e))i=!0;else if(this.#d){let{relatedTarget:l,target:p}=this.#d;if(p===e)if(Ce(l))i=!0;else if(this.#c){let{key:m,target:d,type:E}=this.#c;d===l?(this.#l===null||p===this.#l)&&(i=!0):m==="Tab"?(E==="keydown"&&d!==e||E==="keyup"&&d===e)&&(d===p?(this.#l===null||d===this.#l&&l===null)&&(i=!0):i=!0):m&&(E==="keydown"||E==="keyup")&&d===e&&(i=!0)}else(l===null||l===this.#l)&&(i=!0)}i?(this.#l=e,n.add(e)):this.#l===e&&(this.#l=null)}break}case"focus-within":{let i,l=this.#s.activeElement;if(pe(l))for(;l;){if(l===e){i=!0;break}l=l.parentNode}i&&n.add(e);break}case"open":case"closed":{(r==="details"||r==="dialog")&&(e.hasAttribute("open")?a==="open"&&n.add(e):a==="closed"&&n.add(e));break}case"disabled":case"enabled":{if([...ce,"fieldset","optgroup","option"].includes(r)||ue(e,{formAssociated:!0})){let l;if(e.disabled||e.hasAttribute("disabled"))l=!0;else if(e.localName==="option")f.localName==="optgroup"&&(f.disabled||f.hasAttribute("disabled"))&&(l=!0);else if(e.localName!=="optgroup"){let p=f;for(;p;)if(p.localName==="fieldset"&&(p.disabled||p.hasAttribute("disabled"))){let m=p.firstElementChild;for(;m&&m.localName!=="legend";)m=m.nextElementSibling;m&&m.contains(e)||(l=!0);break}else{if(p.localName==="form")break;if(p.parentNode?.nodeType===1){if(p.parentNode.localName==="form")break;p=p.parentNode}else break}}l?a==="disabled"&&n.add(e):a==="enabled"&&n.add(e)}break}case"read-only":case"read-write":{let i,l;switch(r){case"textarea":{e.readOnly||e.hasAttribute("readonly")||e.disabled||e.hasAttribute("disabled")?i=!0:l=!0;break}case"input":{!e.type||Z.includes(e.type)?e.readOnly||e.hasAttribute("readonly")||e.disabled||e.hasAttribute("disabled")?i=!0:l=!0:i=!0;break}default:ee(e)?l=!0:i=!0}i?a==="read-only"&&n.add(e):a==="read-write"&&l&&n.add(e);break}case"placeholder-shown":{let i;if(e.placeholder?i=e.placeholder:e.hasAttribute("placeholder")&&(i=e.getAttribute("placeholder")),typeof i=="string"&&!/[\r\n]/.test(i)){let l;r==="textarea"?l=e:r==="input"&&(e.hasAttribute("type")?[...Q,"number"].includes(e.getAttribute("type"))&&(l=e):l=e),l&&e.value===""&&n.add(e)}break}case"checked":{let i=e.getAttribute("type");(e.checked&&r==="input"&&(i==="checkbox"||i==="radio")||e.selected&&r==="option")&&n.add(e);break}case"indeterminate":{if(e.indeterminate&&r==="input"&&e.type==="checkbox"||r==="progress"&&!e.hasAttribute("value"))n.add(e);else if(r==="input"&&e.type==="radio"&&!e.hasAttribute("checked")){let i=e.name,l=e.parentNode;for(;l&&l.localName!=="form";)l=l.parentNode;l||(l=this.#s.documentElement);let p=this._createTreeWalker(l),m=g(l,p);m=p.firstChild();let d;for(;m&&!(m.localName==="input"&&m.getAttribute("type")==="radio"&&(m.hasAttribute("name")?m.getAttribute("name")===i&&(d=!!m.checked):d=!!m.checked,d));)m=p.nextNode();d||n.add(e)}break}case"default":{let i=["checkbox","radio"],l=["button","reset"],p=["image","submit"],m=e.getAttribute("type");if(r==="button"&&!(e.hasAttribute("type")&&l.includes(m))||r==="input"&&e.hasAttribute("type")&&p.includes(m)){let d=e.parentNode;for(;d&&d.localName!=="form";)d=d.parentNode;if(d){let E=this._createTreeWalker(d),b=g(d,E);for(b=E.firstChild();b;){let x=b.localName,y=b.getAttribute("type"),A;if(x==="button"?A=!(b.hasAttribute("type")&&l.includes(y)):x==="input"&&(A=b.hasAttribute("type")&&p.includes(y)),A){b===e&&n.add(e);break}b=E.nextNode()}}}else(r==="input"&&e.hasAttribute("type")&&i.includes(m)&&e.hasAttribute("checked")||r==="option"&&e.hasAttribute("selected"))&&n.add(e);break}case"valid":case"invalid":{let i=[...ce,"form"];if(i.includes(r)){let l;e.checkValidity()&&(e.maxLength>=0?e.maxLength>=e.value.length&&(l=!0):l=!0),l?a==="valid"&&n.add(e):a==="invalid"&&n.add(e)}else if(r==="fieldset"){let l=this._createTreeWalker(e),p=g(e,l);p=l.firstChild();let m;if(!p)m=!0;else for(;p&&!(i.includes(p.localName)&&(p.checkValidity()?p.maxLength>=0?m=p.maxLength>=p.value.length:m=!0:m=!1,!m));)p=l.nextNode();m?a==="valid"&&n.add(e):a==="invalid"&&n.add(e)}break}case"in-range":case"out-of-range":{let i=[..._e,"number","range"],l=e.getAttribute("type");if(r==="input"&&!(e.readonly||e.hasAttribute("readonly"))&&!(e.disabled||e.hasAttribute("disabled"))&&i.includes(l)){let p=e.validity.rangeUnderflow||e.validity.rangeOverflow;(a==="out-of-range"&&p||a==="in-range"&&!p&&(e.hasAttribute("min")||e.hasAttribute("max")||l==="range"))&&n.add(e)}break}case"required":case"optional":{let i,l;if(r==="select"||r==="textarea")e.required||e.hasAttribute("required")?i=!0:l=!0;else if(r==="input")if(e.hasAttribute("type")){let p=[...Z,"checkbox","file","radio"],m=e.getAttribute("type");p.includes(m)&&(e.required||e.hasAttribute("required"))?i=!0:l=!0}else e.required||e.hasAttribute("required")?i=!0:l=!0;(a==="required"&&i||a==="optional"&&l)&&n.add(e);break}case"root":{e===this.#s.documentElement&&n.add(e);break}case"empty":{if(e.hasChildNodes()){let i=this._createTreeWalker(e,{force:!0,whatToShow:4294967295}),l=i.firstChild(),p;for(;l&&(p=l.nodeType!==1&&l.nodeType!==3,!!p);)l=i.nextSibling();p&&n.add(e)}else n.add(e);break}case"first-child":{(f&&e===f.firstElementChild||e===this.#n)&&n.add(e);break}case"last-child":{(f&&e===f.lastElementChild||e===this.#n)&&n.add(e);break}case"only-child":{(f&&e===f.firstElementChild&&e===f.lastElementChild||e===this.#n)&&n.add(e);break}case"first-of-type":{if(f){let[i]=this._collectNthOfType({a:0,b:1},e);i&&n.add(i)}else e===this.#n&&n.add(e);break}case"last-of-type":{if(f){let[i]=this._collectNthOfType({a:0,b:1,reverse:!0},e);i&&n.add(i)}else e===this.#n&&n.add(e);break}case"only-of-type":{if(f){let[i]=this._collectNthOfType({a:0,b:1},e);if(i===e){let[l]=this._collectNthOfType({a:0,b:1,reverse:!0},e);l===e&&n.add(e)}}else e===this.#n&&n.add(e);break}case"defined":{e.hasAttribute("is")||r.includes("-")?ue(e)&&n.add(e):(e instanceof this.#t.HTMLElement||e instanceof this.#t.SVGElement)&&n.add(e);break}case"popover-open":{e.popover&&Ae(e)&&n.add(e);break}case"host":case"host-context":break;case"after":case"before":case"first-letter":case"first-line":{h&&this.onError(new this.#t.DOMException(`Unsupported pseudo-element ::${a}`,C));break}case"autofill":case"blank":case"buffering":case"current":case"fullscreen":case"future":case"has-slotted":case"modal":case"muted":case"past":case"paused":case"picture-in-picture":case"playing":case"seeking":case"stalled":case"user-invalid":case"user-valid":case"volume-locked":case"-webkit-autofill":{h&&this.onError(new this.#t.DOMException(`Unsupported pseudo-class :${a}`,C));break}default:a.startsWith("-webkit-")?h&&this.onError(new this.#t.DOMException(`Unsupported pseudo-class :${a}`,C)):u||this.onError(new this.#t.DOMException(`Unknown pseudo-class :${a}`,N))}return n}_matchShadowHostPseudoClass(t,e){let{children:o,name:s}=t;if(Array.isArray(o)){if(o.length!==1){let h=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${h}`,N))}let{branches:a}=z(o[0]),[r]=a,[...f]=r,{host:u}=e;if(s==="host"){let h;for(let n of f){let{type:i}=n;if(i===v){let l=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${l}`,N))}if(h=this._matchSelector(n,u).has(u),!h)break}return h?e:null}else if(s==="host-context"){let h=u,n;for(;h;){for(let i of f){let{type:l}=i;if(l===v){let p=(0,_.generate)(t);return this.onError(new this.#t.DOMException(`Invalid selector ${p}`,N))}if(n=this._matchSelector(i,h).has(h),!n)break}if(n)break;h=h.parentNode}return n?e:null}}else if(s==="host")return e;return this.onError(new this.#t.DOMException(`Invalid selector :${s}`,N))}_matchSelector(t,e,o={}){let{type:s}=t,a=M(t.name),r=new Set;if(e.nodeType===1)switch(s){case B:{at(t,e)&&r.add(e);break}case R:{e.id===a&&r.add(e);break}case j:{e.classList.contains(a)&&r.add(e);break}case k:return this._matchPseudoClassSelector(t,e,o);case F:{ot(t,e,o)&&r.add(e);break}case O:default:try{Ee(a,s,o)}catch(f){this.onError(f)}}else if(this.#u&&s===k&&e.nodeType===11){if(P.includes(a))return o.isShadowRoot=!0,this._matchPseudoClassSelector(t,e,o);if(a==="host"||a==="host-context"){let f=this._matchShadowHostPseudoClass(t,e,o);f&&(this.#w=!0,r.add(f))}}return r}_matchLeaves(t,e,o={}){let s;if(this.#f?s=this.#m.get(t):s=this.#x.get(t),s&&s.has(e)){let{matched:a}=s.get(e);return a}else{let a=!0,r=[...ce,"fieldset","form"],f=["any-link","defined","dir","link"];e.nodeType===1&&r.includes(e.localName)&&(a=!1);let u;for(let h of t){switch(h.type){case B:case R:{a=!1;break}case k:{f.includes(h.name)&&(a=!1);break}default:}if(u=this._matchSelector(h,e,o).has(e),!u)break}return a&&(s||(s=new WeakMap),s.set(e,{matched:u}),this.#f?this.#m.set(t,s):this.#x.set(t,s)),u}}_findDescendantNodes(t,e,o={}){let[s,...a]=t,r=a.length>0,{type:f}=s,u=M(s.name),h=new Set,n=!1;if(this.#u||e.nodeType!==1)n=!0;else switch(f){case O:{Ee(u,f,o);break}case R:{if(this.#n.nodeType===1)n=!0;else{let i=this.#n.getElementById(u);i&&i!==e&&e.contains(i)&&(r?this._matchLeaves(a,i,o)&&h.add(i):h.add(i))}break}default:n=!0}if(n){let i=this._createTreeWalker(e),l=g(e,i);for(l=i.firstChild();l;)this._matchLeaves(t,l,o)&&h.add(l),l=i.nextNode()}return h}_matchCombinator(t,e,o={}){let{combo:s,leaves:a}=t,{name:r}=s,{parentNode:f}=e,{dir:u}=o,h=new Set;if(u===W)switch(r){case"+":{let n=e.nextElementSibling;n&&this._matchLeaves(a,n,o)&&h.add(n);break}case"~":{if(f){let n=e.nextElementSibling;for(;n;)this._matchLeaves(a,n,o)&&h.add(n),n=n.nextElementSibling}break}case">":{let n=e.firstElementChild;for(;n;)this._matchLeaves(a,n,o)&&h.add(n),n=n.nextElementSibling;break}case" ":default:{let n=this._findDescendantNodes(a,e,o);if(n.size)return n}}else switch(r){case"+":{let n=e.previousElementSibling;n&&this._matchLeaves(a,n,o)&&h.add(n);break}case"~":{if(f){let n=f.firstElementChild;for(;n&&n!==e;)this._matchLeaves(a,n,o)&&h.add(n),n=n.nextElementSibling}break}case">":{f&&this._matchLeaves(a,f,o)&&h.add(f);break}case" ":default:{let n=[],i=f;for(;i;)this._matchLeaves(a,i,o)&&n.push(i),i=i.parentNode;if(n.length)return new Set(n.reverse())}}return h}_findQswalker(t,e,o={}){let{force:s,targetType:a}=o,r=this.#b,f=[],u=g(e,r,!!s);if(u)for((u.nodeType!==1||u===e&&u!==this.#n)&&(u=r.nextNode());u&&!(this._matchLeaves(t,u,{warn:this.#o})&&(f.push(u),a!==L));)u=r.nextNode();return f}_matchSelf(t){let e=[],o=!1;return this._matchLeaves(t,this.#e,{warn:this.#o})&&(e.push(this.#e),o=!0),[e,o]}_findLineal(t,e){let{complex:o}=e,s=[],a=!1,r=this._matchLeaves(t,this.#e,{warn:this.#o});if(r&&(s.push(this.#e),a=!0),!r||o){let f=this.#e.parentNode;for(;f&&(r=this._matchLeaves(t,f,{warn:this.#o}),r&&(s.push(f),a=!0),f.parentNode);)f=f.parentNode}return[s,a]}_findEntryNodes(t,e,o){let{leaves:s}=t,[a,...r]=s,f=r.length>0,{name:u,type:h}=a,n=[],i=!1,l=!1;switch(h){case O:{Ee(u,h,{warn:this.#o});break}case R:{if(e===D)[n,i]=this._matchSelf(s);else if(e===$)[n,i]=this._findLineal(s,{complex:o});else if(e===S&&this.#n.nodeType!==1){let p=this.#n.getElementById(u);p&&(f?this._matchLeaves(r,p,{warn:this.#o})&&(n.push(p),i=!0):(n.push(p),i=!0))}else n=this._findQswalker(s,this.#e,{targetType:e}),n.length&&(i=!0);break}case j:{e===D?[n,i]=this._matchSelf(s):e===$?[n,i]=this._findLineal(s,{complex:o}):(n=this._findQswalker(s,this.#e,{targetType:e}),n.length&&(i=!0));break}case F:{e===D?[n,i]=this._matchSelf(s):e===$?[n,i]=this._findLineal(s,{complex:o}):(n=this._findQswalker(s,this.#e,{targetType:e}),n.length&&(i=!0));break}default:if(e!==$&&(u==="host"||u==="host-context")){let p;if(this.#u&&this.#e.nodeType===11?p=this._matchShadowHostPseudoClass(a,this.#e):f&&this.#e.nodeType===1&&(p=this._matchShadowHostPseudoClass(a,this.#e.shadowRoot)),p){let m;if(f){for(let d of r)if(/^host(?:-context)?$/.test(d.name)?m=this._matchShadowHostPseudoClass(d,p)===p:d.name==="has"?m=this._matchPseudoClassSelector(d,p,{}).has(p):m=!1,!m)break}else m=!0;m&&(n.push(p),i=!0)}}else e===D?[n,i]=this._matchSelf(s):e===$?[n,i]=this._findLineal(s,{complex:o}):e===S?(n=this._findQswalker(s,this.#e,{targetType:e}),n.length&&(i=!0)):l=!0}return{compound:f,filtered:i,nodes:n,pending:l}}_collectNodes(t){let e=this.#r.values();if(t===L||t===S){let o=new Set,s=0;for(let{branch:a}of e){let r=a.length,f=r>1,u=a[0],h,n;if(f){let{combo:d,leaves:[{name:E,type:b}]}=u,x=a[r-1],{leaves:[{name:y,type:A}]}=x;if(h=W,n=u,this.#N.includes(":scope")||A===O||A===R)h=Y,n=x;else if(E==="*"&&b===F)h=Y,n=x;else if(y==="*"&&A===F)h=W,n=u;else if(r===2){let{name:se}=d;(se==="+"||se==="~")&&(h=Y,n=x)}}else h=Y,n=u;let{compound:i,filtered:l,nodes:p,pending:m}=this._findEntryNodes(n,t,f);p.length?(this.#r[s].find=!0,this.#p[s]=p):m&&o.add(new Map([["index",s],["twig",n]])),this.#r[s].dir=h,this.#r[s].filtered=l||!i,s++}if(o.size){let a,r;this.#e!==this.#n&&this.#e.nodeType===1?(a=this.#e,r=this.#b):(a=this.#n,r=this._createTreeWalker(a));let f=g(a,r);for(;f;){let u=!1;if(this.#e.nodeType===1?f===this.#e?u=!0:u=this.#e.contains(f):u=!0,u)for(let h of o){let{leaves:n}=h.get("twig");if(this._matchLeaves(n,f,{warn:this.#o})){let l=h.get("index");this.#r[l].filtered=!0,this.#r[l].find=!0,this.#p[l].push(f)}}f!==r.currentNode&&(f=g(f,r)),f=r.nextNode()}}}else{let o=0;for(let{branch:s}of e){let a=s[s.length-1],r=s.length>1,{compound:f,filtered:u,nodes:h}=this._findEntryNodes(a,t,r);h.length&&(this.#r[o].find=!0,this.#p[o]=h),this.#r[o].dir=Y,this.#r[o].filtered=u||!f,o++}}return[this.#r,this.#p]}_getCombinedNodes(t,e,o){let s=[];for(let a of e){let r=this._matchCombinator(t,a,{dir:o,warn:this.#o});r.size&&s.push(...r)}return s.length?new Set(s):new Set}_matchNodeNext(t,e,o){let{combo:s,index:a}=o,{combo:r,leaves:f}=t[a],u={combo:s,leaves:f},h=this._getCombinedNodes(u,e,W);if(h.size)if(a===t.length-1){let[n]=de(h);return n}else return this._matchNodeNext(t,h,{combo:r,index:a+1});return null}_matchNodePrev(t,e,o){let{index:s}=o,a=t[s],r=new Set([e]),f=this._getCombinedNodes(a,r,Y);if(f.size){if(s===0)return e;{let u;for(let h of f)if(u=this._matchNodePrev(t,h,{index:s-1}),u)break;if(u)return e}}return null}find(t){(t===L||t===S)&&this._prepareQuerySelectorWalker();let[[...e],o]=this._collectNodes(t),s=e.length,a,r=new Set;for(let f=0;f<s;f++){let{branch:u,dir:h,find:n}=e[f],i=u.length;if(i&&n){let l=o[f],p=l.length,m=i-1;if(m===0)if((t===L||t===S)&&this.#e.nodeType===1)for(let d=0;d<p;d++){let E=l[d];if(E!==this.#e&&this.#e.contains(E)&&(r.add(E),t===S))break}else if(t===L)if(r.size){let d=[...r];r=new Set([...d,...l]),a=!0}else r=new Set(l);else{let[d]=l;r.add(d)}else if(t===L)if(h===W){let{combo:d}=u[0],E=d;for(let b of l){let x=new Set([b]);for(let y=1;y<i;y++){let{combo:A,leaves:se}=u[y],ft={combo:E,leaves:se};if(x=this._getCombinedNodes(ft,x,h),x.size)if(y===m)if(r.size){let ht=[...r];r=new Set([...ht,...x]),a=!0,E=d}else r=x,E=d;else E=A;else break}}}else for(let d of l){let E=new Set([d]);for(let b=m-1;b>=0;b--){let x=u[b];if(E=this._getCombinedNodes(x,E,h),E.size)b===0&&(r.add(d),i>1&&r.size>1&&(a=!0));else break}}else if(t===S&&h===W){let{combo:d}=u[0],E;for(let b of l)if(E=this._matchNodeNext(u,new Set([b]),{combo:d,index:1}),E){r.add(E);break}if(!E){let{leaves:b}=u[0],[x]=l,[y]=this._findQswalker(b,x,{targetType:t});for(;y;){if(E=this._matchNodeNext(u,new Set([y]),{combo:d,index:1}),E){r.add(E);break}[y]=this._findQswalker(b,y,{targetType:t,force:!0})}}}else{let d;for(let E of l)if(d=this._matchNodePrev(u,E,{index:m-1}),d){r.add(E);break}if(!d&&t===S){let{leaves:E}=u[m],[b]=l,[x]=this._findQswalker(E,b,{targetType:t});for(;x;){if(d=this._matchNodePrev(u,x,{index:m-1}),d){r.add(x);break}[x]=this._findQswalker(E,x,{targetType:t,force:!0})}}}}}return t===S?(r.delete(this.#e),r.size>1&&(r=new Set(de(r)))):t===L&&(r.delete(this.#e),a&&r.size>1&&(r=new Set(de(r)))),r}};var Ie=new RegExp(`${q}${le}${q}`,"i"),lt=new RegExp(`${q}${Be}${q}`,"i"),ct=new RegExp(`^${ze}$`),Re=class{#r;#a;#i;#s;constructor(t,e){this.#r=t,this.#a=e??t.document,this.#i=new xe(t),this.#s=tt(t,e)}matches(t,e,o){if(e?.nodeType){if(e.nodeType!==1){let r=new this.#r.TypeError(`Unexpected node ${e.nodeName}`);this.#i.onError(r,o)}}else{let r=new this.#r.TypeError(`Unexpected type ${T(e)}`);this.#i.onError(r,o)}let s=e.ownerDocument;if(s===this.#a&&s.contentType==="text/html"&&e.parentNode){let r={complex:Ie.test(t),compound:!1,descend:!1,simple:!1,target:D};if(te(t,r))try{return this.#s.match(t,e)}catch{}}let a;try{this.#i.setup(t,e,o),a=this.#i.find(D).size}catch(r){this.#i.onError(r,o)}return!!a}closest(t,e,o){if(e?.nodeType){if(e.nodeType!==1){let r=new this.#r.TypeError(`Unexpected node ${e.nodeName}`);this.#i.onError(r,o)}}else{let r=new this.#r.TypeError(`Unexpected type ${T(e)}`);this.#i.onError(r,o)}let s=e.ownerDocument;if(s===this.#a&&s.contentType==="text/html"&&e.parentNode){let r={complex:Ie.test(t),compound:!1,descend:!1,simple:!1,target:$};if(te(t,r))try{return this.#s.closest(t,e)}catch{}}let a;try{this.#i.setup(t,e,o);let r=this.#i.find($);if(r.size){let f=e;for(;f;){if(r.has(f)){a=f;break}f=f.parentNode}}}catch(r){this.#i.onError(r,o)}return a??null}querySelector(t,e,o){if(!e?.nodeType){let r=new this.#r.TypeError(`Unexpected type ${T(e)}`);this.#i.onError(r,o)}let s;if(e.nodeType===9?s=e:s=e.ownerDocument,s===this.#a&&s.contentType==="text/html"){let r={complex:!1,compound:!(ct.test(t)||Ie.test(t)),descend:lt.test(t),simple:ct.test(t),target:S};if(te(t,r))try{return this.#s.first(t,e)}catch{}}let a;try{this.#i.setup(t,e,o);let r=this.#i.find(S);r.size&&([a]=r)}catch(r){this.#i.onError(r,o)}return a??null}querySelectorAll(t,e,o){if(!e?.nodeType){let r=new this.#r.TypeError(`Unexpected type ${T(e)}`);this.#i.onError(r,o)}let s;if(e.nodeType===9?s=e:s=e.ownerDocument,s===this.#a&&s.contentType==="text/html"){let r={complex:!1,compound:!1,descend:lt.test(t),simple:!1,target:L};if(te(t,r))try{return this.#s.select(t,e)}catch{}}let a;try{this.#i.setup(t,e,o);let r=this.#i.find(L);r.size&&(a=[...r])}catch(r){this.#i.onError(r,o)}return a??[]}};0&&(module.exports={DOMSelector});
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/index.js
30
+ var index_exports = {};
31
+ __export(index_exports, {
32
+ DOMSelector: () => DOMSelector
33
+ });
34
+ module.exports = __toCommonJS(index_exports);
35
+
36
+ // src/js/parser.js
37
+ var import_css_tree2 = require("css-tree");
38
+
39
+ // src/js/utility.js
40
+ var import_nwsapi = __toESM(require("@asamuzakjp/nwsapi"), 1);
41
+ var import_bidi_js = __toESM(require("bidi-js"), 1);
42
+ var import_css_tree = require("css-tree");
43
+ var import_is_potential_custom_element_name = __toESM(require("is-potential-custom-element-name"), 1);
44
+
45
+ // src/js/constant.js
46
+ var ATTR_SELECTOR = "AttributeSelector";
47
+ var CLASS_SELECTOR = "ClassSelector";
48
+ var COMBINATOR = "Combinator";
49
+ var IDENT = "Identifier";
50
+ var ID_SELECTOR = "IdSelector";
51
+ var NOT_SUPPORTED_ERR = "NotSupportedError";
52
+ var NTH = "Nth";
53
+ var PS_CLASS_SELECTOR = "PseudoClassSelector";
54
+ var PS_ELEMENT_SELECTOR = "PseudoElementSelector";
55
+ var SELECTOR = "Selector";
56
+ var STRING = "String";
57
+ var SYNTAX_ERR = "SyntaxError";
58
+ var TARGET_ALL = "all";
59
+ var TARGET_FIRST = "first";
60
+ var TARGET_LINEAL = "lineal";
61
+ var TARGET_SELF = "self";
62
+ var TYPE_SELECTOR = "TypeSelector";
63
+ var BIT_01 = 1;
64
+ var BIT_02 = 2;
65
+ var BIT_04 = 4;
66
+ var BIT_08 = 8;
67
+ var BIT_16 = 16;
68
+ var BIT_32 = 32;
69
+ var BIT_FFFF = 65535;
70
+ var DUO = 2;
71
+ var HEX = 16;
72
+ var HYPHEN = 45;
73
+ var TYPE_FROM = 8;
74
+ var TYPE_TO = -1;
75
+ var ELEMENT_NODE = 1;
76
+ var TEXT_NODE = 3;
77
+ var DOCUMENT_NODE = 9;
78
+ var DOCUMENT_FRAGMENT_NODE = 11;
79
+ var DOCUMENT_POSITION_PRECEDING = 2;
80
+ var DOCUMENT_POSITION_CONTAINS = 8;
81
+ var SHOW_ALL = 4294967295;
82
+ var WALKER_FILTER = 1281;
83
+ var ALPHA_NUM = "[A-Z\\d]+";
84
+ var CHILD_IDX = "(?:first|last|only)-(?:child|of-type)";
85
+ var DIGIT = "(?:0|[1-9]\\d*)";
86
+ var LANG_PART = `(?:-${ALPHA_NUM})*`;
87
+ var PSEUDO_CLASS = `(?:any-)?link|${CHILD_IDX}|checked|empty|indeterminate|read-(?:only|write)|root|target`;
88
+ var ANB = `[+-]?(?:${DIGIT}n?|n)|(?:[+-]?${DIGIT})?n\\s*[+-]\\s*${DIGIT}`;
89
+ var N_TH = `nth-(?:last-)?(?:child|of-type)\\(\\s*(?:even|odd|${ANB})\\s*\\)`;
90
+ var SUB_TYPE = "\\[[^|\\]]+\\]|[#.:][\\w-]+";
91
+ var SUB_TYPE_WO_PSEUDO = "\\[[^|\\]]+\\]|[#.][\\w-]+";
92
+ var TAG_ID_CLASS = "(?:[A-Za-z][\\w-]*|[#.][\\w-]+)";
93
+ var TAG_TYPE = "\\*|[A-Za-z][\\w-]*";
94
+ var TAG_TYPE_I = "\\*|[A-Z][\\w-]*";
95
+ var COMPOUND = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE})+)`;
96
+ var COMPOUND_WO_PSEUDO = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE_WO_PSEUDO})+)`;
97
+ var COMBO = "\\s?[\\s>~+]\\s?";
98
+ var COMPLEX = `${COMPOUND}(?:${COMBO}${COMPOUND})*`;
99
+ var DESCEND = "\\s?[\\s>]\\s?";
100
+ var NESTED_LOGIC_A = `:is\\(\\s*${COMPOUND}(?:\\s*,\\s*${COMPOUND})*\\s*\\)`;
101
+ var NESTED_LOGIC_B = `:is\\(\\s*${COMPLEX}(?:\\s*,\\s*${COMPLEX})*\\s*\\)`;
102
+ var COMPOUND_A = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${NESTED_LOGIC_A})+)`;
103
+ var COMPOUND_B = `(?:${TAG_TYPE}|(?:${TAG_TYPE})?(?:${SUB_TYPE}|${NESTED_LOGIC_B})+)`;
104
+ var COMPOUND_I = `(?:${TAG_TYPE_I}|(?:${TAG_TYPE_I})?(?:${SUB_TYPE})+)`;
105
+ var COMPLEX_L = `${COMPOUND_B}(?:${COMBO}${COMPOUND_B})*`;
106
+ var LOGIC_COMPLEX = `(?:is|not)\\(\\s*${COMPLEX_L}(?:\\s*,\\s*${COMPLEX_L})*\\s*\\)`;
107
+ var LOGIC_COMPOUND = `(?:is|not)\\(\\s*${COMPOUND_A}(?:\\s*,\\s*${COMPOUND_A})*\\s*\\)`;
108
+ var HAS_COMPOUND = `has\\([\\s>]?\\s*${COMPOUND_WO_PSEUDO}\\s*\\)`;
109
+ var KEY_FORM_FOCUS = Object.freeze(["button", "input", "select", "textarea"]);
110
+ var KEY_INPUT_BUTTON = Object.freeze(["button", "reset", "submit"]);
111
+ var KEY_INPUT_DATE = Object.freeze(["date", "datetime-local", "month", "time", "week"]);
112
+ var KEY_INPUT_TEXT = Object.freeze(["email", "password", "search", "tel", "text", "url"]);
113
+ var KEY_INPUT_EDIT = Object.freeze([...KEY_INPUT_DATE, ...KEY_INPUT_TEXT, "number"]);
114
+ var KEY_INPUT_LTR = Object.freeze([
115
+ "checkbox",
116
+ "color",
117
+ "date",
118
+ "image",
119
+ "number",
120
+ "range",
121
+ "radio",
122
+ "time"
123
+ ]);
124
+ var KEY_LOGICAL = Object.freeze(["has", "is", "not", "where"]);
125
+ var KEY_MODIFIER = Object.freeze([
126
+ "Alt",
127
+ "AltGraph",
128
+ "CapsLock",
129
+ "Control",
130
+ "Fn",
131
+ "FnLock",
132
+ "Hyper",
133
+ "Meta",
134
+ "NumLock",
135
+ "ScrollLock",
136
+ "Shift",
137
+ "Super",
138
+ "Symbol",
139
+ "SymbolLock"
140
+ ]);
141
+ var KEY_PS_STATE = Object.freeze([
142
+ "enabled",
143
+ "disabled",
144
+ "valid",
145
+ "invalid",
146
+ "in-range",
147
+ "out-of-range",
148
+ "checked",
149
+ "indeterminate",
150
+ "read-only",
151
+ "read-write",
152
+ "open",
153
+ "closed",
154
+ "placeholder-shown"
155
+ ]);
156
+ var KEY_SHADOW_HOST = Object.freeze(["host", "host-context"]);
157
+
158
+ // src/js/utility.js
159
+ var REG_LOGIC_COMPLEX = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPLEX})`);
160
+ var REG_LOGIC_COMPOUND = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND})`);
161
+ var REG_LOGIC_HAS_COMPOUND = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH}|${LOGIC_COMPOUND}|${HAS_COMPOUND})`);
162
+ var REG_END_WITH_HAS = new RegExp(`:${HAS_COMPOUND}$`);
163
+ var REG_WO_LOGICAL = new RegExp(`:(?!${PSEUDO_CLASS}|${N_TH})`);
164
+ var getType = (o) => Object.prototype.toString.call(o).slice(TYPE_FROM, TYPE_TO);
165
+ var resolveContent = (node) => {
166
+ if (!node?.nodeType) {
167
+ throw new TypeError(`Unexpected type ${getType(node)}`);
168
+ }
169
+ let document;
170
+ let root;
171
+ let shadow;
172
+ switch (node.nodeType) {
173
+ case DOCUMENT_NODE: {
174
+ document = node;
175
+ root = node;
176
+ break;
177
+ }
178
+ case DOCUMENT_FRAGMENT_NODE: {
179
+ const { host, mode, ownerDocument } = node;
180
+ document = ownerDocument;
181
+ root = node;
182
+ shadow = host && (mode === "close" || mode === "open");
183
+ break;
184
+ }
185
+ case ELEMENT_NODE: {
186
+ document = node.ownerDocument;
187
+ let refNode = node;
188
+ while (refNode) {
189
+ const { host, mode, nodeType, parentNode } = refNode;
190
+ if (nodeType === DOCUMENT_FRAGMENT_NODE) {
191
+ shadow = host && (mode === "close" || mode === "open");
192
+ break;
193
+ } else if (parentNode) {
194
+ refNode = parentNode;
195
+ } else {
196
+ break;
197
+ }
198
+ }
199
+ root = refNode;
200
+ break;
201
+ }
202
+ default: {
203
+ throw new TypeError(`Unexpected node ${node.nodeName}`);
204
+ }
205
+ }
206
+ return [
207
+ document,
208
+ root,
209
+ !!shadow
210
+ ];
211
+ };
212
+ var traverseNode = (node, walker, force = false) => {
213
+ if (!node?.nodeType) {
214
+ throw new TypeError(`Unexpected type ${getType(node)}`);
215
+ }
216
+ if (!walker) {
217
+ return null;
218
+ }
219
+ let refNode = walker.currentNode;
220
+ if (refNode === node) {
221
+ return refNode;
222
+ } else if (force || refNode.contains(node)) {
223
+ refNode = walker.nextNode();
224
+ while (refNode) {
225
+ if (refNode === node) {
226
+ break;
227
+ }
228
+ refNode = walker.nextNode();
229
+ }
230
+ return refNode;
231
+ } else {
232
+ if (refNode !== walker.root) {
233
+ let bool;
234
+ while (refNode) {
235
+ if (refNode === node) {
236
+ bool = true;
237
+ break;
238
+ } else if (refNode === walker.root || refNode.contains(node)) {
239
+ break;
240
+ }
241
+ refNode = walker.parentNode();
242
+ }
243
+ if (bool) {
244
+ return refNode;
245
+ }
246
+ }
247
+ if (node.nodeType === ELEMENT_NODE) {
248
+ let bool;
249
+ while (refNode) {
250
+ if (refNode === node) {
251
+ bool = true;
252
+ break;
253
+ }
254
+ refNode = walker.nextNode();
255
+ }
256
+ if (bool) {
257
+ return refNode;
258
+ }
259
+ }
260
+ }
261
+ return null;
262
+ };
263
+ var isCustomElement = (node, opt = {}) => {
264
+ if (!node?.nodeType) {
265
+ throw new TypeError(`Unexpected type ${getType(node)}`);
266
+ }
267
+ if (node.nodeType !== ELEMENT_NODE) {
268
+ return false;
269
+ }
270
+ const { localName, ownerDocument } = node;
271
+ const { formAssociated } = opt;
272
+ const window = ownerDocument.defaultView;
273
+ let elmConstructor;
274
+ const attr = node.getAttribute("is");
275
+ if (attr) {
276
+ elmConstructor = (0, import_is_potential_custom_element_name.default)(attr) && window.customElements.get(attr);
277
+ } else {
278
+ elmConstructor = (0, import_is_potential_custom_element_name.default)(localName) && window.customElements.get(localName);
279
+ }
280
+ if (elmConstructor) {
281
+ if (formAssociated) {
282
+ return !!elmConstructor.formAssociated;
283
+ }
284
+ return true;
285
+ }
286
+ return false;
287
+ };
288
+ var getSlottedTextContent = (node) => {
289
+ if (!node?.nodeType) {
290
+ throw new TypeError(`Unexpected type ${getType(node)}`);
291
+ }
292
+ if (typeof node.assignedNodes !== "function") {
293
+ return null;
294
+ }
295
+ const nodes = node.assignedNodes();
296
+ if (nodes.length) {
297
+ let text;
298
+ for (const item of nodes) {
299
+ text = item.textContent.trim();
300
+ if (text) {
301
+ break;
302
+ }
303
+ }
304
+ return text;
305
+ }
306
+ return node.textContent.trim();
307
+ };
308
+ var getDirectionality = (node) => {
309
+ if (!node?.nodeType) {
310
+ throw new TypeError(`Unexpected type ${getType(node)}`);
311
+ }
312
+ if (node.nodeType !== ELEMENT_NODE) {
313
+ return null;
314
+ }
315
+ const { dir: dirAttr, localName, parentNode } = node;
316
+ const { getEmbeddingLevels } = (0, import_bidi_js.default)();
317
+ if (dirAttr === "ltr" || dirAttr === "rtl") {
318
+ return dirAttr;
319
+ } else if (dirAttr === "auto") {
320
+ let text;
321
+ switch (localName) {
322
+ case "input": {
323
+ const valueKeys = [...KEY_INPUT_BUTTON, ...KEY_INPUT_TEXT, "hidden"];
324
+ if (!node.type || valueKeys.includes(node.type)) {
325
+ text = node.value;
326
+ } else {
327
+ const ltrKeys = [
328
+ "checkbox",
329
+ "color",
330
+ "date",
331
+ "image",
332
+ "number",
333
+ "range",
334
+ "radio",
335
+ "time"
336
+ ];
337
+ if (ltrKeys.includes(node.type)) {
338
+ return "ltr";
339
+ }
340
+ }
341
+ break;
342
+ }
343
+ case "slot": {
344
+ text = getSlottedTextContent(node);
345
+ break;
346
+ }
347
+ case "textarea": {
348
+ text = node.value;
349
+ break;
350
+ }
351
+ default: {
352
+ const items = [].slice.call(node.childNodes);
353
+ for (const item of items) {
354
+ const {
355
+ dir: itemDir,
356
+ localName: itemLocalName,
357
+ nodeType: itemNodeType,
358
+ textContent: itemTextContent
359
+ } = item;
360
+ if (itemNodeType === TEXT_NODE) {
361
+ text = itemTextContent.trim();
362
+ } else if (itemNodeType === ELEMENT_NODE) {
363
+ const keys = ["bdi", "script", "style", "textarea"];
364
+ if (!keys.includes(itemLocalName) && (!itemDir || itemDir !== "ltr" && itemDir !== "rtl")) {
365
+ if (itemLocalName === "slot") {
366
+ text = getSlottedTextContent(item);
367
+ } else {
368
+ text = itemTextContent.trim();
369
+ }
370
+ }
371
+ }
372
+ if (text) {
373
+ break;
374
+ }
375
+ }
376
+ }
377
+ }
378
+ if (text) {
379
+ const { paragraphs: [{ level }] } = getEmbeddingLevels(text);
380
+ if (level % 2 === 1) {
381
+ return "rtl";
382
+ }
383
+ } else if (parentNode) {
384
+ const { nodeType: parentNodeType } = parentNode;
385
+ if (parentNodeType === ELEMENT_NODE) {
386
+ return getDirectionality(parentNode);
387
+ }
388
+ }
389
+ } else if (localName === "input" && node.type === "tel") {
390
+ return "ltr";
391
+ } else if (localName === "bdi") {
392
+ const text = node.textContent.trim();
393
+ if (text) {
394
+ const { paragraphs: [{ level }] } = getEmbeddingLevels(text);
395
+ if (level % 2 === 1) {
396
+ return "rtl";
397
+ }
398
+ }
399
+ } else if (parentNode) {
400
+ if (localName === "slot") {
401
+ const text = getSlottedTextContent(node);
402
+ if (text) {
403
+ const { paragraphs: [{ level }] } = getEmbeddingLevels(text);
404
+ if (level % 2 === 1) {
405
+ return "rtl";
406
+ }
407
+ return "ltr";
408
+ }
409
+ }
410
+ const { nodeType: parentNodeType } = parentNode;
411
+ if (parentNodeType === ELEMENT_NODE) {
412
+ return getDirectionality(parentNode);
413
+ }
414
+ }
415
+ return "ltr";
416
+ };
417
+ var isContentEditable = (node) => {
418
+ if (!node?.nodeType) {
419
+ throw new TypeError(`Unexpected type ${getType(node)}`);
420
+ }
421
+ if (node.nodeType !== ELEMENT_NODE) {
422
+ return false;
423
+ }
424
+ if (typeof node.isContentEditable === "boolean") {
425
+ return node.isContentEditable;
426
+ } else if (node.ownerDocument.designMode === "on") {
427
+ return true;
428
+ } else {
429
+ let attr;
430
+ if (node.hasAttribute("contenteditable")) {
431
+ attr = node.getAttribute("contenteditable");
432
+ } else {
433
+ attr = "inherit";
434
+ }
435
+ switch (attr) {
436
+ case "":
437
+ case "true": {
438
+ return true;
439
+ }
440
+ case "plaintext-only": {
441
+ return true;
442
+ }
443
+ case "false": {
444
+ return false;
445
+ }
446
+ default: {
447
+ if (node?.parentNode?.nodeType === ELEMENT_NODE) {
448
+ return isContentEditable(node.parentNode);
449
+ }
450
+ return false;
451
+ }
452
+ }
453
+ }
454
+ };
455
+ var isVisible = (node) => {
456
+ if (node?.nodeType !== ELEMENT_NODE) {
457
+ return false;
458
+ }
459
+ const window = node.ownerDocument.defaultView;
460
+ const { display, visibility } = window.getComputedStyle(node);
461
+ if (display !== "none" && visibility === "visible") {
462
+ return true;
463
+ }
464
+ return false;
465
+ };
466
+ var isFocusVisible = (node) => {
467
+ if (node?.nodeType !== ELEMENT_NODE) {
468
+ return false;
469
+ }
470
+ const { localName, type } = node;
471
+ switch (localName) {
472
+ case "input": {
473
+ if (!type || KEY_INPUT_EDIT.includes(type)) {
474
+ return true;
475
+ }
476
+ return false;
477
+ }
478
+ case "textarea": {
479
+ return true;
480
+ }
481
+ default: {
482
+ return isContentEditable(node);
483
+ }
484
+ }
485
+ };
486
+ var isFocusableArea = (node) => {
487
+ if (node?.nodeType !== ELEMENT_NODE) {
488
+ return false;
489
+ }
490
+ if (!node.isConnected) {
491
+ return false;
492
+ }
493
+ const window = node.ownerDocument.defaultView;
494
+ if (node instanceof window.HTMLElement) {
495
+ if (Number.isInteger(parseInt(node.getAttribute("tabindex")))) {
496
+ return true;
497
+ }
498
+ if (isContentEditable(node)) {
499
+ return true;
500
+ }
501
+ const { localName, parentNode } = node;
502
+ switch (localName) {
503
+ case "a": {
504
+ if (node.href || node.hasAttribute("href")) {
505
+ return true;
506
+ }
507
+ return false;
508
+ }
509
+ case "iframe": {
510
+ return true;
511
+ }
512
+ case "input": {
513
+ if (node.disabled || node.hasAttribute("disabled") || node.hidden || node.hasAttribute("hidden")) {
514
+ return false;
515
+ }
516
+ return true;
517
+ }
518
+ case "summary": {
519
+ if (parentNode.localName === "details") {
520
+ let child = parentNode.firstElementChild;
521
+ let bool = false;
522
+ while (child) {
523
+ if (child.localName === "summary") {
524
+ bool = child === node;
525
+ break;
526
+ }
527
+ child = child.nextElementSibling;
528
+ }
529
+ return bool;
530
+ }
531
+ return false;
532
+ }
533
+ default: {
534
+ const keys = ["button", "select", "textarea"];
535
+ if (keys.includes(localName) && !(node.disabled || node.hasAttribute("disabled"))) {
536
+ return true;
537
+ }
538
+ }
539
+ }
540
+ } else if (node instanceof window.SVGElement) {
541
+ if (Number.isInteger(parseInt(node.getAttributeNS(null, "tabindex")))) {
542
+ const keys = [
543
+ "clipPath",
544
+ "defs",
545
+ "desc",
546
+ "linearGradient",
547
+ "marker",
548
+ "mask",
549
+ "metadata",
550
+ "pattern",
551
+ "radialGradient",
552
+ "script",
553
+ "style",
554
+ "symbol",
555
+ "title"
556
+ ];
557
+ const ns = "http://www.w3.org/2000/svg";
558
+ let bool;
559
+ let refNode = node;
560
+ while (refNode.namespaceURI === ns) {
561
+ bool = keys.includes(refNode.localName);
562
+ if (bool) {
563
+ break;
564
+ }
565
+ if (refNode?.parentNode?.namespaceURI === ns) {
566
+ refNode = refNode.parentNode;
567
+ } else {
568
+ break;
569
+ }
570
+ }
571
+ if (bool) {
572
+ return false;
573
+ }
574
+ return true;
575
+ }
576
+ if (node.localName === "a" && (node.href || node.hasAttributeNS(null, "href"))) {
577
+ return true;
578
+ }
579
+ }
580
+ return false;
581
+ };
582
+ var getNamespaceURI = (ns, node) => {
583
+ if (typeof ns !== "string") {
584
+ throw new TypeError(`Unexpected type ${getType(ns)}`);
585
+ } else if (!node?.nodeType) {
586
+ throw new TypeError(`Unexpected type ${getType(node)}`);
587
+ }
588
+ if (!ns || node.nodeType !== ELEMENT_NODE) {
589
+ return null;
590
+ }
591
+ const { attributes } = node;
592
+ let res;
593
+ for (const attr of attributes) {
594
+ const { name, namespaceURI, prefix, value } = attr;
595
+ if (name === `xmlns:${ns}`) {
596
+ res = value;
597
+ } else if (prefix === ns) {
598
+ res = namespaceURI;
599
+ }
600
+ if (res) {
601
+ break;
602
+ }
603
+ }
604
+ return res ?? null;
605
+ };
606
+ var isNamespaceDeclared = (ns = "", node = {}) => {
607
+ if (!ns || typeof ns !== "string" || node?.nodeType !== ELEMENT_NODE) {
608
+ return false;
609
+ }
610
+ if (node.lookupNamespaceURI(ns)) {
611
+ return true;
612
+ }
613
+ const root = node.ownerDocument.documentElement;
614
+ let parent = node;
615
+ let res;
616
+ while (parent) {
617
+ res = getNamespaceURI(ns, parent);
618
+ if (res || parent === root) {
619
+ break;
620
+ }
621
+ parent = parent.parentNode;
622
+ }
623
+ return !!res;
624
+ };
625
+ var isPreceding = (nodeA, nodeB) => {
626
+ if (!nodeA?.nodeType) {
627
+ throw new TypeError(`Unexpected type ${getType(nodeA)}`);
628
+ } else if (!nodeB?.nodeType) {
629
+ throw new TypeError(`Unexpected type ${getType(nodeB)}`);
630
+ }
631
+ if (nodeA.nodeType !== ELEMENT_NODE || nodeB.nodeType !== ELEMENT_NODE) {
632
+ return false;
633
+ }
634
+ const posBit = nodeB.compareDocumentPosition(nodeA);
635
+ const res = posBit & DOCUMENT_POSITION_PRECEDING || posBit & DOCUMENT_POSITION_CONTAINS;
636
+ return !!res;
637
+ };
638
+ var sortNodes = (nodes = []) => {
639
+ const arr = [...nodes];
640
+ if (arr.length > 1) {
641
+ arr.sort((a, b) => {
642
+ let res;
643
+ if (isPreceding(b, a)) {
644
+ res = 1;
645
+ } else {
646
+ res = -1;
647
+ }
648
+ return res;
649
+ });
650
+ }
651
+ return arr;
652
+ };
653
+ var initNwsapi = (window, document) => {
654
+ if (!window?.DOMException) {
655
+ throw new TypeError(`Unexpected global object ${getType(window)}`);
656
+ }
657
+ if (document?.nodeType !== DOCUMENT_NODE) {
658
+ document = window.document;
659
+ }
660
+ const nw = (0, import_nwsapi.default)({
661
+ document,
662
+ DOMException: window.DOMException
663
+ });
664
+ nw.configure({
665
+ LOGERRORS: false
666
+ });
667
+ return nw;
668
+ };
669
+ var filterSelector = (selector, opt = {}) => {
670
+ if (!selector || typeof selector !== "string") {
671
+ return false;
672
+ }
673
+ const { complex, compound, descend, simple, target } = opt;
674
+ if (simple || compound) {
675
+ return false;
676
+ }
677
+ if (selector.includes("[")) {
678
+ const index = selector.lastIndexOf("[");
679
+ const sel = selector.substring(index);
680
+ if (sel.indexOf("]") < 0) {
681
+ return false;
682
+ }
683
+ }
684
+ if (/[|\\]|::|[^\u0021-\u007F\s]|\[\s*[\w$*=^|~-]+(?:(?:"[\w$*=^|~\s'-]+"|'[\w$*=^|~\s"-]+')?(?:\s+[\w$*=^|~-]+)+|"[^"\]]{1,255}|'[^'\]]{1,255})\s*\]|:(?:is|where)\(\s*\)/.test(selector)) {
685
+ return false;
686
+ }
687
+ if (selector.includes(":")) {
688
+ if (descend) {
689
+ return false;
690
+ } else if ((target === TARGET_SELF || target === TARGET_LINEAL) && /:has\(/.test(selector)) {
691
+ if (!complex || REG_LOGIC_HAS_COMPOUND.test(selector)) {
692
+ return false;
693
+ }
694
+ return REG_END_WITH_HAS.test(selector);
695
+ } else if (/:(?:is|not)\(/.test(selector)) {
696
+ if (complex) {
697
+ return !REG_LOGIC_COMPLEX.test(selector);
698
+ } else {
699
+ return !REG_LOGIC_COMPOUND.test(selector);
700
+ }
701
+ } else {
702
+ return !REG_WO_LOGICAL.test(selector);
703
+ }
704
+ }
705
+ return true;
706
+ };
707
+
708
+ // src/js/parser.js
709
+ var import_css_tree3 = require("css-tree");
710
+ var REG_EMPTY_PS_FUNC = /(?<=:(?:dir|has|host(?:-context)?|is|lang|not|nth-(?:last-)?(?:child|of-type)|where))\(\s+\)/g;
711
+ var REG_SHADOW_PS_ELEMENT = /^part|slotted$/;
712
+ var U_FFFD = "\uFFFD";
713
+ var unescapeSelector = (selector = "") => {
714
+ if (typeof selector === "string" && selector.indexOf("\\", 0) >= 0) {
715
+ const arr = selector.split("\\");
716
+ const l = arr.length;
717
+ for (let i = 1; i < l; i++) {
718
+ let item = arr[i];
719
+ if (item === "" && i === l - 1) {
720
+ item = U_FFFD;
721
+ } else {
722
+ const hexExists = /^([\da-f]{1,6}\s?)/i.exec(item);
723
+ if (hexExists) {
724
+ const [, hex] = hexExists;
725
+ let str;
726
+ try {
727
+ const low = parseInt("D800", HEX);
728
+ const high = parseInt("DFFF", HEX);
729
+ const deci = parseInt(hex, HEX);
730
+ if (deci === 0 || deci >= low && deci <= high) {
731
+ str = U_FFFD;
732
+ } else {
733
+ str = String.fromCodePoint(deci);
734
+ }
735
+ } catch (e) {
736
+ str = U_FFFD;
737
+ }
738
+ let postStr = "";
739
+ if (item.length > hex.length) {
740
+ postStr = item.substring(hex.length);
741
+ }
742
+ item = `${str}${postStr}`;
743
+ } else if (/^[\n\r\f]/.test(item)) {
744
+ item = "\\" + item;
745
+ }
746
+ }
747
+ arr[i] = item;
748
+ }
749
+ selector = arr.join("");
750
+ }
751
+ return selector;
752
+ };
753
+ var preprocess = (...args) => {
754
+ if (!args.length) {
755
+ throw new TypeError("1 argument required, but only 0 present.");
756
+ }
757
+ let [selector] = args;
758
+ if (typeof selector === "string") {
759
+ let index = 0;
760
+ while (index >= 0) {
761
+ index = selector.indexOf("#", index);
762
+ if (index < 0) {
763
+ break;
764
+ }
765
+ const preHash = selector.substring(0, index + 1);
766
+ let postHash = selector.substring(index + 1);
767
+ if (/^\d$/.test(postHash.substring(0, 1))) {
768
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
769
+ }
770
+ const codePoint = postHash.codePointAt(0);
771
+ if (codePoint === HYPHEN) {
772
+ if (/^\d$/.test(postHash.substring(1, 2))) {
773
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
774
+ }
775
+ } else if (codePoint > BIT_FFFF) {
776
+ const str = `\\${codePoint.toString(HEX)} `;
777
+ if (postHash.length === DUO) {
778
+ postHash = str;
779
+ } else {
780
+ postHash = `${str}${postHash.substring(DUO)}`;
781
+ }
782
+ }
783
+ selector = `${preHash}${postHash}`;
784
+ index++;
785
+ }
786
+ selector = selector.replace(/\f|\r\n?/g, "\n").replace(/[\0\uD800-\uDFFF]|\\$/g, U_FFFD);
787
+ } else if (selector === void 0 || selector === null) {
788
+ selector = getType(selector).toLowerCase();
789
+ } else if (Array.isArray(selector)) {
790
+ selector = selector.join(",");
791
+ } else if (Object.prototype.hasOwnProperty.call(selector, "toString")) {
792
+ selector = selector.toString();
793
+ } else {
794
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
795
+ }
796
+ return selector.replace(/\x26/g, ":scope");
797
+ };
798
+ var parseSelector = (selector) => {
799
+ selector = preprocess(selector);
800
+ if (/^$|^\s*>|,\s*$/.test(selector)) {
801
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
802
+ }
803
+ let res;
804
+ try {
805
+ const ast = (0, import_css_tree2.parse)(selector, {
806
+ context: "selectorList",
807
+ parseCustomProperty: true
808
+ });
809
+ res = (0, import_css_tree2.toPlainObject)(ast);
810
+ } catch (e) {
811
+ const { message } = e;
812
+ if (/^(?:"\]"|Attribute selector [()\s,=~^$*|]+) is expected$/.test(message) && !selector.endsWith("]")) {
813
+ const index = selector.lastIndexOf("[");
814
+ const sel = selector.substring(index);
815
+ if (sel.includes('"')) {
816
+ const quotes = sel.match(/"/g).length;
817
+ if (quotes % 2) {
818
+ res = parseSelector(`${selector}"]`);
819
+ } else {
820
+ res = parseSelector(`${selector}]`);
821
+ }
822
+ } else {
823
+ res = parseSelector(`${selector}]`);
824
+ }
825
+ } else if (message === '")" is expected') {
826
+ if (REG_EMPTY_PS_FUNC.test(selector)) {
827
+ res = parseSelector(`${selector.replaceAll(REG_EMPTY_PS_FUNC, "()")}`);
828
+ } else if (!selector.endsWith(")")) {
829
+ res = parseSelector(`${selector})`);
830
+ } else {
831
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
832
+ }
833
+ } else {
834
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
835
+ }
836
+ }
837
+ return res;
838
+ };
839
+ var walkAST = (ast = {}) => {
840
+ const branches = /* @__PURE__ */ new Set();
841
+ const info = /* @__PURE__ */ new Map();
842
+ const opt = {
843
+ enter: (node) => {
844
+ switch (node.type) {
845
+ case SELECTOR: {
846
+ branches.add(node.children);
847
+ break;
848
+ }
849
+ case PS_CLASS_SELECTOR: {
850
+ if (KEY_LOGICAL.includes(node.name)) {
851
+ info.set("hasNestedSelector", true);
852
+ info.set("hasLogicalPseudoFunc", true);
853
+ if (node.name === "has") {
854
+ info.set("hasHasPseudoFunc", true);
855
+ }
856
+ } else if (KEY_PS_STATE.includes(node.name)) {
857
+ info.set("hasStatePseudoClass", true);
858
+ } else if (KEY_SHADOW_HOST.includes(node.name) && Array.isArray(node.children) && node.children.length) {
859
+ info.set("hasNestedSelector", true);
860
+ }
861
+ break;
862
+ }
863
+ case PS_ELEMENT_SELECTOR: {
864
+ if (REG_SHADOW_PS_ELEMENT.test(node.name)) {
865
+ info.set("hasNestedSelector", true);
866
+ }
867
+ break;
868
+ }
869
+ case NTH: {
870
+ if (node.selector) {
871
+ info.set("hasNestedSelector", true);
872
+ info.set("hasNthChildOfSelector", true);
873
+ }
874
+ break;
875
+ }
876
+ default:
877
+ }
878
+ }
879
+ };
880
+ (0, import_css_tree2.walk)(ast, opt);
881
+ if (info.get("hasNestedSelector")) {
882
+ (0, import_css_tree2.findAll)(ast, (node, item, list) => {
883
+ if (list) {
884
+ if (node.type === PS_CLASS_SELECTOR && KEY_LOGICAL.includes(node.name)) {
885
+ const itemList = list.filter((i) => {
886
+ const { name, type } = i;
887
+ return type === PS_CLASS_SELECTOR && KEY_LOGICAL.includes(name);
888
+ });
889
+ for (const { children } of itemList) {
890
+ for (const { children: grandChildren } of children) {
891
+ for (const { children: greatGrandChildren } of grandChildren) {
892
+ if (branches.has(greatGrandChildren)) {
893
+ branches.delete(greatGrandChildren);
894
+ }
895
+ }
896
+ }
897
+ }
898
+ } else if (node.type === PS_CLASS_SELECTOR && KEY_SHADOW_HOST.includes(node.name) && Array.isArray(node.children) && node.children.length) {
899
+ const itemList = list.filter((i) => {
900
+ const { children, name, type } = i;
901
+ const res = type === PS_CLASS_SELECTOR && KEY_SHADOW_HOST.includes(name) && Array.isArray(children) && children.length;
902
+ return res;
903
+ });
904
+ for (const { children } of itemList) {
905
+ for (const { children: grandChildren } of children) {
906
+ if (branches.has(grandChildren)) {
907
+ branches.delete(grandChildren);
908
+ }
909
+ }
910
+ }
911
+ } else if (node.type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(node.name)) {
912
+ const itemList = list.filter((i) => {
913
+ const { name, type } = i;
914
+ const res = type === PS_ELEMENT_SELECTOR && REG_SHADOW_PS_ELEMENT.test(name);
915
+ return res;
916
+ });
917
+ for (const { children } of itemList) {
918
+ for (const { children: grandChildren } of children) {
919
+ if (branches.has(grandChildren)) {
920
+ branches.delete(grandChildren);
921
+ }
922
+ }
923
+ }
924
+ } else if (node.type === NTH && node.selector) {
925
+ const itemList = list.filter((i) => {
926
+ const { selector, type } = i;
927
+ const res = type === NTH && selector;
928
+ return res;
929
+ });
930
+ for (const { selector } of itemList) {
931
+ const { children } = selector;
932
+ for (const { children: grandChildren } of children) {
933
+ if (branches.has(grandChildren)) {
934
+ branches.delete(grandChildren);
935
+ }
936
+ }
937
+ }
938
+ }
939
+ }
940
+ });
941
+ }
942
+ return {
943
+ branches: [...branches],
944
+ info: Object.fromEntries(info)
945
+ };
946
+ };
947
+ var sortAST = (asts) => {
948
+ const arr = [...asts];
949
+ if (arr.length > 1) {
950
+ const order = /* @__PURE__ */ new Map([
951
+ [PS_ELEMENT_SELECTOR, BIT_01],
952
+ [ID_SELECTOR, BIT_02],
953
+ [CLASS_SELECTOR, BIT_04],
954
+ [TYPE_SELECTOR, BIT_08],
955
+ [ATTR_SELECTOR, BIT_16],
956
+ [PS_CLASS_SELECTOR, BIT_32]
957
+ ]);
958
+ arr.sort((a, b) => {
959
+ const { type: typeA } = a;
960
+ const { type: typeB } = b;
961
+ const bitA = order.get(typeA);
962
+ const bitB = order.get(typeB);
963
+ let res;
964
+ if (bitA === bitB) {
965
+ res = 0;
966
+ } else if (bitA > bitB) {
967
+ res = 1;
968
+ } else {
969
+ res = -1;
970
+ }
971
+ return res;
972
+ });
973
+ }
974
+ return arr;
975
+ };
976
+ var parseAstName = (selector) => {
977
+ let prefix;
978
+ let localName;
979
+ if (selector && typeof selector === "string") {
980
+ if (selector.indexOf("|") > -1) {
981
+ [prefix, localName] = selector.split("|");
982
+ } else {
983
+ prefix = "*";
984
+ localName = selector;
985
+ }
986
+ } else {
987
+ throw new DOMException(`Invalid selector ${selector}`, SYNTAX_ERR);
988
+ }
989
+ return {
990
+ prefix,
991
+ localName
992
+ };
993
+ };
994
+
995
+ // src/js/matcher.js
996
+ var matchPseudoElementSelector = (astName, astType, opt = {}) => {
997
+ const { forgive, warn } = opt;
998
+ if (astType === PS_ELEMENT_SELECTOR) {
999
+ switch (astName) {
1000
+ case "after":
1001
+ case "backdrop":
1002
+ case "before":
1003
+ case "cue":
1004
+ case "cue-region":
1005
+ case "first-letter":
1006
+ case "first-line":
1007
+ case "file-selector-button":
1008
+ case "marker":
1009
+ case "placeholder":
1010
+ case "selection":
1011
+ case "target-text": {
1012
+ if (warn) {
1013
+ throw new DOMException(
1014
+ `Unsupported pseudo-element ::${astName}`,
1015
+ NOT_SUPPORTED_ERR
1016
+ );
1017
+ }
1018
+ break;
1019
+ }
1020
+ case "part":
1021
+ case "slotted": {
1022
+ if (warn) {
1023
+ throw new DOMException(
1024
+ `Unsupported pseudo-element ::${astName}()`,
1025
+ NOT_SUPPORTED_ERR
1026
+ );
1027
+ }
1028
+ break;
1029
+ }
1030
+ default: {
1031
+ if (astName.startsWith("-webkit-")) {
1032
+ if (warn) {
1033
+ throw new DOMException(
1034
+ `Unsupported pseudo-element ::${astName}`,
1035
+ NOT_SUPPORTED_ERR
1036
+ );
1037
+ }
1038
+ } else if (!forgive) {
1039
+ throw new DOMException(
1040
+ `Unknown pseudo-element ::${astName}`,
1041
+ SYNTAX_ERR
1042
+ );
1043
+ }
1044
+ }
1045
+ }
1046
+ } else {
1047
+ throw new TypeError(`Unexpected ast type ${getType(astType)}`);
1048
+ }
1049
+ };
1050
+ var matchDirectionPseudoClass = (ast, node) => {
1051
+ const { name } = ast;
1052
+ if (!name) {
1053
+ let type;
1054
+ if (name === "") {
1055
+ type = "(empty String)";
1056
+ } else {
1057
+ type = getType(name);
1058
+ }
1059
+ throw new TypeError(`Unexpected ast type ${type}`);
1060
+ }
1061
+ const dir = getDirectionality(node);
1062
+ return name === dir;
1063
+ };
1064
+ var matchLanguagePseudoClass = (ast, node) => {
1065
+ const { name, type, value } = ast;
1066
+ let astName;
1067
+ if (type === STRING && value) {
1068
+ astName = value;
1069
+ } else if (type === IDENT && name) {
1070
+ astName = unescapeSelector(name);
1071
+ }
1072
+ const { contentType } = node.ownerDocument;
1073
+ const html = /^(?:application\/xhtml\+x|text\/ht)ml$/.test(contentType);
1074
+ const xml = /^(?:application\/(?:[\w\-.]+\+)?|image\/[\w\-.]+\+|text\/)xml$/.test(contentType);
1075
+ if (astName === "*") {
1076
+ if (html && node.hasAttribute("lang") || xml && node.hasAttribute("xml:lang")) {
1077
+ if (html && node.getAttribute("lang") || xml && node.getAttribute("xml:lang")) {
1078
+ return true;
1079
+ }
1080
+ } else {
1081
+ let parent = node.parentNode;
1082
+ let res;
1083
+ while (parent) {
1084
+ if (parent.nodeType === ELEMENT_NODE) {
1085
+ if (html && parent.hasAttribute("lang") || xml && parent.hasAttribute("xml:lang")) {
1086
+ if (html && parent.hasAttribute("lang") || xml && parent.hasAttribute("xml:lang")) {
1087
+ res = true;
1088
+ }
1089
+ break;
1090
+ }
1091
+ parent = parent.parentNode;
1092
+ } else {
1093
+ break;
1094
+ }
1095
+ }
1096
+ return !!res;
1097
+ }
1098
+ } else if (astName) {
1099
+ const reg = new RegExp(`^(?:\\*-)?${ALPHA_NUM}${LANG_PART}$`, "i");
1100
+ if (reg.test(astName)) {
1101
+ let regExtendedLang;
1102
+ if (astName.indexOf("-") > -1) {
1103
+ const [langMain, langSub, ...langRest] = astName.split("-");
1104
+ let extendedMain;
1105
+ if (langMain === "*") {
1106
+ extendedMain = `${ALPHA_NUM}${LANG_PART}`;
1107
+ } else {
1108
+ extendedMain = `${langMain}${LANG_PART}`;
1109
+ }
1110
+ const extendedSub = `-${langSub}${LANG_PART}`;
1111
+ const len = langRest.length;
1112
+ let extendedRest = "";
1113
+ if (len) {
1114
+ for (let i = 0; i < len; i++) {
1115
+ extendedRest += `-${langRest[i]}${LANG_PART}`;
1116
+ }
1117
+ }
1118
+ regExtendedLang = new RegExp(`^${extendedMain}${extendedSub}${extendedRest}$`, "i");
1119
+ } else {
1120
+ regExtendedLang = new RegExp(`^${astName}${LANG_PART}$`, "i");
1121
+ }
1122
+ if (html && node.hasAttribute("lang") || xml && node.hasAttribute("xml:lang")) {
1123
+ const attr = html && node.getAttribute("lang") || xml && node.getAttribute("xml:lang") || "";
1124
+ return regExtendedLang.test(attr);
1125
+ } else {
1126
+ let parent = node.parentNode;
1127
+ let res;
1128
+ while (parent) {
1129
+ if (parent.nodeType === ELEMENT_NODE) {
1130
+ if (html && parent.hasAttribute("lang") || xml && parent.hasAttribute("xml:lang")) {
1131
+ const attr = html && parent.getAttribute("lang") || xml && parent.getAttribute("xml:lang") || "";
1132
+ res = regExtendedLang.test(attr);
1133
+ break;
1134
+ }
1135
+ parent = parent.parentNode;
1136
+ } else {
1137
+ break;
1138
+ }
1139
+ }
1140
+ return !!res;
1141
+ }
1142
+ }
1143
+ }
1144
+ return false;
1145
+ };
1146
+ var matchAttributeSelector = (ast, node) => {
1147
+ const {
1148
+ flags: astFlags,
1149
+ matcher: astMatcher,
1150
+ name: astName,
1151
+ value: astValue
1152
+ } = ast;
1153
+ if (typeof astFlags === "string" && !/^[is]$/i.test(astFlags)) {
1154
+ const css = (0, import_css_tree3.generate)(ast);
1155
+ throw new DOMException(`Invalid selector ${css}`, SYNTAX_ERR);
1156
+ }
1157
+ const { attributes } = node;
1158
+ if (attributes?.length) {
1159
+ const contentType = node.ownerDocument.contentType;
1160
+ let caseInsensitive;
1161
+ if (contentType === "text/html") {
1162
+ if (typeof astFlags === "string" && /^s$/i.test(astFlags)) {
1163
+ caseInsensitive = false;
1164
+ } else {
1165
+ caseInsensitive = true;
1166
+ }
1167
+ } else if (typeof astFlags === "string" && /^i$/i.test(astFlags)) {
1168
+ caseInsensitive = true;
1169
+ } else {
1170
+ caseInsensitive = false;
1171
+ }
1172
+ let astAttrName = unescapeSelector(astName.name);
1173
+ if (caseInsensitive) {
1174
+ astAttrName = astAttrName.toLowerCase();
1175
+ }
1176
+ const attrValues = /* @__PURE__ */ new Set();
1177
+ if (astAttrName.indexOf("|") > -1) {
1178
+ const {
1179
+ prefix: astPrefix,
1180
+ localName: astLocalName
1181
+ } = parseAstName(astAttrName);
1182
+ for (const item of attributes) {
1183
+ let { name: itemName, value: itemValue } = item;
1184
+ if (caseInsensitive) {
1185
+ itemName = itemName.toLowerCase();
1186
+ itemValue = itemValue.toLowerCase();
1187
+ }
1188
+ switch (astPrefix) {
1189
+ case "": {
1190
+ if (astLocalName === itemName) {
1191
+ attrValues.add(itemValue);
1192
+ }
1193
+ break;
1194
+ }
1195
+ case "*": {
1196
+ if (itemName.indexOf(":") > -1) {
1197
+ if (itemName.endsWith(`:${astLocalName}`)) {
1198
+ attrValues.add(itemValue);
1199
+ }
1200
+ } else if (astLocalName === itemName) {
1201
+ attrValues.add(itemValue);
1202
+ }
1203
+ break;
1204
+ }
1205
+ default: {
1206
+ if (itemName.indexOf(":") > -1) {
1207
+ const [itemPrefix, itemLocalName] = itemName.split(":");
1208
+ if (itemPrefix === "xml" && itemLocalName === "lang") {
1209
+ continue;
1210
+ } else if (astPrefix === itemPrefix && astLocalName === itemLocalName) {
1211
+ const namespaceDeclared = isNamespaceDeclared(astPrefix, node);
1212
+ if (namespaceDeclared) {
1213
+ attrValues.add(itemValue);
1214
+ }
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ }
1220
+ } else {
1221
+ for (let { name: itemName, value: itemValue } of attributes) {
1222
+ if (caseInsensitive) {
1223
+ itemName = itemName.toLowerCase();
1224
+ itemValue = itemValue.toLowerCase();
1225
+ }
1226
+ if (itemName.indexOf(":") > -1) {
1227
+ const [itemPrefix, itemLocalName] = itemName.split(":");
1228
+ if (itemPrefix === "xml" && itemLocalName === "lang") {
1229
+ continue;
1230
+ } else if (astAttrName === itemLocalName) {
1231
+ attrValues.add(itemValue);
1232
+ }
1233
+ } else if (astAttrName === itemName) {
1234
+ attrValues.add(itemValue);
1235
+ }
1236
+ }
1237
+ }
1238
+ if (attrValues.size) {
1239
+ const { name: astIdentValue, value: astStringValue } = astValue ?? {};
1240
+ let attrValue;
1241
+ if (astIdentValue) {
1242
+ if (caseInsensitive) {
1243
+ attrValue = astIdentValue.toLowerCase();
1244
+ } else {
1245
+ attrValue = astIdentValue;
1246
+ }
1247
+ } else if (astStringValue) {
1248
+ if (caseInsensitive) {
1249
+ attrValue = astStringValue.toLowerCase();
1250
+ } else {
1251
+ attrValue = astStringValue;
1252
+ }
1253
+ } else if (astStringValue === "") {
1254
+ attrValue = astStringValue;
1255
+ }
1256
+ switch (astMatcher) {
1257
+ case "=": {
1258
+ return typeof attrValue === "string" && attrValues.has(attrValue);
1259
+ }
1260
+ case "~=": {
1261
+ if (attrValue && typeof attrValue === "string") {
1262
+ let res;
1263
+ for (const value of attrValues) {
1264
+ const item = new Set(value.split(/\s+/));
1265
+ if (item.has(attrValue)) {
1266
+ res = true;
1267
+ break;
1268
+ }
1269
+ }
1270
+ return !!res;
1271
+ }
1272
+ return false;
1273
+ }
1274
+ case "|=": {
1275
+ if (attrValue && typeof attrValue === "string") {
1276
+ let item;
1277
+ for (const value of attrValues) {
1278
+ if (value === attrValue || value.startsWith(`${attrValue}-`)) {
1279
+ item = value;
1280
+ break;
1281
+ }
1282
+ }
1283
+ if (item) {
1284
+ return true;
1285
+ }
1286
+ return false;
1287
+ }
1288
+ return false;
1289
+ }
1290
+ case "^=": {
1291
+ if (attrValue && typeof attrValue === "string") {
1292
+ let item;
1293
+ for (const value of attrValues) {
1294
+ if (value.startsWith(`${attrValue}`)) {
1295
+ item = value;
1296
+ break;
1297
+ }
1298
+ }
1299
+ if (item) {
1300
+ return true;
1301
+ }
1302
+ return false;
1303
+ }
1304
+ return false;
1305
+ }
1306
+ case "$=": {
1307
+ if (attrValue && typeof attrValue === "string") {
1308
+ let item;
1309
+ for (const value of attrValues) {
1310
+ if (value.endsWith(`${attrValue}`)) {
1311
+ item = value;
1312
+ break;
1313
+ }
1314
+ }
1315
+ if (item) {
1316
+ return true;
1317
+ }
1318
+ return false;
1319
+ }
1320
+ return false;
1321
+ }
1322
+ case "*=": {
1323
+ if (attrValue && typeof attrValue === "string") {
1324
+ let item;
1325
+ for (const value of attrValues) {
1326
+ if (value.includes(`${attrValue}`)) {
1327
+ item = value;
1328
+ break;
1329
+ }
1330
+ }
1331
+ if (item) {
1332
+ return true;
1333
+ }
1334
+ return false;
1335
+ }
1336
+ return false;
1337
+ }
1338
+ case null:
1339
+ default: {
1340
+ return true;
1341
+ }
1342
+ }
1343
+ }
1344
+ }
1345
+ return false;
1346
+ };
1347
+ var matchTypeSelector = (ast, node, opt = {}) => {
1348
+ const astName = unescapeSelector(ast.name);
1349
+ const { localName, namespaceURI, prefix } = node;
1350
+ const { forgive } = opt;
1351
+ let {
1352
+ prefix: astPrefix,
1353
+ localName: astLocalName
1354
+ } = parseAstName(astName, node);
1355
+ if (node.ownerDocument.contentType === "text/html" && /[A-Z][\\w-]*/i.test(localName)) {
1356
+ astPrefix = astPrefix.toLowerCase();
1357
+ astLocalName = astLocalName.toLowerCase();
1358
+ }
1359
+ let nodePrefix;
1360
+ let nodeLocalName;
1361
+ if (localName.indexOf(":") > -1) {
1362
+ [nodePrefix, nodeLocalName] = localName.split(":");
1363
+ } else {
1364
+ nodePrefix = prefix || "";
1365
+ nodeLocalName = localName;
1366
+ }
1367
+ switch (astPrefix) {
1368
+ case "": {
1369
+ if (!nodePrefix && !namespaceURI && (astLocalName === "*" || astLocalName === nodeLocalName)) {
1370
+ return true;
1371
+ }
1372
+ return false;
1373
+ }
1374
+ case "*": {
1375
+ if (astLocalName === "*" || astLocalName === nodeLocalName) {
1376
+ return true;
1377
+ }
1378
+ return false;
1379
+ }
1380
+ default: {
1381
+ const astNS = node.lookupNamespaceURI(astPrefix);
1382
+ const nodeNS = node.lookupNamespaceURI(nodePrefix);
1383
+ if (astNS === nodeNS && astPrefix === nodePrefix) {
1384
+ if (astLocalName === "*" || astLocalName === nodeLocalName) {
1385
+ return true;
1386
+ }
1387
+ return false;
1388
+ } else if (!forgive && !astNS) {
1389
+ throw new DOMException(`Undeclared namespace ${astPrefix}`, SYNTAX_ERR);
1390
+ }
1391
+ return false;
1392
+ }
1393
+ }
1394
+ };
1395
+
1396
+ // src/js/finder.js
1397
+ var DIR_NEXT = "next";
1398
+ var DIR_PREV = "prev";
1399
+ var Finder = class {
1400
+ /* private fields */
1401
+ #ast;
1402
+ #astCache;
1403
+ #check;
1404
+ #descendant;
1405
+ #document;
1406
+ #documentCache;
1407
+ #domSymbolTree;
1408
+ #event;
1409
+ #focus;
1410
+ #invalidate;
1411
+ #invalidateResults;
1412
+ #lastFocusVisible;
1413
+ #node;
1414
+ #nodes;
1415
+ #noexcept;
1416
+ #pseudoElement;
1417
+ #qswalker;
1418
+ #results;
1419
+ #root;
1420
+ #selector;
1421
+ #shadow;
1422
+ #verifyShadowHost;
1423
+ #walkers;
1424
+ #warn;
1425
+ #window;
1426
+ /**
1427
+ * construct
1428
+ * @param {object} window - window
1429
+ */
1430
+ constructor(window) {
1431
+ this.#window = window;
1432
+ this.#astCache = /* @__PURE__ */ new WeakMap();
1433
+ this.#documentCache = /* @__PURE__ */ new WeakMap();
1434
+ this.#invalidateResults = /* @__PURE__ */ new WeakMap();
1435
+ this.#results = /* @__PURE__ */ new WeakMap();
1436
+ this.#event = null;
1437
+ this.#focus = null;
1438
+ this.#lastFocusVisible = null;
1439
+ this._registerEventListeners();
1440
+ }
1441
+ /**
1442
+ * handle error
1443
+ * @param {Error} e - Error
1444
+ * @param {object} [opt] - options
1445
+ * @param {boolean} [opt.noexcept] - no exception
1446
+ * @throws Error
1447
+ * @returns {void}
1448
+ */
1449
+ onError(e, opt = {}) {
1450
+ const noexcept = opt.noexcept ?? this.#noexcept;
1451
+ if (!noexcept) {
1452
+ if (e instanceof DOMException || e instanceof this.#window.DOMException) {
1453
+ if (e.name === NOT_SUPPORTED_ERR) {
1454
+ if (this.#warn) {
1455
+ console.warn(e.message);
1456
+ }
1457
+ } else {
1458
+ throw new this.#window.DOMException(e.message, e.name);
1459
+ }
1460
+ } else if (e.name in this.#window) {
1461
+ throw new this.#window[e.name](e.message);
1462
+ } else {
1463
+ throw e;
1464
+ }
1465
+ }
1466
+ }
1467
+ /**
1468
+ * setup finder
1469
+ * @param {string} selector - CSS selector
1470
+ * @param {object} node - Document, DocumentFragment, Element node
1471
+ * @param {object} [opt] - options
1472
+ * @param {boolean} [opt.noexcept] - no exception
1473
+ * @param {boolean} [opt.warn] - console warn
1474
+ * @returns {object} - finder
1475
+ */
1476
+ setup(selector, node, opt = {}) {
1477
+ const { check, domSymbolTree, noexcept, warn } = opt;
1478
+ this.#check = !!check;
1479
+ this.#domSymbolTree = domSymbolTree;
1480
+ this.#noexcept = !!noexcept;
1481
+ this.#warn = !!warn;
1482
+ this.#node = node;
1483
+ [
1484
+ this.#document,
1485
+ this.#root,
1486
+ this.#shadow
1487
+ ] = resolveContent(node);
1488
+ this.#selector = selector;
1489
+ [
1490
+ this.#ast,
1491
+ this.#nodes
1492
+ ] = this._correspond(selector);
1493
+ this.#invalidateResults = /* @__PURE__ */ new WeakMap();
1494
+ this.#pseudoElement = [];
1495
+ this.#walkers = /* @__PURE__ */ new WeakMap();
1496
+ this.#verifyShadowHost = null;
1497
+ return this;
1498
+ }
1499
+ /**
1500
+ * register event listeners
1501
+ * @private
1502
+ * @returns {Array.<void>} - results
1503
+ */
1504
+ _registerEventListeners() {
1505
+ const opt = {
1506
+ capture: true,
1507
+ passive: true
1508
+ };
1509
+ const func = [];
1510
+ const focusKeys = ["focus", "focusin"];
1511
+ for (const key of focusKeys) {
1512
+ func.push(this.#window.addEventListener(key, (evt) => {
1513
+ this.#focus = evt;
1514
+ }, opt));
1515
+ }
1516
+ const keyboardKeys = ["keydown", "keyup"];
1517
+ for (const key of keyboardKeys) {
1518
+ func.push(this.#window.addEventListener(key, (evt) => {
1519
+ const { key: key2 } = evt;
1520
+ if (!KEY_MODIFIER.includes(key2)) {
1521
+ this.#event = evt;
1522
+ }
1523
+ }, opt));
1524
+ }
1525
+ const mouseKeys = [
1526
+ "mouseover",
1527
+ "mousedown",
1528
+ "mouseup",
1529
+ "click",
1530
+ "mouseout"
1531
+ ];
1532
+ for (const key of mouseKeys) {
1533
+ func.push(this.#window.addEventListener(key, (evt) => {
1534
+ this.#event = evt;
1535
+ }, opt));
1536
+ }
1537
+ return func;
1538
+ }
1539
+ /**
1540
+ * correspond ast and nodes
1541
+ * @private
1542
+ * @param {string} selector - CSS selector
1543
+ * @returns {Array.<Array.<object>>} - array of ast and nodes
1544
+ */
1545
+ _correspond(selector) {
1546
+ const nodes = [];
1547
+ this.#descendant = false;
1548
+ this.#invalidate = false;
1549
+ let ast;
1550
+ if (this.#documentCache.has(this.#document)) {
1551
+ const cachedItem = this.#documentCache.get(this.#document);
1552
+ if (cachedItem && cachedItem.has(`${selector}`)) {
1553
+ const item = cachedItem.get(`${selector}`);
1554
+ ast = item.ast;
1555
+ this.#descendant = item.descendant;
1556
+ this.#invalidate = item.invalidate;
1557
+ }
1558
+ }
1559
+ if (ast) {
1560
+ const l = ast.length;
1561
+ for (let i = 0; i < l; i++) {
1562
+ ast[i].dir = null;
1563
+ ast[i].filtered = false;
1564
+ ast[i].find = false;
1565
+ nodes[i] = [];
1566
+ }
1567
+ } else {
1568
+ let cssAst;
1569
+ try {
1570
+ cssAst = parseSelector(selector);
1571
+ } catch (e) {
1572
+ return this.onError(e);
1573
+ }
1574
+ const { branches, info } = walkAST(cssAst);
1575
+ const {
1576
+ hasHasPseudoFunc,
1577
+ hasLogicalPseudoFunc,
1578
+ hasNthChildOfSelector,
1579
+ hasStatePseudoClass
1580
+ } = info;
1581
+ let invalidate = hasHasPseudoFunc || hasStatePseudoClass || !!(hasLogicalPseudoFunc && hasNthChildOfSelector);
1582
+ let descendant = false;
1583
+ let i = 0;
1584
+ ast = [];
1585
+ for (const [...items] of branches) {
1586
+ const branch = [];
1587
+ let item = items.shift();
1588
+ if (item && item.type !== COMBINATOR) {
1589
+ const leaves = /* @__PURE__ */ new Set();
1590
+ while (item) {
1591
+ let itemName = item.name;
1592
+ if (item.type === COMBINATOR) {
1593
+ const [nextItem] = items;
1594
+ if (nextItem.type === COMBINATOR) {
1595
+ return this.onError(new this.#window.DOMException(
1596
+ `Invalid selector ${selector}`,
1597
+ SYNTAX_ERR
1598
+ ));
1599
+ }
1600
+ if (itemName === "+" || itemName === "~") {
1601
+ invalidate = true;
1602
+ } else {
1603
+ descendant = true;
1604
+ }
1605
+ branch.push({
1606
+ combo: item,
1607
+ leaves: sortAST(leaves)
1608
+ });
1609
+ leaves.clear();
1610
+ } else if (item) {
1611
+ if (itemName && typeof itemName === "string") {
1612
+ itemName = unescapeSelector(itemName);
1613
+ if (typeof itemName === "string" && itemName !== item.name) {
1614
+ item.name = itemName;
1615
+ }
1616
+ if (/[|:]/.test(itemName)) {
1617
+ item.namespace = true;
1618
+ }
1619
+ }
1620
+ leaves.add(item);
1621
+ }
1622
+ if (items.length) {
1623
+ item = items.shift();
1624
+ } else {
1625
+ branch.push({
1626
+ combo: null,
1627
+ leaves: sortAST(leaves)
1628
+ });
1629
+ leaves.clear();
1630
+ break;
1631
+ }
1632
+ }
1633
+ }
1634
+ ast.push({
1635
+ branch,
1636
+ dir: null,
1637
+ filtered: false,
1638
+ find: false
1639
+ });
1640
+ nodes[i] = [];
1641
+ i++;
1642
+ }
1643
+ let cachedItem;
1644
+ if (this.#documentCache.has(this.#document)) {
1645
+ cachedItem = this.#documentCache.get(this.#document);
1646
+ } else {
1647
+ cachedItem = /* @__PURE__ */ new Map();
1648
+ }
1649
+ cachedItem.set(`${selector}`, {
1650
+ ast,
1651
+ descendant,
1652
+ invalidate
1653
+ });
1654
+ this.#documentCache.set(this.#document, cachedItem);
1655
+ this.#descendant = descendant;
1656
+ this.#invalidate = invalidate;
1657
+ }
1658
+ return [
1659
+ ast,
1660
+ nodes
1661
+ ];
1662
+ }
1663
+ /**
1664
+ * create tree walker
1665
+ * @private
1666
+ * @param {object} node - Document, DocumentFragment, Element node
1667
+ * @param {object} [opt] - options
1668
+ * @param {boolean} [opt.force] - force new tree walker
1669
+ * @param {number} [opt.whatToShow] - NodeFilter whatToShow
1670
+ * @returns {object} - tree walker
1671
+ */
1672
+ _createTreeWalker(node, opt = {}) {
1673
+ const { force = false, whatToShow = WALKER_FILTER } = opt;
1674
+ let walker;
1675
+ if (force) {
1676
+ walker = this.#document.createTreeWalker(node, whatToShow);
1677
+ } else if (this.#walkers.has(node)) {
1678
+ walker = this.#walkers.get(node);
1679
+ } else {
1680
+ walker = this.#document.createTreeWalker(node, whatToShow);
1681
+ this.#walkers.set(node, walker);
1682
+ }
1683
+ return walker;
1684
+ }
1685
+ /**
1686
+ * prepare querySelector walker
1687
+ * @private
1688
+ * @returns {object} - tree walker
1689
+ */
1690
+ _prepareQuerySelectorWalker() {
1691
+ this.#qswalker = this._createTreeWalker(this.#node);
1692
+ return this.#qswalker;
1693
+ }
1694
+ /**
1695
+ * collect nth child
1696
+ * @private
1697
+ * @param {object} anb - An+B options
1698
+ * @param {number} anb.a - a
1699
+ * @param {number} anb.b - b
1700
+ * @param {boolean} [anb.reverse] - reverse order
1701
+ * @param {object} [anb.selector] - AST
1702
+ * @param {object} node - Element node
1703
+ * @param {object} [opt] - options
1704
+ * @returns {Set.<object>} - collection of matched nodes
1705
+ */
1706
+ _collectNthChild(anb, node, opt = {}) {
1707
+ const { a, b, reverse, selector } = anb;
1708
+ const { parentNode } = node;
1709
+ const matched = /* @__PURE__ */ new Set();
1710
+ let selectorBranches;
1711
+ if (selector) {
1712
+ if (this.#astCache.has(selector)) {
1713
+ selectorBranches = this.#astCache.get(selector);
1714
+ } else {
1715
+ const { branches: branches2 } = walkAST(selector);
1716
+ selectorBranches = branches2;
1717
+ if (!this.#invalidate) {
1718
+ this.#astCache.set(selector, selectorBranches);
1719
+ }
1720
+ }
1721
+ const { branches } = walkAST(selector);
1722
+ selectorBranches = branches;
1723
+ }
1724
+ if (parentNode) {
1725
+ const walker = this._createTreeWalker(parentNode, {
1726
+ force: true
1727
+ });
1728
+ let refNode = walker.firstChild();
1729
+ const selectorNodes = /* @__PURE__ */ new Set();
1730
+ let l = 0;
1731
+ if (selectorBranches) {
1732
+ while (refNode) {
1733
+ if (isVisible(refNode)) {
1734
+ let bool;
1735
+ for (const leaves of selectorBranches) {
1736
+ bool = this._matchLeaves(leaves, refNode, opt);
1737
+ if (!bool) {
1738
+ break;
1739
+ }
1740
+ }
1741
+ if (bool) {
1742
+ selectorNodes.add(refNode);
1743
+ }
1744
+ }
1745
+ l++;
1746
+ refNode = walker.nextSibling();
1747
+ }
1748
+ } else {
1749
+ while (refNode) {
1750
+ l++;
1751
+ refNode = walker.nextSibling();
1752
+ }
1753
+ }
1754
+ if (a === 0) {
1755
+ if (b > 0 && b <= l) {
1756
+ if (selectorNodes.size) {
1757
+ refNode = traverseNode(parentNode, walker);
1758
+ if (reverse) {
1759
+ refNode = walker.lastChild();
1760
+ } else {
1761
+ refNode = walker.firstChild();
1762
+ }
1763
+ let i = 0;
1764
+ while (refNode) {
1765
+ if (selectorNodes.has(refNode)) {
1766
+ if (i === b - 1) {
1767
+ matched.add(refNode);
1768
+ break;
1769
+ }
1770
+ i++;
1771
+ }
1772
+ if (reverse) {
1773
+ refNode = walker.previousSibling();
1774
+ } else {
1775
+ refNode = walker.nextSibling();
1776
+ }
1777
+ }
1778
+ } else if (!selector) {
1779
+ refNode = traverseNode(parentNode, walker);
1780
+ if (reverse) {
1781
+ refNode = walker.lastChild();
1782
+ } else {
1783
+ refNode = walker.firstChild();
1784
+ }
1785
+ let i = 0;
1786
+ while (refNode) {
1787
+ if (i === b - 1) {
1788
+ matched.add(refNode);
1789
+ break;
1790
+ }
1791
+ if (reverse) {
1792
+ refNode = walker.previousSibling();
1793
+ } else {
1794
+ refNode = walker.nextSibling();
1795
+ }
1796
+ i++;
1797
+ }
1798
+ }
1799
+ }
1800
+ } else {
1801
+ let nth = b - 1;
1802
+ if (a > 0) {
1803
+ while (nth < 0) {
1804
+ nth += a;
1805
+ }
1806
+ }
1807
+ if (nth >= 0 && nth < l) {
1808
+ refNode = traverseNode(parentNode, walker);
1809
+ if (reverse) {
1810
+ refNode = walker.lastChild();
1811
+ } else {
1812
+ refNode = walker.firstChild();
1813
+ }
1814
+ let i = 0;
1815
+ let j = a > 0 ? 0 : b - 1;
1816
+ while (refNode) {
1817
+ if (refNode && nth >= 0 && nth < l) {
1818
+ if (selectorNodes.size) {
1819
+ if (selectorNodes.has(refNode)) {
1820
+ if (j === nth) {
1821
+ matched.add(refNode);
1822
+ nth += a;
1823
+ }
1824
+ if (a > 0) {
1825
+ j++;
1826
+ } else {
1827
+ j--;
1828
+ }
1829
+ }
1830
+ } else if (i === nth) {
1831
+ if (!selector) {
1832
+ matched.add(refNode);
1833
+ }
1834
+ nth += a;
1835
+ }
1836
+ if (reverse) {
1837
+ refNode = walker.previousSibling();
1838
+ } else {
1839
+ refNode = walker.nextSibling();
1840
+ }
1841
+ i++;
1842
+ } else {
1843
+ break;
1844
+ }
1845
+ }
1846
+ }
1847
+ }
1848
+ if (reverse && matched.size > 1) {
1849
+ const m = [...matched];
1850
+ return new Set(m.reverse());
1851
+ }
1852
+ } else if (node === this.#root && a + b === 1) {
1853
+ if (selectorBranches) {
1854
+ let bool;
1855
+ for (const leaves of selectorBranches) {
1856
+ bool = this._matchLeaves(leaves, node, opt);
1857
+ if (bool) {
1858
+ break;
1859
+ }
1860
+ }
1861
+ if (bool) {
1862
+ matched.add(node);
1863
+ }
1864
+ } else {
1865
+ matched.add(node);
1866
+ }
1867
+ }
1868
+ return matched;
1869
+ }
1870
+ /**
1871
+ * collect nth of type
1872
+ * @private
1873
+ * @param {object} anb - An+B options
1874
+ * @param {number} anb.a - a
1875
+ * @param {number} anb.b - b
1876
+ * @param {boolean} [anb.reverse] - reverse order
1877
+ * @param {object} node - Element node
1878
+ * @returns {Set.<object>} - collection of matched nodes
1879
+ */
1880
+ _collectNthOfType(anb, node) {
1881
+ const { a, b, reverse } = anb;
1882
+ const { localName, namespaceURI, parentNode, prefix } = node;
1883
+ const matched = /* @__PURE__ */ new Set();
1884
+ if (parentNode) {
1885
+ const walker = this._createTreeWalker(parentNode, {
1886
+ force: true
1887
+ });
1888
+ let refNode = traverseNode(parentNode, walker);
1889
+ refNode = walker.firstChild();
1890
+ let l = 0;
1891
+ while (refNode) {
1892
+ l++;
1893
+ refNode = walker.nextSibling();
1894
+ }
1895
+ if (a === 0) {
1896
+ if (b > 0 && b <= l) {
1897
+ refNode = traverseNode(parentNode, walker);
1898
+ if (reverse) {
1899
+ refNode = walker.lastChild();
1900
+ } else {
1901
+ refNode = walker.firstChild();
1902
+ }
1903
+ let j = 0;
1904
+ while (refNode) {
1905
+ const {
1906
+ localName: itemLocalName,
1907
+ namespaceURI: itemNamespaceURI,
1908
+ prefix: itemPrefix
1909
+ } = refNode;
1910
+ if (itemLocalName === localName && itemPrefix === prefix && itemNamespaceURI === namespaceURI) {
1911
+ if (j === b - 1) {
1912
+ matched.add(refNode);
1913
+ break;
1914
+ }
1915
+ j++;
1916
+ }
1917
+ if (reverse) {
1918
+ refNode = walker.previousSibling();
1919
+ } else {
1920
+ refNode = walker.nextSibling();
1921
+ }
1922
+ }
1923
+ }
1924
+ } else {
1925
+ let nth = b - 1;
1926
+ if (a > 0) {
1927
+ while (nth < 0) {
1928
+ nth += a;
1929
+ }
1930
+ }
1931
+ if (nth >= 0 && nth < l) {
1932
+ refNode = traverseNode(parentNode, walker);
1933
+ if (reverse) {
1934
+ refNode = walker.lastChild();
1935
+ } else {
1936
+ refNode = walker.firstChild();
1937
+ }
1938
+ let j = a > 0 ? 0 : b - 1;
1939
+ while (refNode) {
1940
+ const {
1941
+ localName: itemLocalName,
1942
+ namespaceURI: itemNamespaceURI,
1943
+ prefix: itemPrefix
1944
+ } = refNode;
1945
+ if (itemLocalName === localName && itemPrefix === prefix && itemNamespaceURI === namespaceURI) {
1946
+ if (j === nth) {
1947
+ matched.add(refNode);
1948
+ nth += a;
1949
+ }
1950
+ if (nth < 0 || nth >= l) {
1951
+ break;
1952
+ } else if (a > 0) {
1953
+ j++;
1954
+ } else {
1955
+ j--;
1956
+ }
1957
+ }
1958
+ if (reverse) {
1959
+ refNode = walker.previousSibling();
1960
+ } else {
1961
+ refNode = walker.nextSibling();
1962
+ }
1963
+ }
1964
+ }
1965
+ }
1966
+ if (reverse && matched.size > 1) {
1967
+ const m = [...matched];
1968
+ return new Set(m.reverse());
1969
+ }
1970
+ } else if (node === this.#root && a + b === 1) {
1971
+ matched.add(node);
1972
+ }
1973
+ return matched;
1974
+ }
1975
+ /**
1976
+ * match An+B
1977
+ * @private
1978
+ * @param {object} ast - AST
1979
+ * @param {object} node - Element node
1980
+ * @param {string} nthName - nth pseudo-class name
1981
+ * @param {object} [opt] - options
1982
+ * @returns {Set.<object>} - collection of matched nodes
1983
+ */
1984
+ _matchAnPlusB(ast, node, nthName, opt = {}) {
1985
+ const {
1986
+ nth: {
1987
+ a,
1988
+ b,
1989
+ name: nthIdentName
1990
+ },
1991
+ selector
1992
+ } = ast;
1993
+ const anbMap = /* @__PURE__ */ new Map();
1994
+ if (nthIdentName) {
1995
+ if (nthIdentName === "even") {
1996
+ anbMap.set("a", 2);
1997
+ anbMap.set("b", 0);
1998
+ } else if (nthIdentName === "odd") {
1999
+ anbMap.set("a", 2);
2000
+ anbMap.set("b", 1);
2001
+ }
2002
+ if (nthName.indexOf("last") > -1) {
2003
+ anbMap.set("reverse", true);
2004
+ }
2005
+ } else {
2006
+ if (typeof a === "string" && /-?\d+/.test(a)) {
2007
+ anbMap.set("a", a * 1);
2008
+ } else {
2009
+ anbMap.set("a", 0);
2010
+ }
2011
+ if (typeof b === "string" && /-?\d+/.test(b)) {
2012
+ anbMap.set("b", b * 1);
2013
+ } else {
2014
+ anbMap.set("b", 0);
2015
+ }
2016
+ if (nthName.indexOf("last") > -1) {
2017
+ anbMap.set("reverse", true);
2018
+ }
2019
+ }
2020
+ if (nthName === "nth-child" || nthName === "nth-last-child") {
2021
+ if (selector) {
2022
+ anbMap.set("selector", selector);
2023
+ }
2024
+ const anb = Object.fromEntries(anbMap);
2025
+ const nodes = this._collectNthChild(anb, node, opt);
2026
+ return nodes;
2027
+ } else if (nthName === "nth-of-type" || nthName === "nth-last-of-type") {
2028
+ const anb = Object.fromEntries(anbMap);
2029
+ const nodes = this._collectNthOfType(anb, node);
2030
+ return nodes;
2031
+ }
2032
+ return /* @__PURE__ */ new Set();
2033
+ }
2034
+ /**
2035
+ * match :has() pseudo-class function
2036
+ * @private
2037
+ * @param {Array.<object>} astLeaves - AST leaves
2038
+ * @param {object} node - Element node
2039
+ * @param {object} [opt] - options
2040
+ * @returns {boolean} - result
2041
+ */
2042
+ _matchHasPseudoFunc(astLeaves, node, opt = {}) {
2043
+ if (Array.isArray(astLeaves) && astLeaves.length) {
2044
+ const leaves = [...astLeaves];
2045
+ const [leaf] = leaves;
2046
+ const { type: leafType } = leaf;
2047
+ let combo;
2048
+ if (leafType === COMBINATOR) {
2049
+ combo = leaves.shift();
2050
+ } else {
2051
+ combo = {
2052
+ name: " ",
2053
+ type: COMBINATOR
2054
+ };
2055
+ }
2056
+ const twigLeaves = [];
2057
+ while (leaves.length) {
2058
+ const [item] = leaves;
2059
+ const { type: itemType } = item;
2060
+ if (itemType === COMBINATOR) {
2061
+ break;
2062
+ } else {
2063
+ twigLeaves.push(leaves.shift());
2064
+ }
2065
+ }
2066
+ const twig = {
2067
+ combo,
2068
+ leaves: twigLeaves
2069
+ };
2070
+ opt.dir = DIR_NEXT;
2071
+ const nodes = this._matchCombinator(twig, node, opt);
2072
+ if (nodes.size) {
2073
+ if (leaves.length) {
2074
+ let bool = false;
2075
+ for (const nextNode of nodes) {
2076
+ bool = this._matchHasPseudoFunc(leaves, nextNode, opt);
2077
+ if (bool) {
2078
+ break;
2079
+ }
2080
+ }
2081
+ return bool;
2082
+ }
2083
+ return true;
2084
+ }
2085
+ }
2086
+ return false;
2087
+ }
2088
+ /**
2089
+ * match logical pseudo-class functions - :has(), :is(), :not(), :where()
2090
+ * @private
2091
+ * @param {object} astData - AST data
2092
+ * @param {object} node - Element node
2093
+ * @param {object} [opt] - options
2094
+ * @returns {?object} - matched node
2095
+ */
2096
+ _matchLogicalPseudoFunc(astData, node, opt = {}) {
2097
+ const { astName, branches, twigBranches } = astData;
2098
+ const isShadowRoot = (opt.isShadowRoot || this.#shadow) && node.nodeType === DOCUMENT_FRAGMENT_NODE;
2099
+ if (astName === "has") {
2100
+ let bool;
2101
+ for (const leaves of branches) {
2102
+ bool = this._matchHasPseudoFunc(leaves, node, opt);
2103
+ if (bool) {
2104
+ break;
2105
+ }
2106
+ }
2107
+ if (bool) {
2108
+ if (isShadowRoot) {
2109
+ if (this.#verifyShadowHost) {
2110
+ return node;
2111
+ }
2112
+ } else {
2113
+ return node;
2114
+ }
2115
+ }
2116
+ } else {
2117
+ if (isShadowRoot) {
2118
+ let invalid;
2119
+ for (const branch of branches) {
2120
+ if (branch.length > 1) {
2121
+ invalid = true;
2122
+ break;
2123
+ } else if (astName === "not") {
2124
+ const [{ type: childAstType }] = branch;
2125
+ if (childAstType !== PS_CLASS_SELECTOR) {
2126
+ invalid = true;
2127
+ break;
2128
+ }
2129
+ }
2130
+ }
2131
+ if (invalid) {
2132
+ return null;
2133
+ }
2134
+ }
2135
+ opt.forgive = astName === "is" || astName === "where";
2136
+ const l = twigBranches.length;
2137
+ let bool;
2138
+ for (let i = 0; i < l; i++) {
2139
+ const branch = twigBranches[i];
2140
+ const lastIndex = branch.length - 1;
2141
+ const { leaves } = branch[lastIndex];
2142
+ bool = this._matchLeaves(leaves, node, opt);
2143
+ if (bool && lastIndex > 0) {
2144
+ let nextNodes = /* @__PURE__ */ new Set([node]);
2145
+ for (let j = lastIndex - 1; j >= 0; j--) {
2146
+ const twig = branch[j];
2147
+ const arr = [];
2148
+ opt.dir = DIR_PREV;
2149
+ for (const nextNode of nextNodes) {
2150
+ const m = this._matchCombinator(twig, nextNode, opt);
2151
+ if (m.size) {
2152
+ arr.push(...m);
2153
+ }
2154
+ }
2155
+ if (arr.length) {
2156
+ if (j === 0) {
2157
+ bool = true;
2158
+ } else {
2159
+ nextNodes = new Set(arr);
2160
+ }
2161
+ } else {
2162
+ bool = false;
2163
+ break;
2164
+ }
2165
+ }
2166
+ }
2167
+ if (bool) {
2168
+ break;
2169
+ }
2170
+ }
2171
+ if (astName === "not") {
2172
+ if (bool) {
2173
+ return null;
2174
+ }
2175
+ return node;
2176
+ } else if (bool) {
2177
+ return node;
2178
+ }
2179
+ }
2180
+ return null;
2181
+ }
2182
+ /**
2183
+ * match pseudo-class selector
2184
+ * @private
2185
+ * @see https://html.spec.whatwg.org/#pseudo-classes
2186
+ * @param {object} ast - AST
2187
+ * @param {object} node - Element node
2188
+ * @param {object} [opt] - options
2189
+ * @returns {Set.<object>} - collection of matched nodes
2190
+ */
2191
+ _matchPseudoClassSelector(ast, node, opt = {}) {
2192
+ const { children: astChildren, name: astName } = ast;
2193
+ const { localName, parentNode } = node;
2194
+ const {
2195
+ forgive,
2196
+ warn = this.#warn
2197
+ } = opt;
2198
+ const matched = /* @__PURE__ */ new Set();
2199
+ if (Array.isArray(astChildren) && KEY_LOGICAL.includes(astName)) {
2200
+ if (!astChildren.length && astName !== "is" && astName !== "where") {
2201
+ const css = (0, import_css_tree3.generate)(ast);
2202
+ return this.onError(new this.#window.DOMException(
2203
+ `Invalid selector ${css}`,
2204
+ SYNTAX_ERR
2205
+ ));
2206
+ }
2207
+ let astData;
2208
+ if (this.#astCache.has(ast)) {
2209
+ astData = this.#astCache.get(ast);
2210
+ } else {
2211
+ const { branches } = walkAST(ast);
2212
+ if (astName === "has") {
2213
+ let forgiven;
2214
+ for (const child of astChildren) {
2215
+ const item = (0, import_css_tree3.find)(child, (leaf) => {
2216
+ if (KEY_LOGICAL.includes(leaf.name) && (0, import_css_tree3.find)(leaf, (nestedLeaf) => nestedLeaf.name === "has")) {
2217
+ return leaf;
2218
+ }
2219
+ return null;
2220
+ });
2221
+ if (item) {
2222
+ const itemName = item.name;
2223
+ if (itemName === "is" || itemName === "where") {
2224
+ forgiven = true;
2225
+ break;
2226
+ } else {
2227
+ const css = (0, import_css_tree3.generate)(ast);
2228
+ return this.onError(new this.#window.DOMException(
2229
+ `Invalid selector ${css}`,
2230
+ SYNTAX_ERR
2231
+ ));
2232
+ }
2233
+ }
2234
+ }
2235
+ if (forgiven) {
2236
+ return matched;
2237
+ }
2238
+ astData = {
2239
+ astName,
2240
+ branches
2241
+ };
2242
+ } else {
2243
+ const twigBranches = [];
2244
+ for (const [...leaves] of branches) {
2245
+ const branch = [];
2246
+ const leavesSet = /* @__PURE__ */ new Set();
2247
+ let item = leaves.shift();
2248
+ while (item) {
2249
+ if (item.type === COMBINATOR) {
2250
+ branch.push({
2251
+ combo: item,
2252
+ leaves: [...leavesSet]
2253
+ });
2254
+ leavesSet.clear();
2255
+ } else if (item) {
2256
+ leavesSet.add(item);
2257
+ }
2258
+ if (leaves.length) {
2259
+ item = leaves.shift();
2260
+ } else {
2261
+ branch.push({
2262
+ combo: null,
2263
+ leaves: [...leavesSet]
2264
+ });
2265
+ leavesSet.clear();
2266
+ break;
2267
+ }
2268
+ }
2269
+ twigBranches.push(branch);
2270
+ }
2271
+ astData = {
2272
+ astName,
2273
+ branches,
2274
+ twigBranches
2275
+ };
2276
+ if (!this.#invalidate) {
2277
+ this.#astCache.set(ast, astData);
2278
+ }
2279
+ }
2280
+ }
2281
+ const res = this._matchLogicalPseudoFunc(astData, node, opt);
2282
+ if (res) {
2283
+ matched.add(res);
2284
+ }
2285
+ } else if (Array.isArray(astChildren)) {
2286
+ if (/^nth-(?:last-)?(?:child|of-type)$/.test(astName)) {
2287
+ if (astChildren.length !== 1) {
2288
+ const css = (0, import_css_tree3.generate)(ast);
2289
+ return this.onError(new this.#window.DOMException(
2290
+ `Invalid selector ${css}`,
2291
+ SYNTAX_ERR
2292
+ ));
2293
+ }
2294
+ const [branch] = astChildren;
2295
+ const nodes = this._matchAnPlusB(branch, node, astName, opt);
2296
+ return nodes;
2297
+ } else {
2298
+ switch (astName) {
2299
+ // :dir()
2300
+ case "dir": {
2301
+ if (astChildren.length !== 1) {
2302
+ const css = (0, import_css_tree3.generate)(ast);
2303
+ return this.onError(new this.#window.DOMException(
2304
+ `Invalid selector ${css}`,
2305
+ SYNTAX_ERR
2306
+ ));
2307
+ }
2308
+ const [astChild] = astChildren;
2309
+ const res = matchDirectionPseudoClass(astChild, node);
2310
+ if (res) {
2311
+ matched.add(node);
2312
+ }
2313
+ break;
2314
+ }
2315
+ // :lang()
2316
+ case "lang": {
2317
+ if (!astChildren.length) {
2318
+ const css = (0, import_css_tree3.generate)(ast);
2319
+ return this.onError(new this.#window.DOMException(
2320
+ `Invalid selector ${css}`,
2321
+ SYNTAX_ERR
2322
+ ));
2323
+ }
2324
+ let bool;
2325
+ for (const astChild of astChildren) {
2326
+ bool = matchLanguagePseudoClass(astChild, node);
2327
+ if (bool) {
2328
+ break;
2329
+ }
2330
+ }
2331
+ if (bool) {
2332
+ matched.add(node);
2333
+ }
2334
+ break;
2335
+ }
2336
+ // :state()
2337
+ case "state": {
2338
+ if (isCustomElement(node)) {
2339
+ const [{ value: stateValue }] = astChildren;
2340
+ if (stateValue) {
2341
+ if (node[stateValue]) {
2342
+ matched.add(node);
2343
+ } else {
2344
+ for (const i in node) {
2345
+ const prop = node[i];
2346
+ if (prop instanceof this.#window.ElementInternals) {
2347
+ if (prop?.states?.has(stateValue)) {
2348
+ matched.add(node);
2349
+ }
2350
+ break;
2351
+ }
2352
+ }
2353
+ }
2354
+ }
2355
+ }
2356
+ break;
2357
+ }
2358
+ case "current":
2359
+ case "nth-col":
2360
+ case "nth-last-col": {
2361
+ if (warn) {
2362
+ this.onError(new this.#window.DOMException(
2363
+ `Unsupported pseudo-class :${astName}()`,
2364
+ NOT_SUPPORTED_ERR
2365
+ ));
2366
+ }
2367
+ break;
2368
+ }
2369
+ case "host":
2370
+ case "host-context": {
2371
+ break;
2372
+ }
2373
+ // dropped from CSS Selectors 3
2374
+ case "contains": {
2375
+ if (warn) {
2376
+ this.onError(new this.#window.DOMException(
2377
+ `Unknown pseudo-class :${astName}()`,
2378
+ NOT_SUPPORTED_ERR
2379
+ ));
2380
+ }
2381
+ break;
2382
+ }
2383
+ default: {
2384
+ if (!forgive) {
2385
+ this.onError(new this.#window.DOMException(
2386
+ `Unknown pseudo-class :${astName}()`,
2387
+ SYNTAX_ERR
2388
+ ));
2389
+ }
2390
+ }
2391
+ }
2392
+ }
2393
+ } else {
2394
+ switch (astName) {
2395
+ case "any-link":
2396
+ case "link": {
2397
+ if ((localName === "a" || localName === "area") && node.hasAttribute("href")) {
2398
+ matched.add(node);
2399
+ }
2400
+ break;
2401
+ }
2402
+ case "local-link": {
2403
+ if ((localName === "a" || localName === "area") && node.hasAttribute("href")) {
2404
+ const { href, origin, pathname } = new URL(this.#document.URL);
2405
+ const attrURL = new URL(node.getAttribute("href"), href);
2406
+ if (attrURL.origin === origin && attrURL.pathname === pathname) {
2407
+ matched.add(node);
2408
+ }
2409
+ }
2410
+ break;
2411
+ }
2412
+ case "visited": {
2413
+ break;
2414
+ }
2415
+ case "hover": {
2416
+ const { target, type } = this.#event ?? {};
2417
+ if (/^(?:click|mouse(?:down|over|up))$/.test(type) && node.contains(target)) {
2418
+ matched.add(node);
2419
+ }
2420
+ break;
2421
+ }
2422
+ case "active": {
2423
+ const { buttons, target, type } = this.#event ?? {};
2424
+ if (type === "mousedown" && buttons & BIT_01 && node.contains(target)) {
2425
+ matched.add(node);
2426
+ }
2427
+ break;
2428
+ }
2429
+ case "target": {
2430
+ const { hash } = new URL(this.#document.URL);
2431
+ if (node.id && hash === `#${node.id}` && this.#document.contains(node)) {
2432
+ matched.add(node);
2433
+ }
2434
+ break;
2435
+ }
2436
+ case "target-within": {
2437
+ const { hash } = new URL(this.#document.URL);
2438
+ if (hash) {
2439
+ const id = hash.replace(/^#/, "");
2440
+ let current = this.#document.getElementById(id);
2441
+ while (current) {
2442
+ if (current === node) {
2443
+ matched.add(node);
2444
+ break;
2445
+ }
2446
+ current = current.parentNode;
2447
+ }
2448
+ }
2449
+ break;
2450
+ }
2451
+ case "scope": {
2452
+ if (this.#node.nodeType === ELEMENT_NODE) {
2453
+ if (!this.#shadow && node === this.#node) {
2454
+ matched.add(node);
2455
+ }
2456
+ } else if (node === this.#document.documentElement) {
2457
+ matched.add(node);
2458
+ }
2459
+ break;
2460
+ }
2461
+ case "focus": {
2462
+ if (node === this.#document.activeElement && isFocusableArea(node)) {
2463
+ matched.add(node);
2464
+ }
2465
+ break;
2466
+ }
2467
+ case "focus-visible": {
2468
+ if (node === this.#document.activeElement && isFocusableArea(node)) {
2469
+ let bool;
2470
+ if (isFocusVisible(node)) {
2471
+ bool = true;
2472
+ } else if (this.#focus) {
2473
+ const { relatedTarget, target: focusTarget } = this.#focus;
2474
+ if (focusTarget === node) {
2475
+ if (isFocusVisible(relatedTarget)) {
2476
+ bool = true;
2477
+ } else if (this.#event) {
2478
+ const {
2479
+ key: eventKey,
2480
+ target: eventTarget,
2481
+ type: eventType
2482
+ } = this.#event;
2483
+ if (eventTarget === relatedTarget) {
2484
+ if (this.#lastFocusVisible === null) {
2485
+ bool = true;
2486
+ } else if (focusTarget === this.#lastFocusVisible) {
2487
+ bool = true;
2488
+ }
2489
+ } else if (eventKey === "Tab") {
2490
+ if (eventType === "keydown" && eventTarget !== node || eventType === "keyup" && eventTarget === node) {
2491
+ if (eventTarget === focusTarget) {
2492
+ if (this.#lastFocusVisible === null) {
2493
+ bool = true;
2494
+ } else if (eventTarget === this.#lastFocusVisible && relatedTarget === null) {
2495
+ bool = true;
2496
+ }
2497
+ } else {
2498
+ bool = true;
2499
+ }
2500
+ }
2501
+ } else if (eventKey) {
2502
+ if ((eventType === "keydown" || eventType === "keyup") && eventTarget === node) {
2503
+ bool = true;
2504
+ }
2505
+ }
2506
+ } else if (relatedTarget === null || relatedTarget === this.#lastFocusVisible) {
2507
+ bool = true;
2508
+ }
2509
+ }
2510
+ }
2511
+ if (bool) {
2512
+ this.#lastFocusVisible = node;
2513
+ matched.add(node);
2514
+ } else if (this.#lastFocusVisible === node) {
2515
+ this.#lastFocusVisible = null;
2516
+ }
2517
+ }
2518
+ break;
2519
+ }
2520
+ case "focus-within": {
2521
+ let bool;
2522
+ let current = this.#document.activeElement;
2523
+ if (isFocusableArea(current)) {
2524
+ while (current) {
2525
+ if (current === node) {
2526
+ bool = true;
2527
+ break;
2528
+ }
2529
+ current = current.parentNode;
2530
+ }
2531
+ }
2532
+ if (bool) {
2533
+ matched.add(node);
2534
+ }
2535
+ break;
2536
+ }
2537
+ case "open":
2538
+ case "closed": {
2539
+ if (localName === "details" || localName === "dialog") {
2540
+ if (node.hasAttribute("open")) {
2541
+ if (astName === "open") {
2542
+ matched.add(node);
2543
+ }
2544
+ } else if (astName === "closed") {
2545
+ matched.add(node);
2546
+ }
2547
+ }
2548
+ break;
2549
+ }
2550
+ case "disabled":
2551
+ case "enabled": {
2552
+ const keys = [...KEY_FORM_FOCUS, "fieldset", "optgroup", "option"];
2553
+ if (keys.includes(localName) || isCustomElement(node, { formAssociated: true })) {
2554
+ let disabled;
2555
+ if (node.disabled || node.hasAttribute("disabled")) {
2556
+ disabled = true;
2557
+ } else if (node.localName === "option") {
2558
+ if (parentNode.localName === "optgroup" && (parentNode.disabled || parentNode.hasAttribute("disabled"))) {
2559
+ disabled = true;
2560
+ }
2561
+ } else if (node.localName !== "optgroup") {
2562
+ let parent = parentNode;
2563
+ while (parent) {
2564
+ if (parent.localName === "fieldset" && (parent.disabled || parent.hasAttribute("disabled"))) {
2565
+ let refNode = parent.firstElementChild;
2566
+ while (refNode) {
2567
+ if (refNode.localName === "legend") {
2568
+ break;
2569
+ }
2570
+ refNode = refNode.nextElementSibling;
2571
+ }
2572
+ if (refNode) {
2573
+ if (!refNode.contains(node)) {
2574
+ disabled = true;
2575
+ }
2576
+ } else {
2577
+ disabled = true;
2578
+ }
2579
+ break;
2580
+ } else if (parent.localName === "form") {
2581
+ break;
2582
+ } else if (parent.parentNode?.nodeType === ELEMENT_NODE) {
2583
+ if (parent.parentNode.localName === "form") {
2584
+ break;
2585
+ } else {
2586
+ parent = parent.parentNode;
2587
+ }
2588
+ } else {
2589
+ break;
2590
+ }
2591
+ }
2592
+ }
2593
+ if (disabled) {
2594
+ if (astName === "disabled") {
2595
+ matched.add(node);
2596
+ }
2597
+ } else if (astName === "enabled") {
2598
+ matched.add(node);
2599
+ }
2600
+ }
2601
+ break;
2602
+ }
2603
+ case "read-only":
2604
+ case "read-write": {
2605
+ let readonly;
2606
+ let writable;
2607
+ switch (localName) {
2608
+ case "textarea": {
2609
+ if (node.readOnly || node.hasAttribute("readonly") || node.disabled || node.hasAttribute("disabled")) {
2610
+ readonly = true;
2611
+ } else {
2612
+ writable = true;
2613
+ }
2614
+ break;
2615
+ }
2616
+ case "input": {
2617
+ if (!node.type || KEY_INPUT_EDIT.includes(node.type)) {
2618
+ if (node.readOnly || node.hasAttribute("readonly") || node.disabled || node.hasAttribute("disabled")) {
2619
+ readonly = true;
2620
+ } else {
2621
+ writable = true;
2622
+ }
2623
+ } else {
2624
+ readonly = true;
2625
+ }
2626
+ break;
2627
+ }
2628
+ default: {
2629
+ if (isContentEditable(node)) {
2630
+ writable = true;
2631
+ } else {
2632
+ readonly = true;
2633
+ }
2634
+ }
2635
+ }
2636
+ if (readonly) {
2637
+ if (astName === "read-only") {
2638
+ matched.add(node);
2639
+ }
2640
+ } else if (astName === "read-write" && writable) {
2641
+ matched.add(node);
2642
+ }
2643
+ break;
2644
+ }
2645
+ case "placeholder-shown": {
2646
+ let placeholder;
2647
+ if (node.placeholder) {
2648
+ placeholder = node.placeholder;
2649
+ } else if (node.hasAttribute("placeholder")) {
2650
+ placeholder = node.getAttribute("placeholder");
2651
+ }
2652
+ if (typeof placeholder === "string" && !/[\r\n]/.test(placeholder)) {
2653
+ let targetNode;
2654
+ if (localName === "textarea") {
2655
+ targetNode = node;
2656
+ } else if (localName === "input") {
2657
+ if (node.hasAttribute("type")) {
2658
+ const keys = [...KEY_INPUT_TEXT, "number"];
2659
+ if (keys.includes(node.getAttribute("type"))) {
2660
+ targetNode = node;
2661
+ }
2662
+ } else {
2663
+ targetNode = node;
2664
+ }
2665
+ }
2666
+ if (targetNode && node.value === "") {
2667
+ matched.add(node);
2668
+ }
2669
+ }
2670
+ break;
2671
+ }
2672
+ case "checked": {
2673
+ const attrType = node.getAttribute("type");
2674
+ if (node.checked && localName === "input" && (attrType === "checkbox" || attrType === "radio") || node.selected && localName === "option") {
2675
+ matched.add(node);
2676
+ }
2677
+ break;
2678
+ }
2679
+ case "indeterminate": {
2680
+ if (node.indeterminate && localName === "input" && node.type === "checkbox" || localName === "progress" && !node.hasAttribute("value")) {
2681
+ matched.add(node);
2682
+ } else if (localName === "input" && node.type === "radio" && !node.hasAttribute("checked")) {
2683
+ const nodeName = node.name;
2684
+ let parent = node.parentNode;
2685
+ while (parent) {
2686
+ if (parent.localName === "form") {
2687
+ break;
2688
+ }
2689
+ parent = parent.parentNode;
2690
+ }
2691
+ if (!parent) {
2692
+ parent = this.#document.documentElement;
2693
+ }
2694
+ const walker = this._createTreeWalker(parent);
2695
+ let refNode = traverseNode(parent, walker);
2696
+ refNode = walker.firstChild();
2697
+ let checked;
2698
+ while (refNode) {
2699
+ if (refNode.localName === "input" && refNode.getAttribute("type") === "radio") {
2700
+ if (refNode.hasAttribute("name")) {
2701
+ if (refNode.getAttribute("name") === nodeName) {
2702
+ checked = !!refNode.checked;
2703
+ }
2704
+ } else {
2705
+ checked = !!refNode.checked;
2706
+ }
2707
+ if (checked) {
2708
+ break;
2709
+ }
2710
+ }
2711
+ refNode = walker.nextNode();
2712
+ }
2713
+ if (!checked) {
2714
+ matched.add(node);
2715
+ }
2716
+ }
2717
+ break;
2718
+ }
2719
+ case "default": {
2720
+ const chekcKeys = ["checkbox", "radio"];
2721
+ const resetKeys = ["button", "reset"];
2722
+ const submitKeys = ["image", "submit"];
2723
+ const attrType = node.getAttribute("type");
2724
+ if (localName === "button" && !(node.hasAttribute("type") && resetKeys.includes(attrType)) || localName === "input" && node.hasAttribute("type") && submitKeys.includes(attrType)) {
2725
+ let form = node.parentNode;
2726
+ while (form) {
2727
+ if (form.localName === "form") {
2728
+ break;
2729
+ }
2730
+ form = form.parentNode;
2731
+ }
2732
+ if (form) {
2733
+ const walker = this._createTreeWalker(form);
2734
+ let refNode = traverseNode(form, walker);
2735
+ refNode = walker.firstChild();
2736
+ while (refNode) {
2737
+ const nodeName = refNode.localName;
2738
+ const nodeAttrType = refNode.getAttribute("type");
2739
+ let m;
2740
+ if (nodeName === "button") {
2741
+ m = !(refNode.hasAttribute("type") && resetKeys.includes(nodeAttrType));
2742
+ } else if (nodeName === "input") {
2743
+ m = refNode.hasAttribute("type") && submitKeys.includes(nodeAttrType);
2744
+ }
2745
+ if (m) {
2746
+ if (refNode === node) {
2747
+ matched.add(node);
2748
+ }
2749
+ break;
2750
+ }
2751
+ refNode = walker.nextNode();
2752
+ }
2753
+ }
2754
+ } else if (localName === "input" && node.hasAttribute("type") && chekcKeys.includes(attrType) && node.hasAttribute("checked")) {
2755
+ matched.add(node);
2756
+ } else if (localName === "option" && node.hasAttribute("selected")) {
2757
+ matched.add(node);
2758
+ }
2759
+ break;
2760
+ }
2761
+ case "valid":
2762
+ case "invalid": {
2763
+ const keys = [...KEY_FORM_FOCUS, "form"];
2764
+ if (keys.includes(localName)) {
2765
+ let valid;
2766
+ if (node.checkValidity()) {
2767
+ if (node.maxLength >= 0) {
2768
+ if (node.maxLength >= node.value.length) {
2769
+ valid = true;
2770
+ }
2771
+ } else {
2772
+ valid = true;
2773
+ }
2774
+ }
2775
+ if (valid) {
2776
+ if (astName === "valid") {
2777
+ matched.add(node);
2778
+ }
2779
+ } else if (astName === "invalid") {
2780
+ matched.add(node);
2781
+ }
2782
+ } else if (localName === "fieldset") {
2783
+ const walker = this._createTreeWalker(node);
2784
+ let refNode = traverseNode(node, walker);
2785
+ refNode = walker.firstChild();
2786
+ let valid;
2787
+ if (!refNode) {
2788
+ valid = true;
2789
+ } else {
2790
+ while (refNode) {
2791
+ if (keys.includes(refNode.localName)) {
2792
+ if (refNode.checkValidity()) {
2793
+ if (refNode.maxLength >= 0) {
2794
+ valid = refNode.maxLength >= refNode.value.length;
2795
+ } else {
2796
+ valid = true;
2797
+ }
2798
+ } else {
2799
+ valid = false;
2800
+ }
2801
+ if (!valid) {
2802
+ break;
2803
+ }
2804
+ }
2805
+ refNode = walker.nextNode();
2806
+ }
2807
+ }
2808
+ if (valid) {
2809
+ if (astName === "valid") {
2810
+ matched.add(node);
2811
+ }
2812
+ } else if (astName === "invalid") {
2813
+ matched.add(node);
2814
+ }
2815
+ }
2816
+ break;
2817
+ }
2818
+ case "in-range":
2819
+ case "out-of-range": {
2820
+ const keys = [...KEY_INPUT_DATE, "number", "range"];
2821
+ const attrType = node.getAttribute("type");
2822
+ if (localName === "input" && !(node.readonly || node.hasAttribute("readonly")) && !(node.disabled || node.hasAttribute("disabled")) && keys.includes(attrType)) {
2823
+ const flowed = node.validity.rangeUnderflow || node.validity.rangeOverflow;
2824
+ if (astName === "out-of-range" && flowed) {
2825
+ matched.add(node);
2826
+ } else if (astName === "in-range" && !flowed && (node.hasAttribute("min") || node.hasAttribute("max") || attrType === "range")) {
2827
+ matched.add(node);
2828
+ }
2829
+ }
2830
+ break;
2831
+ }
2832
+ case "required":
2833
+ case "optional": {
2834
+ let required;
2835
+ let optional;
2836
+ if (localName === "select" || localName === "textarea") {
2837
+ if (node.required || node.hasAttribute("required")) {
2838
+ required = true;
2839
+ } else {
2840
+ optional = true;
2841
+ }
2842
+ } else if (localName === "input") {
2843
+ if (node.hasAttribute("type")) {
2844
+ const keys = [...KEY_INPUT_EDIT, "checkbox", "file", "radio"];
2845
+ const attrType = node.getAttribute("type");
2846
+ if (keys.includes(attrType)) {
2847
+ if (node.required || node.hasAttribute("required")) {
2848
+ required = true;
2849
+ } else {
2850
+ optional = true;
2851
+ }
2852
+ } else {
2853
+ optional = true;
2854
+ }
2855
+ } else if (node.required || node.hasAttribute("required")) {
2856
+ required = true;
2857
+ } else {
2858
+ optional = true;
2859
+ }
2860
+ }
2861
+ if (astName === "required" && required) {
2862
+ matched.add(node);
2863
+ } else if (astName === "optional" && optional) {
2864
+ matched.add(node);
2865
+ }
2866
+ break;
2867
+ }
2868
+ case "root": {
2869
+ if (node === this.#document.documentElement) {
2870
+ matched.add(node);
2871
+ }
2872
+ break;
2873
+ }
2874
+ case "empty": {
2875
+ if (node.hasChildNodes()) {
2876
+ const walker = this._createTreeWalker(node, {
2877
+ force: true,
2878
+ whatToShow: SHOW_ALL
2879
+ });
2880
+ let refNode = walker.firstChild();
2881
+ let bool;
2882
+ while (refNode) {
2883
+ bool = refNode.nodeType !== ELEMENT_NODE && refNode.nodeType !== TEXT_NODE;
2884
+ if (!bool) {
2885
+ break;
2886
+ }
2887
+ refNode = walker.nextSibling();
2888
+ }
2889
+ if (bool) {
2890
+ matched.add(node);
2891
+ }
2892
+ } else {
2893
+ matched.add(node);
2894
+ }
2895
+ break;
2896
+ }
2897
+ case "first-child": {
2898
+ if (parentNode && node === parentNode.firstElementChild || node === this.#root) {
2899
+ matched.add(node);
2900
+ }
2901
+ break;
2902
+ }
2903
+ case "last-child": {
2904
+ if (parentNode && node === parentNode.lastElementChild || node === this.#root) {
2905
+ matched.add(node);
2906
+ }
2907
+ break;
2908
+ }
2909
+ case "only-child": {
2910
+ if (parentNode && node === parentNode.firstElementChild && node === parentNode.lastElementChild || node === this.#root) {
2911
+ matched.add(node);
2912
+ }
2913
+ break;
2914
+ }
2915
+ case "first-of-type": {
2916
+ if (parentNode) {
2917
+ const [node1] = this._collectNthOfType({
2918
+ a: 0,
2919
+ b: 1
2920
+ }, node);
2921
+ if (node1) {
2922
+ matched.add(node1);
2923
+ }
2924
+ } else if (node === this.#root) {
2925
+ matched.add(node);
2926
+ }
2927
+ break;
2928
+ }
2929
+ case "last-of-type": {
2930
+ if (parentNode) {
2931
+ const [node1] = this._collectNthOfType({
2932
+ a: 0,
2933
+ b: 1,
2934
+ reverse: true
2935
+ }, node);
2936
+ if (node1) {
2937
+ matched.add(node1);
2938
+ }
2939
+ } else if (node === this.#root) {
2940
+ matched.add(node);
2941
+ }
2942
+ break;
2943
+ }
2944
+ case "only-of-type": {
2945
+ if (parentNode) {
2946
+ const [node1] = this._collectNthOfType({
2947
+ a: 0,
2948
+ b: 1
2949
+ }, node);
2950
+ if (node1 === node) {
2951
+ const [node2] = this._collectNthOfType({
2952
+ a: 0,
2953
+ b: 1,
2954
+ reverse: true
2955
+ }, node);
2956
+ if (node2 === node) {
2957
+ matched.add(node);
2958
+ }
2959
+ }
2960
+ } else if (node === this.#root) {
2961
+ matched.add(node);
2962
+ }
2963
+ break;
2964
+ }
2965
+ case "defined": {
2966
+ if (node.hasAttribute("is") || localName.includes("-")) {
2967
+ if (isCustomElement(node)) {
2968
+ matched.add(node);
2969
+ }
2970
+ } else if (node instanceof this.#window.HTMLElement || node instanceof this.#window.SVGElement) {
2971
+ matched.add(node);
2972
+ }
2973
+ break;
2974
+ }
2975
+ case "popover-open": {
2976
+ if (node.popover && isVisible(node)) {
2977
+ matched.add(node);
2978
+ }
2979
+ break;
2980
+ }
2981
+ case "host":
2982
+ case "host-context": {
2983
+ break;
2984
+ }
2985
+ // legacy pseudo-elements
2986
+ case "after":
2987
+ case "before":
2988
+ case "first-letter":
2989
+ case "first-line": {
2990
+ if (warn) {
2991
+ this.onError(new this.#window.DOMException(
2992
+ `Unsupported pseudo-element ::${astName}`,
2993
+ NOT_SUPPORTED_ERR
2994
+ ));
2995
+ }
2996
+ break;
2997
+ }
2998
+ // not supported
2999
+ case "autofill":
3000
+ case "blank":
3001
+ case "buffering":
3002
+ case "current":
3003
+ case "fullscreen":
3004
+ case "future":
3005
+ case "has-slotted":
3006
+ case "modal":
3007
+ case "muted":
3008
+ case "past":
3009
+ case "paused":
3010
+ case "picture-in-picture":
3011
+ case "playing":
3012
+ case "seeking":
3013
+ case "stalled":
3014
+ case "user-invalid":
3015
+ case "user-valid":
3016
+ case "volume-locked":
3017
+ case "-webkit-autofill": {
3018
+ if (warn) {
3019
+ this.onError(new this.#window.DOMException(
3020
+ `Unsupported pseudo-class :${astName}`,
3021
+ NOT_SUPPORTED_ERR
3022
+ ));
3023
+ }
3024
+ break;
3025
+ }
3026
+ default: {
3027
+ if (astName.startsWith("-webkit-")) {
3028
+ if (warn) {
3029
+ this.onError(new this.#window.DOMException(
3030
+ `Unsupported pseudo-class :${astName}`,
3031
+ NOT_SUPPORTED_ERR
3032
+ ));
3033
+ }
3034
+ } else if (!forgive) {
3035
+ this.onError(new this.#window.DOMException(
3036
+ `Unknown pseudo-class :${astName}`,
3037
+ SYNTAX_ERR
3038
+ ));
3039
+ }
3040
+ }
3041
+ }
3042
+ }
3043
+ return matched;
3044
+ }
3045
+ /**
3046
+ * match shadow host pseudo class
3047
+ * @private
3048
+ * @param {object} ast - AST
3049
+ * @param {object} node - DocumentFragment node
3050
+ * @returns {?object} - matched node
3051
+ */
3052
+ _matchShadowHostPseudoClass(ast, node) {
3053
+ const { children: astChildren, name: astName } = ast;
3054
+ if (Array.isArray(astChildren)) {
3055
+ if (astChildren.length !== 1) {
3056
+ const css = (0, import_css_tree3.generate)(ast);
3057
+ return this.onError(new this.#window.DOMException(
3058
+ `Invalid selector ${css}`,
3059
+ SYNTAX_ERR
3060
+ ));
3061
+ }
3062
+ const { branches } = walkAST(astChildren[0]);
3063
+ const [branch] = branches;
3064
+ const [...leaves] = branch;
3065
+ const { host } = node;
3066
+ if (astName === "host") {
3067
+ let bool;
3068
+ for (const leaf of leaves) {
3069
+ const { type: leafType } = leaf;
3070
+ if (leafType === COMBINATOR) {
3071
+ const css = (0, import_css_tree3.generate)(ast);
3072
+ return this.onError(new this.#window.DOMException(
3073
+ `Invalid selector ${css}`,
3074
+ SYNTAX_ERR
3075
+ ));
3076
+ }
3077
+ bool = this._matchSelector(leaf, host).has(host);
3078
+ if (!bool) {
3079
+ break;
3080
+ }
3081
+ }
3082
+ if (bool) {
3083
+ return node;
3084
+ }
3085
+ return null;
3086
+ } else if (astName === "host-context") {
3087
+ let parent = host;
3088
+ let bool;
3089
+ while (parent) {
3090
+ for (const leaf of leaves) {
3091
+ const { type: leafType } = leaf;
3092
+ if (leafType === COMBINATOR) {
3093
+ const css = (0, import_css_tree3.generate)(ast);
3094
+ return this.onError(new this.#window.DOMException(
3095
+ `Invalid selector ${css}`,
3096
+ SYNTAX_ERR
3097
+ ));
3098
+ }
3099
+ bool = this._matchSelector(leaf, parent).has(parent);
3100
+ if (!bool) {
3101
+ break;
3102
+ }
3103
+ }
3104
+ if (bool) {
3105
+ break;
3106
+ } else {
3107
+ parent = parent.parentNode;
3108
+ }
3109
+ }
3110
+ if (bool) {
3111
+ return node;
3112
+ }
3113
+ return null;
3114
+ }
3115
+ } else if (astName === "host") {
3116
+ return node;
3117
+ }
3118
+ return this.onError(new this.#window.DOMException(
3119
+ `Invalid selector :${astName}`,
3120
+ SYNTAX_ERR
3121
+ ));
3122
+ }
3123
+ /**
3124
+ * match selector
3125
+ * @private
3126
+ * @param {object} ast - AST
3127
+ * @param {object} node - Document, DocumentFragment, Element node
3128
+ * @param {object} [opt] - options
3129
+ * @returns {Set.<object>} - collection of matched nodes
3130
+ */
3131
+ _matchSelector(ast, node, opt = {}) {
3132
+ const { type: astType } = ast;
3133
+ const astName = unescapeSelector(ast.name);
3134
+ const matched = /* @__PURE__ */ new Set();
3135
+ if (node.nodeType === ELEMENT_NODE) {
3136
+ switch (astType) {
3137
+ case ATTR_SELECTOR: {
3138
+ const res = matchAttributeSelector(ast, node);
3139
+ if (res) {
3140
+ matched.add(node);
3141
+ }
3142
+ break;
3143
+ }
3144
+ case ID_SELECTOR: {
3145
+ if (node.id === astName) {
3146
+ matched.add(node);
3147
+ }
3148
+ break;
3149
+ }
3150
+ case CLASS_SELECTOR: {
3151
+ if (node.classList.contains(astName)) {
3152
+ matched.add(node);
3153
+ }
3154
+ break;
3155
+ }
3156
+ case PS_CLASS_SELECTOR: {
3157
+ const nodes = this._matchPseudoClassSelector(ast, node, opt);
3158
+ return nodes;
3159
+ }
3160
+ case TYPE_SELECTOR: {
3161
+ const res = matchTypeSelector(ast, node, opt);
3162
+ if (res) {
3163
+ matched.add(node);
3164
+ }
3165
+ break;
3166
+ }
3167
+ case PS_ELEMENT_SELECTOR:
3168
+ default: {
3169
+ try {
3170
+ matchPseudoElementSelector(astName, astType, opt);
3171
+ } catch (e) {
3172
+ this.onError(e);
3173
+ }
3174
+ }
3175
+ }
3176
+ } else if (this.#shadow && astType === PS_CLASS_SELECTOR && node.nodeType === DOCUMENT_FRAGMENT_NODE) {
3177
+ if (KEY_LOGICAL.includes(astName)) {
3178
+ opt.isShadowRoot = true;
3179
+ const nodes = this._matchPseudoClassSelector(ast, node, opt);
3180
+ return nodes;
3181
+ } else if (astName === "host" || astName === "host-context") {
3182
+ const res = this._matchShadowHostPseudoClass(ast, node, opt);
3183
+ if (res) {
3184
+ this.#verifyShadowHost = true;
3185
+ matched.add(res);
3186
+ }
3187
+ }
3188
+ }
3189
+ return matched;
3190
+ }
3191
+ /**
3192
+ * match leaves
3193
+ * @private
3194
+ * @param {Array.<object>} leaves - AST leaves
3195
+ * @param {object} node - node
3196
+ * @param {object} [opt] - options
3197
+ * @returns {boolean} - result
3198
+ */
3199
+ _matchLeaves(leaves, node, opt = {}) {
3200
+ let result;
3201
+ if (this.#invalidate) {
3202
+ result = this.#invalidateResults.get(leaves);
3203
+ } else {
3204
+ result = this.#results.get(leaves);
3205
+ }
3206
+ if (result && result.has(node)) {
3207
+ const { matched } = result.get(node);
3208
+ return matched;
3209
+ } else {
3210
+ let cacheable = true;
3211
+ const formKeys = [...KEY_FORM_FOCUS, "fieldset", "form"];
3212
+ const pseudoKeys = ["any-link", "defined", "dir", "link"];
3213
+ if (node.nodeType === ELEMENT_NODE && formKeys.includes(node.localName)) {
3214
+ cacheable = false;
3215
+ }
3216
+ let bool;
3217
+ for (const leaf of leaves) {
3218
+ switch (leaf.type) {
3219
+ case ATTR_SELECTOR:
3220
+ case ID_SELECTOR: {
3221
+ cacheable = false;
3222
+ break;
3223
+ }
3224
+ case PS_CLASS_SELECTOR: {
3225
+ if (pseudoKeys.includes(leaf.name)) {
3226
+ cacheable = false;
3227
+ }
3228
+ break;
3229
+ }
3230
+ default:
3231
+ }
3232
+ bool = this._matchSelector(leaf, node, opt).has(node);
3233
+ if (!bool) {
3234
+ break;
3235
+ }
3236
+ }
3237
+ if (cacheable) {
3238
+ if (!result) {
3239
+ result = /* @__PURE__ */ new WeakMap();
3240
+ }
3241
+ result.set(node, {
3242
+ matched: bool
3243
+ });
3244
+ if (this.#invalidate) {
3245
+ this.#invalidateResults.set(leaves, result);
3246
+ } else {
3247
+ this.#results.set(leaves, result);
3248
+ }
3249
+ }
3250
+ return bool;
3251
+ }
3252
+ }
3253
+ /**
3254
+ * find descendant nodes
3255
+ * @private
3256
+ * @param {Array.<object>} leaves - AST leaves
3257
+ * @param {object} baseNode - base Element node or Element.shadowRoot
3258
+ * @param {object} [opt] - options
3259
+ * @returns {Set.<object>} - collection of matched nodes
3260
+ */
3261
+ _findDescendantNodes(leaves, baseNode, opt = {}) {
3262
+ const [leaf, ...filterLeaves] = leaves;
3263
+ const compound = filterLeaves.length > 0;
3264
+ const { type: leafType } = leaf;
3265
+ const leafName = unescapeSelector(leaf.name);
3266
+ const nodes = /* @__PURE__ */ new Set();
3267
+ let pending = false;
3268
+ if (this.#shadow || baseNode.nodeType !== ELEMENT_NODE) {
3269
+ pending = true;
3270
+ } else {
3271
+ switch (leafType) {
3272
+ case PS_ELEMENT_SELECTOR: {
3273
+ matchPseudoElementSelector(leafName, leafType, opt);
3274
+ break;
3275
+ }
3276
+ case ID_SELECTOR: {
3277
+ if (this.#root.nodeType === ELEMENT_NODE) {
3278
+ pending = true;
3279
+ } else {
3280
+ const node = this.#root.getElementById(leafName);
3281
+ if (node && node !== baseNode && baseNode.contains(node)) {
3282
+ if (compound) {
3283
+ const bool = this._matchLeaves(filterLeaves, node, opt);
3284
+ if (bool) {
3285
+ nodes.add(node);
3286
+ }
3287
+ } else {
3288
+ nodes.add(node);
3289
+ }
3290
+ }
3291
+ }
3292
+ break;
3293
+ }
3294
+ default: {
3295
+ pending = true;
3296
+ }
3297
+ }
3298
+ }
3299
+ if (pending) {
3300
+ const walker = this._createTreeWalker(baseNode);
3301
+ let refNode = traverseNode(baseNode, walker);
3302
+ refNode = walker.firstChild();
3303
+ while (refNode) {
3304
+ const bool = this._matchLeaves(leaves, refNode, opt);
3305
+ if (bool) {
3306
+ nodes.add(refNode);
3307
+ }
3308
+ refNode = walker.nextNode();
3309
+ }
3310
+ }
3311
+ return nodes;
3312
+ }
3313
+ /**
3314
+ * match combinator
3315
+ * @private
3316
+ * @param {object} twig - twig
3317
+ * @param {object} node - Element node
3318
+ * @param {object} [opt] - option
3319
+ * @returns {Set.<object>} - collection of matched nodes
3320
+ */
3321
+ _matchCombinator(twig, node, opt = {}) {
3322
+ const { combo, leaves } = twig;
3323
+ const { name: comboName } = combo;
3324
+ const { parentNode } = node;
3325
+ const { dir } = opt;
3326
+ const matched = /* @__PURE__ */ new Set();
3327
+ if (dir === DIR_NEXT) {
3328
+ switch (comboName) {
3329
+ case "+": {
3330
+ const refNode = node.nextElementSibling;
3331
+ if (refNode) {
3332
+ const bool = this._matchLeaves(leaves, refNode, opt);
3333
+ if (bool) {
3334
+ matched.add(refNode);
3335
+ }
3336
+ }
3337
+ break;
3338
+ }
3339
+ case "~": {
3340
+ if (parentNode) {
3341
+ let refNode = node.nextElementSibling;
3342
+ while (refNode) {
3343
+ const bool = this._matchLeaves(leaves, refNode, opt);
3344
+ if (bool) {
3345
+ matched.add(refNode);
3346
+ }
3347
+ refNode = refNode.nextElementSibling;
3348
+ }
3349
+ }
3350
+ break;
3351
+ }
3352
+ case ">": {
3353
+ let refNode = node.firstElementChild;
3354
+ while (refNode) {
3355
+ const bool = this._matchLeaves(leaves, refNode, opt);
3356
+ if (bool) {
3357
+ matched.add(refNode);
3358
+ }
3359
+ refNode = refNode.nextElementSibling;
3360
+ }
3361
+ break;
3362
+ }
3363
+ case " ":
3364
+ default: {
3365
+ const nodes = this._findDescendantNodes(leaves, node, opt);
3366
+ if (nodes.size) {
3367
+ return nodes;
3368
+ }
3369
+ }
3370
+ }
3371
+ } else {
3372
+ switch (comboName) {
3373
+ case "+": {
3374
+ const refNode = node.previousElementSibling;
3375
+ if (refNode) {
3376
+ const bool = this._matchLeaves(leaves, refNode, opt);
3377
+ if (bool) {
3378
+ matched.add(refNode);
3379
+ }
3380
+ }
3381
+ break;
3382
+ }
3383
+ case "~": {
3384
+ if (parentNode) {
3385
+ let refNode = parentNode.firstElementChild;
3386
+ while (refNode) {
3387
+ if (refNode === node) {
3388
+ break;
3389
+ } else {
3390
+ const bool = this._matchLeaves(leaves, refNode, opt);
3391
+ if (bool) {
3392
+ matched.add(refNode);
3393
+ }
3394
+ }
3395
+ refNode = refNode.nextElementSibling;
3396
+ }
3397
+ }
3398
+ break;
3399
+ }
3400
+ case ">": {
3401
+ if (parentNode) {
3402
+ const bool = this._matchLeaves(leaves, parentNode, opt);
3403
+ if (bool) {
3404
+ matched.add(parentNode);
3405
+ }
3406
+ }
3407
+ break;
3408
+ }
3409
+ case " ":
3410
+ default: {
3411
+ const arr = [];
3412
+ let refNode = parentNode;
3413
+ while (refNode) {
3414
+ const bool = this._matchLeaves(leaves, refNode, opt);
3415
+ if (bool) {
3416
+ arr.push(refNode);
3417
+ }
3418
+ refNode = refNode.parentNode;
3419
+ }
3420
+ if (arr.length) {
3421
+ return new Set(arr.reverse());
3422
+ }
3423
+ }
3424
+ }
3425
+ }
3426
+ return matched;
3427
+ }
3428
+ /**
3429
+ * find matched node(s) from #qswalker
3430
+ * @private
3431
+ * @param {Array.<object>} leaves - AST leaves
3432
+ * @param {object} node - node to start from
3433
+ * @param {object} opt - options
3434
+ * @param {boolean} [opt.force] - traverse only to next node
3435
+ * @param {string} [opt.targetType] - target type
3436
+ * @returns {Array.<object>} - collection of matched nodes
3437
+ */
3438
+ _findQswalker(leaves, node, opt = {}) {
3439
+ const { force, targetType } = opt;
3440
+ const walker = this.#qswalker;
3441
+ const nodes = [];
3442
+ let refNode = traverseNode(node, walker, !!force);
3443
+ if (refNode) {
3444
+ if (refNode.nodeType !== ELEMENT_NODE) {
3445
+ refNode = walker.nextNode();
3446
+ } else if (refNode === node) {
3447
+ if (refNode !== this.#root) {
3448
+ refNode = walker.nextNode();
3449
+ }
3450
+ }
3451
+ while (refNode) {
3452
+ const matched = this._matchLeaves(leaves, refNode, {
3453
+ warn: this.#warn
3454
+ });
3455
+ if (matched) {
3456
+ nodes.push(refNode);
3457
+ if (targetType !== TARGET_ALL) {
3458
+ break;
3459
+ }
3460
+ }
3461
+ refNode = walker.nextNode();
3462
+ }
3463
+ }
3464
+ return nodes;
3465
+ }
3466
+ /**
3467
+ * match self
3468
+ * @private
3469
+ * @param {Array} leaves - AST leaves
3470
+ * @returns {Array} - [nodes, filtered]
3471
+ */
3472
+ _matchSelf(leaves) {
3473
+ const nodes = [];
3474
+ let filtered = false;
3475
+ const bool = this._matchLeaves(leaves, this.#node, {
3476
+ warn: this.#warn
3477
+ });
3478
+ if (bool) {
3479
+ nodes.push(this.#node);
3480
+ filtered = true;
3481
+ }
3482
+ return [nodes, filtered];
3483
+ }
3484
+ /**
3485
+ * find lineal
3486
+ * @private
3487
+ * @param {Array} leaves - AST leaves
3488
+ * @param {object} opt - options
3489
+ * @returns {Array} - [nodes, filtered]
3490
+ */
3491
+ _findLineal(leaves, opt) {
3492
+ const { complex } = opt;
3493
+ const nodes = [];
3494
+ let filtered = false;
3495
+ let bool = this._matchLeaves(leaves, this.#node, {
3496
+ warn: this.#warn
3497
+ });
3498
+ if (bool) {
3499
+ nodes.push(this.#node);
3500
+ filtered = true;
3501
+ }
3502
+ if (!bool || complex) {
3503
+ let refNode = this.#node.parentNode;
3504
+ while (refNode) {
3505
+ bool = this._matchLeaves(leaves, refNode, {
3506
+ warn: this.#warn
3507
+ });
3508
+ if (bool) {
3509
+ nodes.push(refNode);
3510
+ filtered = true;
3511
+ }
3512
+ if (refNode.parentNode) {
3513
+ refNode = refNode.parentNode;
3514
+ } else {
3515
+ break;
3516
+ }
3517
+ }
3518
+ }
3519
+ return [nodes, filtered];
3520
+ }
3521
+ /**
3522
+ * find entry nodes
3523
+ * @private
3524
+ * @param {object} twig - twig
3525
+ * @param {string} targetType - target type
3526
+ * @param {boolean} complex - complex selector
3527
+ * @returns {object} - nodes and info about it's state.
3528
+ */
3529
+ _findEntryNodes(twig, targetType, complex) {
3530
+ const { leaves } = twig;
3531
+ const [leaf, ...filterLeaves] = leaves;
3532
+ const compound = filterLeaves.length > 0;
3533
+ const { name: leafName, type: leafType } = leaf;
3534
+ let nodes = [];
3535
+ let filtered = false;
3536
+ let pending = false;
3537
+ switch (leafType) {
3538
+ case PS_ELEMENT_SELECTOR: {
3539
+ if (targetType === TARGET_SELF && this.#check) {
3540
+ const css = (0, import_css_tree3.generate)(leaf);
3541
+ this.#pseudoElement.push(css);
3542
+ if (filterLeaves.length) {
3543
+ [nodes, filtered] = this._matchSelf(filterLeaves);
3544
+ } else {
3545
+ nodes.push(this.#node);
3546
+ filtered = true;
3547
+ }
3548
+ } else {
3549
+ matchPseudoElementSelector(leafName, leafType, {
3550
+ warn: this.#warn
3551
+ });
3552
+ }
3553
+ break;
3554
+ }
3555
+ case ID_SELECTOR: {
3556
+ if (targetType === TARGET_SELF) {
3557
+ [nodes, filtered] = this._matchSelf(leaves);
3558
+ } else if (targetType === TARGET_LINEAL) {
3559
+ [nodes, filtered] = this._findLineal(leaves, {
3560
+ complex
3561
+ });
3562
+ } else if (targetType === TARGET_FIRST && this.#root.nodeType !== ELEMENT_NODE) {
3563
+ const node = this.#root.getElementById(leafName);
3564
+ if (node) {
3565
+ if (compound) {
3566
+ const bool = this._matchLeaves(filterLeaves, node, {
3567
+ warn: this.#warn
3568
+ });
3569
+ if (bool) {
3570
+ nodes.push(node);
3571
+ filtered = true;
3572
+ }
3573
+ } else {
3574
+ nodes.push(node);
3575
+ filtered = true;
3576
+ }
3577
+ }
3578
+ } else {
3579
+ nodes = this._findQswalker(leaves, this.#node, {
3580
+ targetType
3581
+ });
3582
+ if (nodes.length) {
3583
+ filtered = true;
3584
+ }
3585
+ }
3586
+ break;
3587
+ }
3588
+ case CLASS_SELECTOR: {
3589
+ if (targetType === TARGET_SELF) {
3590
+ [nodes, filtered] = this._matchSelf(leaves);
3591
+ } else if (targetType === TARGET_LINEAL) {
3592
+ [nodes, filtered] = this._findLineal(leaves, {
3593
+ complex
3594
+ });
3595
+ } else {
3596
+ nodes = this._findQswalker(leaves, this.#node, {
3597
+ targetType
3598
+ });
3599
+ if (nodes.length) {
3600
+ filtered = true;
3601
+ }
3602
+ }
3603
+ break;
3604
+ }
3605
+ case TYPE_SELECTOR: {
3606
+ if (targetType === TARGET_SELF) {
3607
+ [nodes, filtered] = this._matchSelf(leaves);
3608
+ } else if (targetType === TARGET_LINEAL) {
3609
+ [nodes, filtered] = this._findLineal(leaves, {
3610
+ complex
3611
+ });
3612
+ } else {
3613
+ nodes = this._findQswalker(leaves, this.#node, {
3614
+ targetType
3615
+ });
3616
+ if (nodes.length) {
3617
+ filtered = true;
3618
+ }
3619
+ }
3620
+ break;
3621
+ }
3622
+ default: {
3623
+ if (targetType !== TARGET_LINEAL && (leafName === "host" || leafName === "host-context")) {
3624
+ let shadowRoot;
3625
+ if (this.#shadow && this.#node.nodeType === DOCUMENT_FRAGMENT_NODE) {
3626
+ shadowRoot = this._matchShadowHostPseudoClass(leaf, this.#node);
3627
+ } else if (compound && this.#node.nodeType === ELEMENT_NODE) {
3628
+ shadowRoot = this._matchShadowHostPseudoClass(leaf, this.#node.shadowRoot);
3629
+ }
3630
+ if (shadowRoot) {
3631
+ let bool;
3632
+ if (compound) {
3633
+ for (const item of filterLeaves) {
3634
+ if (/^host(?:-context)?$/.test(item.name)) {
3635
+ const node = this._matchShadowHostPseudoClass(item, shadowRoot);
3636
+ bool = node === shadowRoot;
3637
+ } else if (item.name === "has") {
3638
+ bool = this._matchPseudoClassSelector(item, shadowRoot, {}).has(shadowRoot);
3639
+ } else {
3640
+ bool = false;
3641
+ }
3642
+ if (!bool) {
3643
+ break;
3644
+ }
3645
+ }
3646
+ } else {
3647
+ bool = true;
3648
+ }
3649
+ if (bool) {
3650
+ nodes.push(shadowRoot);
3651
+ filtered = true;
3652
+ }
3653
+ }
3654
+ } else if (targetType === TARGET_SELF) {
3655
+ [nodes, filtered] = this._matchSelf(leaves);
3656
+ } else if (targetType === TARGET_LINEAL) {
3657
+ [nodes, filtered] = this._findLineal(leaves, {
3658
+ complex
3659
+ });
3660
+ } else if (targetType === TARGET_FIRST) {
3661
+ nodes = this._findQswalker(leaves, this.#node, {
3662
+ targetType
3663
+ });
3664
+ if (nodes.length) {
3665
+ filtered = true;
3666
+ }
3667
+ } else {
3668
+ pending = true;
3669
+ }
3670
+ }
3671
+ }
3672
+ return {
3673
+ compound,
3674
+ filtered,
3675
+ nodes,
3676
+ pending
3677
+ };
3678
+ }
3679
+ /**
3680
+ * collect nodes
3681
+ * @private
3682
+ * @param {string} targetType - target type
3683
+ * @returns {Array.<Array.<object>>} - #ast and #nodes
3684
+ */
3685
+ _collectNodes(targetType) {
3686
+ const ast = this.#ast.values();
3687
+ if (targetType === TARGET_ALL || targetType === TARGET_FIRST) {
3688
+ const pendingItems = /* @__PURE__ */ new Set();
3689
+ let i = 0;
3690
+ for (const { branch } of ast) {
3691
+ const branchLen = branch.length;
3692
+ const complex = branchLen > 1;
3693
+ const firstTwig = branch[0];
3694
+ let dir;
3695
+ let twig;
3696
+ if (complex) {
3697
+ const {
3698
+ combo: firstCombo,
3699
+ leaves: [{
3700
+ name: firstName,
3701
+ type: firstType
3702
+ }]
3703
+ } = firstTwig;
3704
+ const lastTwig = branch[branchLen - 1];
3705
+ const {
3706
+ leaves: [{
3707
+ name: lastName,
3708
+ type: lastType
3709
+ }]
3710
+ } = lastTwig;
3711
+ dir = DIR_NEXT;
3712
+ twig = firstTwig;
3713
+ if (this.#selector.includes(":scope") || lastType === PS_ELEMENT_SELECTOR || lastType === ID_SELECTOR) {
3714
+ dir = DIR_PREV;
3715
+ twig = lastTwig;
3716
+ } else if (firstName === "*" && firstType === TYPE_SELECTOR) {
3717
+ dir = DIR_PREV;
3718
+ twig = lastTwig;
3719
+ } else if (lastName === "*" && lastType === TYPE_SELECTOR) {
3720
+ dir = DIR_NEXT;
3721
+ twig = firstTwig;
3722
+ } else if (branchLen === 2) {
3723
+ const { name: comboName } = firstCombo;
3724
+ if (comboName === "+" || comboName === "~") {
3725
+ dir = DIR_PREV;
3726
+ twig = lastTwig;
3727
+ }
3728
+ }
3729
+ } else {
3730
+ dir = DIR_PREV;
3731
+ twig = firstTwig;
3732
+ }
3733
+ const {
3734
+ compound,
3735
+ filtered,
3736
+ nodes,
3737
+ pending
3738
+ } = this._findEntryNodes(twig, targetType, complex);
3739
+ if (nodes.length) {
3740
+ this.#ast[i].find = true;
3741
+ this.#nodes[i] = nodes;
3742
+ } else if (pending) {
3743
+ pendingItems.add(/* @__PURE__ */ new Map([
3744
+ ["index", i],
3745
+ ["twig", twig]
3746
+ ]));
3747
+ }
3748
+ this.#ast[i].dir = dir;
3749
+ this.#ast[i].filtered = filtered || !compound;
3750
+ i++;
3751
+ }
3752
+ if (pendingItems.size) {
3753
+ let node;
3754
+ let walker;
3755
+ if (this.#node !== this.#root && this.#node.nodeType === ELEMENT_NODE) {
3756
+ node = this.#node;
3757
+ walker = this.#qswalker;
3758
+ } else {
3759
+ node = this.#root;
3760
+ walker = this._createTreeWalker(node);
3761
+ }
3762
+ let nextNode = traverseNode(node, walker);
3763
+ while (nextNode) {
3764
+ let bool = false;
3765
+ if (this.#node.nodeType === ELEMENT_NODE) {
3766
+ if (nextNode === this.#node) {
3767
+ bool = true;
3768
+ } else {
3769
+ bool = this.#node.contains(nextNode);
3770
+ }
3771
+ } else {
3772
+ bool = true;
3773
+ }
3774
+ if (bool) {
3775
+ for (const pendingItem of pendingItems) {
3776
+ const { leaves } = pendingItem.get("twig");
3777
+ const matched = this._matchLeaves(leaves, nextNode, {
3778
+ warn: this.#warn
3779
+ });
3780
+ if (matched) {
3781
+ const index = pendingItem.get("index");
3782
+ this.#ast[index].filtered = true;
3783
+ this.#ast[index].find = true;
3784
+ this.#nodes[index].push(nextNode);
3785
+ }
3786
+ }
3787
+ }
3788
+ if (nextNode !== walker.currentNode) {
3789
+ nextNode = traverseNode(nextNode, walker);
3790
+ }
3791
+ nextNode = walker.nextNode();
3792
+ }
3793
+ }
3794
+ } else {
3795
+ let i = 0;
3796
+ for (const { branch } of ast) {
3797
+ const twig = branch[branch.length - 1];
3798
+ const complex = branch.length > 1;
3799
+ const {
3800
+ compound,
3801
+ filtered,
3802
+ nodes
3803
+ } = this._findEntryNodes(twig, targetType, complex);
3804
+ if (nodes.length) {
3805
+ this.#ast[i].find = true;
3806
+ this.#nodes[i] = nodes;
3807
+ }
3808
+ this.#ast[i].dir = DIR_PREV;
3809
+ this.#ast[i].filtered = filtered || !compound;
3810
+ i++;
3811
+ }
3812
+ }
3813
+ return [
3814
+ this.#ast,
3815
+ this.#nodes
3816
+ ];
3817
+ }
3818
+ /**
3819
+ * get combined nodes
3820
+ * @private
3821
+ * @param {object} twig - twig
3822
+ * @param {object} nodes - collection of nodes
3823
+ * @param {string} dir - direction
3824
+ * @returns {Set.<object>} - collection of matched nodes
3825
+ */
3826
+ _getCombinedNodes(twig, nodes, dir) {
3827
+ const arr = [];
3828
+ for (const node of nodes) {
3829
+ const matched = this._matchCombinator(twig, node, {
3830
+ dir,
3831
+ warn: this.#warn
3832
+ });
3833
+ if (matched.size) {
3834
+ arr.push(...matched);
3835
+ }
3836
+ }
3837
+ if (arr.length) {
3838
+ return new Set(arr);
3839
+ }
3840
+ return /* @__PURE__ */ new Set();
3841
+ }
3842
+ /**
3843
+ * match node to next direction
3844
+ * @private
3845
+ * @param {Array} branch - branch
3846
+ * @param {Set.<object>} nodes - collection of Element node
3847
+ * @param {object} opt - option
3848
+ * @param {object} opt.combo - combo
3849
+ * @param {number} opt.index - index
3850
+ * @returns {?object} - matched node
3851
+ */
3852
+ _matchNodeNext(branch, nodes, opt) {
3853
+ const { combo, index } = opt;
3854
+ const { combo: nextCombo, leaves } = branch[index];
3855
+ const twig = {
3856
+ combo,
3857
+ leaves
3858
+ };
3859
+ const nextNodes = this._getCombinedNodes(twig, nodes, DIR_NEXT);
3860
+ if (nextNodes.size) {
3861
+ if (index === branch.length - 1) {
3862
+ const [nextNode] = sortNodes(nextNodes);
3863
+ return nextNode;
3864
+ } else {
3865
+ return this._matchNodeNext(branch, nextNodes, {
3866
+ combo: nextCombo,
3867
+ index: index + 1
3868
+ });
3869
+ }
3870
+ }
3871
+ return null;
3872
+ }
3873
+ /**
3874
+ * match node to previous direction
3875
+ * @private
3876
+ * @param {Array} branch - branch
3877
+ * @param {object} node - Element node
3878
+ * @param {object} opt - option
3879
+ * @param {number} opt.index - index
3880
+ * @returns {?object} - node
3881
+ */
3882
+ _matchNodePrev(branch, node, opt) {
3883
+ const { index } = opt;
3884
+ const twig = branch[index];
3885
+ const nodes = /* @__PURE__ */ new Set([node]);
3886
+ const nextNodes = this._getCombinedNodes(twig, nodes, DIR_PREV);
3887
+ if (nextNodes.size) {
3888
+ if (index === 0) {
3889
+ return node;
3890
+ } else {
3891
+ let matched;
3892
+ for (const nextNode of nextNodes) {
3893
+ matched = this._matchNodePrev(branch, nextNode, {
3894
+ index: index - 1
3895
+ });
3896
+ if (matched) {
3897
+ break;
3898
+ }
3899
+ }
3900
+ if (matched) {
3901
+ return node;
3902
+ }
3903
+ }
3904
+ }
3905
+ return null;
3906
+ }
3907
+ /**
3908
+ * find matched nodes
3909
+ * @param {string} targetType - target type
3910
+ * @returns {Set.<object>} - collection of matched nodes
3911
+ */
3912
+ find(targetType) {
3913
+ if (targetType === TARGET_ALL || targetType === TARGET_FIRST) {
3914
+ this._prepareQuerySelectorWalker();
3915
+ }
3916
+ const [[...branches], collectedNodes] = this._collectNodes(targetType);
3917
+ const l = branches.length;
3918
+ let sort;
3919
+ let nodes = /* @__PURE__ */ new Set();
3920
+ for (let i = 0; i < l; i++) {
3921
+ const { branch, dir, find: find2 } = branches[i];
3922
+ const branchLen = branch.length;
3923
+ if (branchLen && find2) {
3924
+ const entryNodes = collectedNodes[i];
3925
+ const entryNodesLen = entryNodes.length;
3926
+ const lastIndex = branchLen - 1;
3927
+ if (lastIndex === 0) {
3928
+ if ((targetType === TARGET_ALL || targetType === TARGET_FIRST) && this.#node.nodeType === ELEMENT_NODE) {
3929
+ for (let j = 0; j < entryNodesLen; j++) {
3930
+ const node = entryNodes[j];
3931
+ if (node !== this.#node && this.#node.contains(node)) {
3932
+ nodes.add(node);
3933
+ if (targetType === TARGET_FIRST) {
3934
+ break;
3935
+ }
3936
+ }
3937
+ }
3938
+ } else if (targetType === TARGET_ALL) {
3939
+ if (nodes.size) {
3940
+ const n = [...nodes];
3941
+ nodes = /* @__PURE__ */ new Set([...n, ...entryNodes]);
3942
+ sort = true;
3943
+ } else {
3944
+ nodes = new Set(entryNodes);
3945
+ }
3946
+ } else {
3947
+ const [node] = entryNodes;
3948
+ nodes.add(node);
3949
+ }
3950
+ } else if (targetType === TARGET_ALL) {
3951
+ if (dir === DIR_NEXT) {
3952
+ const { combo: firstCombo } = branch[0];
3953
+ let combo = firstCombo;
3954
+ for (const node of entryNodes) {
3955
+ let nextNodes = /* @__PURE__ */ new Set([node]);
3956
+ for (let j = 1; j < branchLen; j++) {
3957
+ const { combo: nextCombo, leaves } = branch[j];
3958
+ const twig = {
3959
+ combo,
3960
+ leaves
3961
+ };
3962
+ nextNodes = this._getCombinedNodes(twig, nextNodes, dir);
3963
+ if (nextNodes.size) {
3964
+ if (j === lastIndex) {
3965
+ if (nodes.size) {
3966
+ const n = [...nodes];
3967
+ nodes = /* @__PURE__ */ new Set([...n, ...nextNodes]);
3968
+ sort = true;
3969
+ combo = firstCombo;
3970
+ } else {
3971
+ nodes = nextNodes;
3972
+ combo = firstCombo;
3973
+ }
3974
+ } else {
3975
+ combo = nextCombo;
3976
+ }
3977
+ } else {
3978
+ break;
3979
+ }
3980
+ }
3981
+ }
3982
+ } else {
3983
+ for (const node of entryNodes) {
3984
+ let nextNodes = /* @__PURE__ */ new Set([node]);
3985
+ for (let j = lastIndex - 1; j >= 0; j--) {
3986
+ const twig = branch[j];
3987
+ nextNodes = this._getCombinedNodes(twig, nextNodes, dir);
3988
+ if (nextNodes.size) {
3989
+ if (j === 0) {
3990
+ nodes.add(node);
3991
+ if (branchLen > 1 && nodes.size > 1) {
3992
+ sort = true;
3993
+ }
3994
+ }
3995
+ } else {
3996
+ break;
3997
+ }
3998
+ }
3999
+ }
4000
+ }
4001
+ } else if (targetType === TARGET_FIRST && dir === DIR_NEXT) {
4002
+ const { combo: entryCombo } = branch[0];
4003
+ let matched;
4004
+ for (const node of entryNodes) {
4005
+ matched = this._matchNodeNext(branch, /* @__PURE__ */ new Set([node]), {
4006
+ combo: entryCombo,
4007
+ index: 1
4008
+ });
4009
+ if (matched) {
4010
+ nodes.add(matched);
4011
+ break;
4012
+ }
4013
+ }
4014
+ if (!matched) {
4015
+ const { leaves: entryLeaves } = branch[0];
4016
+ const [entryNode] = entryNodes;
4017
+ let [refNode] = this._findQswalker(entryLeaves, entryNode, {
4018
+ targetType
4019
+ });
4020
+ while (refNode) {
4021
+ matched = this._matchNodeNext(branch, /* @__PURE__ */ new Set([refNode]), {
4022
+ combo: entryCombo,
4023
+ index: 1
4024
+ });
4025
+ if (matched) {
4026
+ nodes.add(matched);
4027
+ break;
4028
+ }
4029
+ [refNode] = this._findQswalker(entryLeaves, refNode, {
4030
+ targetType,
4031
+ force: true
4032
+ });
4033
+ }
4034
+ }
4035
+ } else {
4036
+ let matched;
4037
+ for (const node of entryNodes) {
4038
+ matched = this._matchNodePrev(branch, node, {
4039
+ index: lastIndex - 1
4040
+ });
4041
+ if (matched) {
4042
+ nodes.add(node);
4043
+ break;
4044
+ }
4045
+ }
4046
+ if (!matched && targetType === TARGET_FIRST) {
4047
+ const { leaves: entryLeaves } = branch[lastIndex];
4048
+ const [entryNode] = entryNodes;
4049
+ let [refNode] = this._findQswalker(entryLeaves, entryNode, {
4050
+ targetType
4051
+ });
4052
+ while (refNode) {
4053
+ matched = this._matchNodePrev(branch, refNode, {
4054
+ index: lastIndex - 1
4055
+ });
4056
+ if (matched) {
4057
+ nodes.add(refNode);
4058
+ break;
4059
+ }
4060
+ [refNode] = this._findQswalker(entryLeaves, refNode, {
4061
+ targetType,
4062
+ force: true
4063
+ });
4064
+ }
4065
+ }
4066
+ }
4067
+ }
4068
+ }
4069
+ if (this.#check) {
4070
+ const match = !!nodes.size;
4071
+ let pseudoElement;
4072
+ if (this.#pseudoElement.length) {
4073
+ pseudoElement = this.#pseudoElement.join("");
4074
+ } else {
4075
+ pseudoElement = null;
4076
+ }
4077
+ return {
4078
+ match,
4079
+ pseudoElement
4080
+ };
4081
+ }
4082
+ if (targetType === TARGET_FIRST) {
4083
+ nodes.delete(this.#node);
4084
+ if (nodes.size > 1) {
4085
+ nodes = new Set(sortNodes(nodes));
4086
+ }
4087
+ } else if (targetType === TARGET_ALL) {
4088
+ nodes.delete(this.#node);
4089
+ if (sort && nodes.size > 1) {
4090
+ nodes = new Set(sortNodes(nodes));
4091
+ }
4092
+ }
4093
+ return nodes;
4094
+ }
4095
+ };
4096
+
4097
+ // src/index.js
4098
+ var REG_COMPLEX = new RegExp(`${COMPOUND_I}${COMBO}${COMPOUND_I}`, "i");
4099
+ var REG_DESCEND = new RegExp(`${COMPOUND_I}${DESCEND}${COMPOUND_I}`, "i");
4100
+ var REG_SIMPLE = new RegExp(`^${TAG_ID_CLASS}$`);
4101
+ var DOMSelector = class {
4102
+ /* private fields */
4103
+ #window;
4104
+ #document;
4105
+ #domSymbolTree;
4106
+ #finder;
4107
+ #idlUtils;
4108
+ #nwsapi;
4109
+ /**
4110
+ * construct
4111
+ * @param {object} window - window
4112
+ * @param {object} document - document
4113
+ * @param {object} [opt] - options
4114
+ */
4115
+ constructor(window, document, opt = {}) {
4116
+ const { domSymbolTree, idlUtils } = opt;
4117
+ this.#window = window;
4118
+ this.#document = document ?? window.document;
4119
+ this.#finder = new Finder(window);
4120
+ this.#nwsapi = initNwsapi(window, document);
4121
+ this.#domSymbolTree = domSymbolTree;
4122
+ this.#idlUtils = idlUtils;
4123
+ }
4124
+ /**
4125
+ * check
4126
+ * @param {string} selector - CSS selector
4127
+ * @param {object} node - Element node
4128
+ * @param {object} opt - options
4129
+ * @returns {object} - check result
4130
+ */
4131
+ check(selector, node, opt = {}) {
4132
+ if (!node?.nodeType) {
4133
+ const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);
4134
+ this.#finder.onError(e, opt);
4135
+ } else if (node.nodeType !== ELEMENT_NODE) {
4136
+ const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`);
4137
+ this.#finder.onError(e, opt);
4138
+ }
4139
+ const document = this.#domSymbolTree ? node._ownerDocument : node.ownerDocument;
4140
+ if (document === this.#document && document.contentType === "text/html" && node.parentNode) {
4141
+ const filterOpt = {
4142
+ complex: REG_COMPLEX.test(selector),
4143
+ compound: false,
4144
+ descend: false,
4145
+ simple: false,
4146
+ target: TARGET_SELF
4147
+ };
4148
+ if (filterSelector(selector, filterOpt)) {
4149
+ try {
4150
+ if (this.#idlUtils) {
4151
+ node = this.#idlUtils.wrapperForImpl(node);
4152
+ }
4153
+ const match = this.#nwsapi.match(selector, node);
4154
+ return {
4155
+ match,
4156
+ pseudoElement: null
4157
+ };
4158
+ } catch (e) {
4159
+ }
4160
+ }
4161
+ }
4162
+ let res;
4163
+ try {
4164
+ if (this.#idlUtils) {
4165
+ node = this.#idlUtils.wrapperForImpl(node);
4166
+ }
4167
+ opt.check = true;
4168
+ opt.domSymbolTree = this.#domSymbolTree;
4169
+ opt.noexept = true;
4170
+ opt.warn = false;
4171
+ this.#finder.setup(selector, node, opt);
4172
+ res = this.#finder.find(TARGET_SELF);
4173
+ } catch (e) {
4174
+ this.#finder.onError(e, opt);
4175
+ }
4176
+ return res;
4177
+ }
4178
+ /**
4179
+ * matches
4180
+ * @param {string} selector - CSS selector
4181
+ * @param {object} node - Element node
4182
+ * @param {object} opt - options
4183
+ * @returns {boolean} - `true` if matched `false` otherwise
4184
+ */
4185
+ matches(selector, node, opt) {
4186
+ if (!node?.nodeType) {
4187
+ const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);
4188
+ this.#finder.onError(e, opt);
4189
+ } else if (node.nodeType !== ELEMENT_NODE) {
4190
+ const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`);
4191
+ this.#finder.onError(e, opt);
4192
+ }
4193
+ const document = this.#domSymbolTree ? node._ownerDocument : node.ownerDocument;
4194
+ if (document === this.#document && document.contentType === "text/html" && node.parentNode) {
4195
+ const filterOpt = {
4196
+ complex: REG_COMPLEX.test(selector),
4197
+ compound: false,
4198
+ descend: false,
4199
+ simple: false,
4200
+ target: TARGET_SELF
4201
+ };
4202
+ if (filterSelector(selector, filterOpt)) {
4203
+ try {
4204
+ if (this.#idlUtils) {
4205
+ node = this.#idlUtils.wrapperForImpl(node);
4206
+ }
4207
+ const res2 = this.#nwsapi.match(selector, node);
4208
+ return res2;
4209
+ } catch (e) {
4210
+ }
4211
+ }
4212
+ }
4213
+ let res;
4214
+ try {
4215
+ if (this.#idlUtils) {
4216
+ node = this.#idlUtils.wrapperForImpl(node);
4217
+ }
4218
+ this.#finder.setup(selector, node, opt);
4219
+ const nodes = this.#finder.find(TARGET_SELF);
4220
+ res = nodes.size;
4221
+ } catch (e) {
4222
+ this.#finder.onError(e, opt);
4223
+ }
4224
+ return !!res;
4225
+ }
4226
+ /**
4227
+ * closest
4228
+ * @param {string} selector - CSS selector
4229
+ * @param {object} node - Element node
4230
+ * @param {object} opt - options
4231
+ * @returns {?object} - matched node
4232
+ */
4233
+ closest(selector, node, opt) {
4234
+ if (!node?.nodeType) {
4235
+ const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);
4236
+ this.#finder.onError(e, opt);
4237
+ } else if (node.nodeType !== ELEMENT_NODE) {
4238
+ const e = new this.#window.TypeError(`Unexpected node ${node.nodeName}`);
4239
+ this.#finder.onError(e, opt);
4240
+ }
4241
+ const document = this.#domSymbolTree ? node._ownerDocument : node.ownerDocument;
4242
+ if (document === this.#document && document.contentType === "text/html" && node.parentNode) {
4243
+ const filterOpt = {
4244
+ complex: REG_COMPLEX.test(selector),
4245
+ compound: false,
4246
+ descend: false,
4247
+ simple: false,
4248
+ target: TARGET_LINEAL
4249
+ };
4250
+ if (filterSelector(selector, filterOpt)) {
4251
+ try {
4252
+ if (this.#idlUtils) {
4253
+ node = this.#idlUtils.wrapperForImpl(node);
4254
+ }
4255
+ const res2 = this.#nwsapi.closest(selector, node);
4256
+ return res2;
4257
+ } catch (e) {
4258
+ }
4259
+ }
4260
+ }
4261
+ let res;
4262
+ try {
4263
+ if (this.#idlUtils) {
4264
+ node = this.#idlUtils.wrapperForImpl(node);
4265
+ }
4266
+ this.#finder.setup(selector, node, opt);
4267
+ const nodes = this.#finder.find(TARGET_LINEAL);
4268
+ if (nodes.size) {
4269
+ let refNode = node;
4270
+ while (refNode) {
4271
+ if (nodes.has(refNode)) {
4272
+ res = refNode;
4273
+ break;
4274
+ }
4275
+ refNode = refNode.parentNode;
4276
+ }
4277
+ }
4278
+ } catch (e) {
4279
+ this.#finder.onError(e, opt);
4280
+ }
4281
+ return res ?? null;
4282
+ }
4283
+ /**
4284
+ * query selector
4285
+ * @param {string} selector - CSS selector
4286
+ * @param {object} node - Document, DocumentFragment, Element node
4287
+ * @param {object} opt - options
4288
+ * @returns {?object} - matched node
4289
+ */
4290
+ querySelector(selector, node, opt) {
4291
+ if (!node?.nodeType) {
4292
+ const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);
4293
+ this.#finder.onError(e, opt);
4294
+ }
4295
+ let document;
4296
+ if (this.#domSymbolTree) {
4297
+ document = node._ownerDocument;
4298
+ } else if (node.nodeType === DOCUMENT_NODE) {
4299
+ document = node;
4300
+ } else {
4301
+ document = node.ownerDocument;
4302
+ }
4303
+ if (document === this.#document && document.contentType === "text/html") {
4304
+ const filterOpt = {
4305
+ complex: false,
4306
+ compound: !(REG_SIMPLE.test(selector) || REG_COMPLEX.test(selector)),
4307
+ descend: REG_DESCEND.test(selector),
4308
+ simple: REG_SIMPLE.test(selector),
4309
+ target: TARGET_FIRST
4310
+ };
4311
+ if (filterSelector(selector, filterOpt)) {
4312
+ try {
4313
+ if (this.#idlUtils) {
4314
+ node = this.#idlUtils.wrapperForImpl(node);
4315
+ }
4316
+ const res2 = this.#nwsapi.first(selector, node);
4317
+ return res2;
4318
+ } catch (e) {
4319
+ }
4320
+ }
4321
+ }
4322
+ let res;
4323
+ try {
4324
+ if (this.#idlUtils) {
4325
+ node = this.#idlUtils.wrapperForImpl(node);
4326
+ }
4327
+ this.#finder.setup(selector, node, opt);
4328
+ const nodes = this.#finder.find(TARGET_FIRST);
4329
+ if (nodes.size) {
4330
+ [res] = nodes;
4331
+ }
4332
+ } catch (e) {
4333
+ this.#finder.onError(e, opt);
4334
+ }
4335
+ return res ?? null;
4336
+ }
4337
+ /**
4338
+ * query selector all
4339
+ * NOTE: returns Array, not NodeList
4340
+ * @param {string} selector - CSS selector
4341
+ * @param {object} node - Document, DocumentFragment, Element node
4342
+ * @param {object} opt - options
4343
+ * @returns {Array.<object|undefined>} - collection of matched nodes
4344
+ */
4345
+ querySelectorAll(selector, node, opt) {
4346
+ if (!node?.nodeType) {
4347
+ const e = new this.#window.TypeError(`Unexpected type ${getType(node)}`);
4348
+ this.#finder.onError(e, opt);
4349
+ }
4350
+ let document;
4351
+ if (this.#domSymbolTree) {
4352
+ document = node._ownerDocument;
4353
+ } else if (node.nodeType === DOCUMENT_NODE) {
4354
+ document = node;
4355
+ } else {
4356
+ document = node.ownerDocument;
4357
+ }
4358
+ if (document === this.#document && document.contentType === "text/html") {
4359
+ const filterOpt = {
4360
+ complex: false,
4361
+ compound: false,
4362
+ descend: REG_DESCEND.test(selector),
4363
+ simple: false,
4364
+ target: TARGET_ALL
4365
+ };
4366
+ if (filterSelector(selector, filterOpt)) {
4367
+ try {
4368
+ if (this.#idlUtils) {
4369
+ node = this.#idlUtils.wrapperForImpl(node);
4370
+ }
4371
+ const res2 = this.#nwsapi.select(selector, node);
4372
+ return res2;
4373
+ } catch (e) {
4374
+ }
4375
+ }
4376
+ }
4377
+ let res;
4378
+ try {
4379
+ if (this.#idlUtils) {
4380
+ node = this.#idlUtils.wrapperForImpl(node);
4381
+ }
4382
+ this.#finder.setup(selector, node, opt);
4383
+ const nodes = this.#finder.find(TARGET_ALL);
4384
+ if (nodes.size) {
4385
+ res = [...nodes];
4386
+ }
4387
+ } catch (e) {
4388
+ this.#finder.onError(e, opt);
4389
+ }
4390
+ return res ?? [];
4391
+ }
4392
+ };
4393
+ // Annotate the CommonJS export names for ESM import in node:
4394
+ 0 && (module.exports = {
4395
+ DOMSelector
4396
+ });
3
4397
  /*!
4
4398
  * DOM Selector - A CSS selector engine.
5
4399
  * @license MIT