Skip to content

Commit 29003f0

Browse files
committed
fix: restore logical selectors and guarded DOM state matching
Consolidates the original contiguous commits 1349bff..7af2512. Preserves the exact tree at the end of this group.
1 parent 84feeb4 commit 29003f0

17 files changed

Lines changed: 936 additions & 33 deletions

‎.config/generated.d.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// The build creates this CommonJS module before tests run. Keep clean-tree
2+
// type checks independent of the generated JavaScript file.
3+
declare module '*/src/nwsapi.js' {
4+
const factory: (host: { document: Document }) => typeof NW.Dom
5+
export default factory
6+
}

‎.config/runtime.d.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ interface NwsapiEngine {
77
first(selector: string, context?: Node): Element | null
88
match(this: void, selector: string, context: Element): boolean
99
configure(options: Record<string, unknown>, clear?: boolean): unknown
10+
install(all?: boolean): void
11+
uninstall(): void
1012
registerSelector(
1113
name: string,
1214
expression: RegExp,

‎assets/repo/coverage.svg‎

Lines changed: 1 addition & 1 deletion
Loading

‎src/nwsapi.mts‎

Lines changed: 115 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939
root = doc.documentElement,
4040
slice = Array.prototype.slice,
4141

42+
// Factory fallback for documents without a window.
43+
ELEMENT_PROTO = global.Element && global.Element.prototype,
44+
4245
HSP = '\\x20\\t',
4346
VSP = '\\r\\n\\f',
4447
WSP = '[' + HSP + VSP + ']',
@@ -88,14 +91,12 @@
8891
locationpc: '(any\\-link|link|visited|target|defined)\\b',
8992
useraction: '(hover|active|focus\\-within|focus\\-visible|focus)\\b',
9093
structural: '(scope|root|empty|(?:(?:first|last|only)(?:-child|\\-of\\-type)))\\b',
91-
inputstate: '(enabled|disabled|read\\-only|read\\-write|placeholder\\-shown|default)\\b',
94+
inputstate: '(enabled|disabled|read\\-only|read\\-write|placeholder\\-shown|default|autofill|-webkit\\-autofill)\\b',
9295
inputvalue: '(checked|indeterminate|required|optional|valid|invalid|in\\-range|out\\-of\\-range)\\b',
9396
// pseudo-classes not requiring parameters and describing functional state
9497
rsrc_state: '(playing|paused|seeking|buffering|stalled|muted|volume\\-locked)\\b',
9598
disp_state: '(open|closed|modal|fullscreen|picture\\-in\\-picture|popover\\-open|popover)\\b',
9699
time_state: '(current|past|future)\\b',
97-
// pseudo-classes for parsing only selectors
98-
pseudo_nop: '(autofill|-webkit\\-autofill)\\b',
99100
// pseudo-elements starting with single colon (:)
100101
pseudo_sng: '(after|before|first\\-letter|first\\-line)\\b',
101102
// pseudo-elements starting with double colon (::)
@@ -115,7 +116,6 @@
115116
time_state: RegExp('^:(?:' + GROUPS.time_state + ')(.*)', 'i'),
116117
locationpc: RegExp('^:(?:' + GROUPS.locationpc + ')(.*)', 'i'),
117118
logicalsel: RegExp('^:(?:' + GROUPS.logicalsel + ')(.*)', 'i'),
118-
pseudo_nop: RegExp('^:(?:' + GROUPS.pseudo_nop + ')(.*)', 'i'),
119119
pseudo_sng: RegExp('^:(?:' + GROUPS.pseudo_sng + ')(.*)', 'i'),
120120
pseudo_dbl: RegExp('^:(?:' + GROUPS.pseudo_dbl + ')(.*)', 'i'),
121121
// combinator symbols
@@ -469,6 +469,28 @@
469469
// argument left unclosed is closed by EOF, as the CSS Syntax parser does
470470
// with any open construct. Returns a match-like array so that callers can
471471
// pop() the remainder the same way they do with a RegExp match.
472+
splitList =
473+
function(text) {
474+
var chr, depth = 0, escaped, i = 0, l = text.length,
475+
quote = '', start = 0, list = [ ];
476+
477+
for (; l > i; ++i) {
478+
chr = text.charAt(i);
479+
if (escaped) { escaped = false; continue; }
480+
if (chr == '\\') { escaped = true; }
481+
else if (quote) { if (chr == quote) { quote = ''; } }
482+
else if (chr == '\x22' || chr == '\x27') { quote = chr; }
483+
else if (chr == '\x28' || chr == '\x5b') { ++depth; }
484+
else if (chr == '\x29' || chr == '\x5d') { --depth; }
485+
else if (chr == ',' && depth === 0) {
486+
list[list.length] = text.slice(start, i).replace(REX.TrimSpaces, '');
487+
start = i + 1;
488+
}
489+
}
490+
list[list.length] = text.slice(start).replace(REX.TrimSpaces, '');
491+
return list;
492+
},
493+
472494
matchLogical =
473495
function(selector) {
474496
var chr, close, escaped, depth = 1, i, l, quote = '',
@@ -778,26 +800,72 @@
778800
return false;
779801
},
780802

803+
// Called during document setup only when legacy mode needs an alias.
804+
legacyMatcher =
805+
function(proto) {
806+
return proto && (proto.webkitMatchesSelector ||
807+
proto.mozMatchesSelector || proto.msMatchesSelector);
808+
},
809+
781810
// use the native selector state when it is available; when NWSAPI has
782811
// installed itself, _matches retains the native implementation
783812
matchesNative =
784813
function(node, selector) {
785-
// A host such as jsdom can delegate matches() back to this engine.
786-
if (matchingNative) return false;
787-
var matcher = _matches || node.matches || node.webkitMatchesSelector ||
788-
node.mozMatchesSelector || node.msMatchesSelector;
789-
if (!matcher) return false;
814+
var view, proto, matcher, ownerDoc = node.ownerDocument || doc;
815+
// Record delegation before doing any lookup. Nested calls must not
816+
// replace the document record belonging to the outer matcher.
817+
if (matchingNative) { matchingNative.delegates = true; return false; }
818+
if (ownerDoc !== matcherDoc) {
819+
if (matcherCache === null) { matcherCache = createWeakMap(); }
820+
matcherDoc = ownerDoc;
821+
matcherRecord = matcherCache && matcherCache.get(ownerDoc);
822+
if (!matcherRecord) {
823+
matcherRecord = {
824+
fallback: null,
825+
matcher: undefined,
826+
delegates: false
827+
};
828+
if (matcherCache) { matcherCache.set(ownerDoc, matcherRecord); }
829+
}
830+
}
831+
// Host methods can change after setup, including element overrides.
832+
// Retain delegation only while the selected function stays the same.
833+
matcher = _matches ||
834+
((ownerDoc.defaultView || Object.prototype.hasOwnProperty.call(node, 'matches')) && node.matches) ||
835+
(ELEMENT_PROTO && ELEMENT_PROTO.matches);
836+
if (!matcher && Config.LEGACY) {
837+
if (matcherRecord.fallback === null) {
838+
view = ownerDoc.defaultView;
839+
proto = view && view.Element && view.Element.prototype;
840+
matcherRecord.fallback = legacyMatcher(proto) ||
841+
(proto !== ELEMENT_PROTO ? legacyMatcher(ELEMENT_PROTO) : undefined);
842+
}
843+
matcher = matcherRecord.fallback;
844+
}
845+
if (matcher !== matcherRecord.matcher) {
846+
matcherRecord.matcher = matcher;
847+
matcherRecord.delegates = false;
848+
}
849+
if (!matcher || matcherRecord.delegates) { return false; }
790850
try {
791-
matchingNative = true;
851+
matchingNative = matcherRecord;
792852
return matcher.call(node, selector);
793853
} catch (e) {
794854
return false;
795855
} finally {
796-
matchingNative = false;
856+
matchingNative = null;
797857
}
798858
},
799859

800-
matchingNative = false,
860+
// The active record is marked directly on re-entry, even if the host throws.
861+
matchingNative = null,
862+
863+
// Consecutive queries avoid a WeakMap lookup. Retain other documents weakly
864+
// so switching realms does not repeat delegation detection. Allocate after
865+
// legacy configuration, on first use; undefined selects the bounded fallback.
866+
matcherDoc = null,
867+
matcherRecord = null,
868+
matcherCache = null,
801869

802870
// :open and :closed have a portable DOM state for details and dialog.
803871
// Native matching extends support to host-language states such as pickers.
@@ -868,6 +936,11 @@
868936
if (typeof option == 'string') { return !!Config[option]; }
869937
if (typeof option != 'object') { return Config; }
870938
for (var i in option) {
939+
// Compiled logical selectors capture the forgiving mode.
940+
if (i == 'FORGIVING' && Config[i] !== !!option[i]) { clear = true; }
941+
if (i == 'LEGACY' && Config[i] !== !!option[i]) {
942+
matcherDoc = matcherCache = null;
943+
}
871944
Config[i] = !!option[i];
872945
}
873946
// clear lambda cache
@@ -977,7 +1050,10 @@
9771050
'(?:[.#]?' + identifier + ')|' +
9781051
'(?:' + attributes + ')' +
9791052
')+|' +
980-
'(?:' + WSP + '?[>+~][^>+~]' + WSP + '?)|' +
1053+
// the combinator is only recognized, not consumed: taking the
1054+
// character after it swallows the '[' of a following attribute
1055+
// selector, which then cannot be parsed
1056+
'(?:' + WSP + '?[>+~](?=[^>+~])' + WSP + '?)|' +
9811057
'(?:' + WSP + '?,' + WSP + '?)|' +
9821058
'(?:' + WSP + '?)|' +
9831059
'(?:\\x29|$)' +
@@ -1363,10 +1439,8 @@
13631439
case 'is':
13641440
case 'where':
13651441
if (Config.FORGIVING) {
1366-
source =
1367-
'try{' +
1368-
'if(s.match("' + expr + '",e)){' + source + '}' +
1369-
'}catch(E){}';
1442+
source = 'if(s.matchForgiving(' +
1443+
JSON.stringify(splitList(match[2])) + ',e)){' + source + '}';
13701444
} else {
13711445
source = 'if(s.match("' + expr + '",e)){' + source + '}';
13721446
}
@@ -1541,7 +1615,7 @@
15411615
break;
15421616
case 'autofill':
15431617
case '-webkit-autofill':
1544-
source = 'if(e.matches&&e.matches(":-webkit-autofill,:autofill")){' + source + '}';
1618+
source = 'if(s.matchesNative(e,":autofill")||s.matchesNative(e,":-webkit-autofill")){' + source + '}';
15451619
break;
15461620
case 'placeholder-shown':
15471621
source =
@@ -1700,11 +1774,6 @@
17001774
}
17011775
}
17021776

1703-
// placeholder for parse only no-op selectors
1704-
else if ((match = selector.match(Patterns.pseudo_nop))) {
1705-
break;
1706-
}
1707-
17081777
// allow pseudo-elements starting with single colon (:)
17091778
// :after, :before, :first-letter, :first-line
17101779
// assert: e.type is in double-colon format, like ::after
@@ -1908,7 +1977,7 @@
19081977

19091978
// parse, validate and split possible compound selectors
19101979
if ((selectors = parsed.match(reValidator)) && selectors.join('') == parsed) {
1911-
selectors = parsed.match(REX.SplitGroup);
1980+
selectors = splitList(parsed);
19121981
if (parsed[parsed.length - 1] == ',') {
19131982
emit(qsInvalid);
19141983
return Config.VERBOSITY ? undefined : (type ? none : false);
@@ -1917,7 +1986,9 @@
19171986
if (Config.FORGIVING) {
19181987
// forgiving pseudos allow to continue even after parse errors
19191988
if (!(parsed.includes(':is(') || parsed.includes(':where('))) {
1920-
emit('\'' + selectors + '\'' + qsInvalid);
1989+
// 'selectors' holds the fragments the validator did match,
1990+
// which read as a mangled selector once joined by String()
1991+
emit('\'' + parsed + '\'' + qsInvalid);
19211992
return Config.VERBOSITY ? undefined : (type ? none : false);
19221993
}
19231994
// The validator cannot read this selector, but it holds a
@@ -1929,7 +2000,7 @@
19292000
// the fragments compiled each of them as a selector of its own,
19302001
// which made 'div:not(:is(svg|div))' match every element in the
19312002
// document rather than the divs.
1932-
selectors = parsed.match(REX.SplitGroup) || [ parsed ];
2003+
selectors = splitList(parsed);
19332004
}
19342005
}
19352006

@@ -1938,7 +2009,7 @@
19382009

19392010
// equivalent of w3c 'matches' method
19402011
match =
1941-
function _matches(selectors, element, callback) {
2012+
function _matches(selectors, element, callback?: (element: Element) => unknown) {
19422013

19432014
var resolver;
19442015

@@ -1952,6 +2023,17 @@
19522023
return match_assert(resolver.factory, element, callback);
19532024
},
19542025

2026+
// Invalid items do not discard the remaining forgiving selectors.
2027+
matchForgiving =
2028+
function(list, element) {
2029+
for (var i = 0, l = list.length; l > i; ++i) {
2030+
try {
2031+
if (match(list[i], element)) { return true; }
2032+
} catch (e) { }
2033+
}
2034+
return false;
2035+
},
2036+
19552037
// true if element matches the selector
19562038
has =
19572039
function(selector, context, callback) {
@@ -2214,7 +2296,7 @@
22142296
Element.prototype.querySelector =
22152297
HTMLElement.prototype.querySelector = _querySelector;
22162298
Element.prototype.querySelectorAll =
2217-
HTMLElement.prototype.querySelectorAll = _querySelector;
2299+
HTMLElement.prototype.querySelectorAll = _querySelectorAll;
22182300
}
22192301
if (_querySelectorAllDoc) {
22202302
Document.prototype.querySelector =
@@ -2243,8 +2325,10 @@
22432325
HOVER?: EventTarget;
22442326
doc: Document; from: Node; root: Element;
22452327
byTag: typeof byTag; has: typeof has; first: typeof first;
2246-
match: typeof match; select: typeof select; ancestor: typeof ancestor;
2328+
match: typeof match; matchForgiving: typeof matchForgiving;
2329+
select: typeof select; ancestor: typeof ancestor;
22472330
nthOfType: typeof nthOfType; nthElement: typeof nthElement;
2331+
matchesNative: typeof matchesNative;
22482332
isOpen: typeof isOpen; isClosed: typeof isClosed; isModal: typeof isModal;
22492333
isFullscreen: typeof isFullscreen; isPictureInPicture: typeof isPictureInPicture;
22502334
isPopoverOpen: typeof isPopoverOpen; isFocusable: typeof isFocusable;
@@ -2261,13 +2345,15 @@
22612345
has: has,
22622346
first: first,
22632347
match: match,
2348+
matchForgiving: matchForgiving,
22642349
select: select,
22652350

22662351
ancestor: ancestor,
22672352

22682353
nthOfType: nthOfType,
22692354
nthElement: nthElement,
22702355

2356+
matchesNative: matchesNative,
22712357
isOpen: isOpen,
22722358
isClosed: isClosed,
22732359
isModal: isModal,
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { test, expect } from 'vitest'
2+
import { JSDOM } from 'jsdom'
3+
import { createRequire } from 'node:module'
4+
5+
const require = createRequire(import.meta.url)
6+
const factory = require('../src/nwsapi.js')
7+
8+
for (const quote of ["'", '"']) {
9+
for (const combinator of ['+', '~', '>']) {
10+
test(`quoted attributes after pseudos (${quote}, ${combinator})`, t => {
11+
const markup =
12+
combinator === '>'
13+
? '<div class="A"><p class="b" id="target"></p></div>'
14+
: '<div><p class="A">text</p><p class="b" id="target"></p></div>'
15+
const { window } = new JSDOM(markup)
16+
t.onTestFinished(() => window.close())
17+
const engine = factory(window)
18+
const selector = `[class*=${quote}a${quote} i]:not(:empty) ${combinator} [class*=${quote}b${quote}]`
19+
const target = window.document.getElementById('target')
20+
for (let repeat = 0; repeat < 2; repeat++) {
21+
expect(engine.select(selector, window.document)).toEqual([target])
22+
expect(engine.first(selector, window.document)).toBe(target)
23+
expect(engine.match(selector, target)).toBe(true)
24+
}
25+
target.className = 'c'
26+
expect(engine.select(selector, window.document)).toEqual([])
27+
})
28+
}
29+
}
30+
31+
test('invalid selectors retain their original text in errors', t => {
32+
const { window } = new JSDOM('<p></p>')
33+
t.onTestFinished(() => window.close())
34+
const engine = factory(window)
35+
const selector = "[class*='a' i]:not(:empty)+[class*='b'] ?"
36+
expect(() => engine.select(selector, window.document)).toThrow(selector)
37+
})

0 commit comments

Comments
 (0)