index.cjs 141 KB

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