@cypress/unique-selector 2.1.3 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,32 @@ Generates a unique CSS selector for the given DOM element.
56
56
 
57
57
  - **`isUniqueCache`** (Map<String, Boolean>, optional) - Cache to improve performance of repeated uniqueness checks. The caller is responsible for cache invalidation.
58
58
 
59
+ - **`requiredAttributes`** (Object, optional) - Specifies attributes that must appear in the generated selector regardless of whether they are needed for uniqueness. When provided, matching attribute selectors are woven into every element's segment of the `>` chain, and ancestors above the unique chain are prepended using descendant combinators.
60
+
61
+ This option takes precedence over `selectorTypes` and `filter` for the attributes it names — if an element has a required attribute, its `[attr="value"]` selector will appear in the output even if `filter` would reject that attribute for uniqueness purposes, and even if the attribute is not listed in `selectorTypes`.
62
+
63
+ The `requiredAttributes` object has the following shape:
64
+
65
+ - **`attributeNames`** (String[]) - The attribute names to inject into the selector (e.g., `['data-component', 'data-cy']`). Exact attribute names only — not patterns or regexes. Names are used as-provided in the generated selector with no internal normalization, so the casing you supply is the casing that appears in the output. When an attribute in `attributeNames` is already present in the base selector (from `selectorTypes`), dedup detection is case-insensitive, so duplicate injection is correctly suppressed regardless of case differences.
66
+ - **`filter`** (Function, optional) - A filter function with the same signature as the top-level `filter` option, applied independently to control which attribute _values_ are allowed to be injected. Return `false` to skip injection for a given element. This filter is separate from the top-level `filter` and serves a different purpose: the top-level `filter` controls which traits are eligible for building a _unique_ selector, while `requiredAttributes.filter` controls which attribute values are eligible for _injection_. The `key` argument passed to this function will match the casing of the name as provided in `attributeNames`.
67
+ - **`elementCache`** (Map<Element, (string|null)[]>, optional) - Cache for per-element required attribute selectors. Each cached entry is an array of individual selector strings parallel to `attributeNames` (null for attributes not present or filtered out). The caller is responsible for cache invalidation.
68
+
69
+ ```javascript
70
+ unique(element, {
71
+ requiredAttributes: {
72
+ attributeNames: ['data-component', 'data-cy'],
73
+ filter: (type, key, value) => {
74
+ // Exclude auto-generated component names from injection
75
+ if (type === 'attribute' && key === 'data-component') {
76
+ return !value.startsWith('jss-');
77
+ }
78
+ return true;
79
+ },
80
+ elementCache: new Map(),
81
+ }
82
+ });
83
+ ```
84
+
59
85
  #### Returns
60
86
 
61
87
  - **String** - A unique CSS selector for the element, or `null` if no unique selector can be generated
@@ -118,6 +144,68 @@ const selector = unique(element, {
118
144
  });
119
145
  ```
120
146
 
147
+ ### Required Attributes
148
+
149
+ Use `requiredAttributes` when you want specific attributes to always appear in the generated selector, regardless of whether they contribute to uniqueness. This is useful when your application uses semantic component attributes (e.g., `data-component`, `data-cy`) that you want reflected in every selector for readability or stability.
150
+
151
+ ```javascript
152
+ // Always include data-component in the selector, even when an ID alone would be unique
153
+ const selector = unique(element, {
154
+ requiredAttributes: {
155
+ attributeNames: ['data-component']
156
+ }
157
+ });
158
+ // '#submit-button' becomes '#submit-button[data-component="PrimaryButton"]'
159
+ // Ancestors with data-component are prepended with descendant combinators:
160
+ // '[data-component="Form"] #submit-button[data-component="PrimaryButton"]'
161
+ ```
162
+
163
+ Required attributes take precedence over `selectorTypes` and `filter`. If an element has a required attribute, it will be injected into the selector even if:
164
+ - The attribute is not listed in `selectorTypes`
165
+ - The top-level `filter` would reject that attribute for uniqueness purposes
166
+
167
+ ```javascript
168
+ // The top-level filter rejects data-component for uniqueness building,
169
+ // but requiredAttributes.filter allows it to still be injected.
170
+ const selector = unique(element, {
171
+ filter: (type, key) => key !== 'data-component',
172
+ requiredAttributes: {
173
+ attributeNames: ['data-component'],
174
+ // No requiredAttributes.filter — all values are injected
175
+ }
176
+ });
177
+ // data-component still appears in the output
178
+ ```
179
+
180
+ Use `requiredAttributes.filter` independently to control which attribute _values_ get injected, without affecting how uniqueness is determined:
181
+
182
+ ```javascript
183
+ // Inject data-component only when the value doesn't look auto-generated
184
+ const selector = unique(element, {
185
+ requiredAttributes: {
186
+ attributeNames: ['data-component'],
187
+ filter: (type, key, value) => {
188
+ if (type === 'attribute' && key === 'data-component') {
189
+ return !value.startsWith('jss-');
190
+ }
191
+ return true;
192
+ },
193
+ elementCache: new Map(), // reuse across calls for performance
194
+ }
195
+ });
196
+ ```
197
+
198
+ When multiple `attributeNames` are specified, each is matched independently on every element:
199
+
200
+ ```javascript
201
+ const selector = unique(element, {
202
+ requiredAttributes: {
203
+ attributeNames: ['data-cy', 'data-region']
204
+ }
205
+ });
206
+ // '[data-region="main"] [data-cy="dashboard"] .widget[data-cy="widget-a"]'
207
+ ```
208
+
121
209
  ### Performance Optimization with Caching
122
210
 
123
211
  ```javascript
@@ -157,6 +245,7 @@ The library follows this strategy to generate unique selectors:
157
245
  3. **Selector type precedence**: Uses the `selectorTypes` array to determine which selector types to try first
158
246
  4. **Combination fallback**: For classes and attributes, tries combinations of multiple selectors if single selectors aren't unique
159
247
  5. **Nth-child fallback**: Uses nth-child positioning as a last resort
248
+ 6. **Required attribute injection**: After the unique `>` chain is determined, any `requiredAttributes` are woven into each element's segment of the chain. Ancestors above the chain that carry a required attribute are prepended as descendant combinators. Required attributes are injected even when they are not needed for uniqueness and even when the top-level `filter` would exclude them from consideration.
160
249
 
161
250
  ## Examples of Generated Selectors
162
251
 
@@ -3,6 +3,10 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.getAttributeSelector = undefined;
7
+
8
+ var _utils = require('./utils');
9
+
6
10
  /**
7
11
  * Returns the {attr} selector of the element
8
12
  * @param { Element } el - The element.
@@ -19,7 +23,7 @@ var getAttributeSelector = exports.getAttributeSelector = function getAttributeS
19
23
 
20
24
  if (attributeValue) {
21
25
  // if we have value that needs quotes
22
- return '[' + attribute + '="' + attributeValue + '"]';
26
+ return '[' + attribute + '="' + (0, _utils.escapeAttributeValue)(attributeValue) + '"]';
23
27
  }
24
28
 
25
29
  return '[' + attribute + ']';
@@ -5,6 +5,8 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.getAttributes = getAttributes;
7
7
 
8
+ var _utils = require('./utils');
9
+
8
10
  function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
9
11
 
10
12
  /**
@@ -23,7 +25,7 @@ function getAttributes(el) {
23
25
 
24
26
  return attrs.reduce(function (sum, next) {
25
27
  if (!(attributesToIgnore.indexOf(next.nodeName) > -1) && (!filter || filter('attribute', next.nodeName, next.value))) {
26
- sum.push('[' + next.nodeName + '="' + next.value + '"]');
28
+ sum.push('[' + next.nodeName + '="' + (0, _utils.escapeAttributeValue)(next.value) + '"]');
27
29
  }
28
30
  return sum;
29
31
  }, []);
package/lib/getName.js CHANGED
@@ -4,6 +4,9 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.getName = getName;
7
+
8
+ var _utils = require('./utils');
9
+
7
10
  /**
8
11
  * Returns the `name` attribute of the element (if one exists)
9
12
  * @param { Object } element
@@ -14,7 +17,7 @@ function getName(el, filter) {
14
17
  var name = el.getAttribute('name');
15
18
 
16
19
  if (name !== null && name !== '' && (!filter || filter('attribute', 'name', name))) {
17
- return '[name="' + name + '"]';
20
+ return '[name="' + (0, _utils.escapeAttributeValue)(name) + '"]';
18
21
  }
19
22
  return null;
20
23
  }
package/lib/index.js CHANGED
@@ -27,6 +27,8 @@ var _getAttribute = require('./getAttribute');
27
27
 
28
28
  var _isShadowRoot = require('./isShadowRoot');
29
29
 
30
+ var _utils = require('./utils');
31
+
30
32
  function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /**
31
33
  * Expose `unique`
32
34
  */
@@ -34,6 +36,70 @@ function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr
34
36
  var dataRegex = /^data-.+/;
35
37
  var attrRegex = /^attribute:(.+)/m;
36
38
 
39
+ /**
40
+ * @typedef CompiledRequiredAttr
41
+ * @property { string } attributeName - The DOM attribute name (e.g. 'data-cy')
42
+ * @property { RegExp } dedupPattern - Matches `[attrName=` or `[attrName]` in a selector string to detect existing usage.
43
+ * Case-insensitive so it catches any casing the base selector builder may have used for the attribute name.
44
+ */
45
+
46
+ /**
47
+ * Returns per-attribute selector strings for all required attributes on an element.
48
+ * Each entry in the returned array corresponds to the same-index entry in compiledAttrs:
49
+ * a `[attr="value"]` string if the attribute is present and passes the filter, otherwise null.
50
+ * @param { Element } el
51
+ * @param { CompiledRequiredAttr[] } compiledAttrs
52
+ * @param { Function | undefined } filter
53
+ * @return { (string|null)[] }
54
+ */
55
+ function getPerAttrSelectors(el, compiledAttrs, filter) {
56
+ return compiledAttrs.map(function (_ref) {
57
+ var attributeName = _ref.attributeName;
58
+
59
+ var attrValue = el.getAttribute(attributeName);
60
+ if (attrValue === null) return null;
61
+ if (filter && !filter('attribute', attributeName, attrValue)) return null;
62
+ return attrValue ? '[' + attributeName + '="' + (0, _utils.escapeAttributeValue)(attrValue) + '"]' : '[' + attributeName + ']';
63
+ });
64
+ }
65
+
66
+ /**
67
+ * Returns per-attribute selectors for an element, using the cache when available.
68
+ * @param { Element } el
69
+ * @param { CompiledRequiredAttr[] } compiledAttrs
70
+ * @param { Function | undefined } filter
71
+ * @param { Map<Element, (string|null)[]> | undefined } cache
72
+ * @return { (string|null)[] }
73
+ */
74
+ function getCachedPerAttrSelectors(el, compiledAttrs, filter, cache) {
75
+ if (cache && cache.has(el)) return cache.get(el);
76
+ var selectors = getPerAttrSelectors(el, compiledAttrs, filter);
77
+ if (cache) cache.set(el, selectors);
78
+ return selectors;
79
+ }
80
+
81
+ /**
82
+ * Merges required attribute selectors into an element's base selector, placing them
83
+ * before any :nth-child pseudo-class. Attributes already present in the base selector
84
+ * are excluded from injection via a case-insensitive dedupPattern check.
85
+ * @param { String } selector - A single element's selector (no combinators)
86
+ * @param { (string|null)[] } perAttrSelectors - Per-attribute selector strings parallel to compiledAttrs
87
+ * @param { CompiledRequiredAttr[] } compiledAttrs
88
+ * @return { String }
89
+ */
90
+ function insertRequiredAttrIntoSelector(selector, perAttrSelectors, compiledAttrs) {
91
+ var toInject = perAttrSelectors.filter(function (s, i) {
92
+ return s !== null && !compiledAttrs[i].dedupPattern.test(selector);
93
+ }).join('');
94
+ if (!toInject) return selector;
95
+ // Insert before :nth-child so the attribute qualifier binds to the element tag/class
96
+ var nthChildIndex = selector.indexOf(':nth-child');
97
+ if (nthChildIndex !== -1) {
98
+ return selector.slice(0, nthChildIndex) + toInject + selector.slice(nthChildIndex);
99
+ }
100
+ return selector + toInject;
101
+ }
102
+
37
103
  /**
38
104
  * @typedef Filter
39
105
  * @type {Function}
@@ -246,8 +312,8 @@ function getUniqueSelector(element, selectorTypes, attributesToIgnore, filter) {
246
312
  }
247
313
 
248
314
  /**
249
- * Generate unique CSS selector for given DOM element. Selector uniqueness is determined based on the given element's root node.
250
- * Elements rendered within Shadow DOM will derive a selector that is unique within the associated ShadowRoot context.
315
+ * Generate unique CSS selector for given DOM element. Selector uniqueness is determined based on the given element's root node.
316
+ * Elements rendered within Shadow DOM will derive a selector that is unique within the associated ShadowRoot context.
251
317
  * Otherwise, a selector that is unique within the element's owning document will be derived.
252
318
  *
253
319
  * @param {Element} el
@@ -255,10 +321,10 @@ function getUniqueSelector(element, selectorTypes, attributesToIgnore, filter) {
255
321
  * @param {String[]} options.selectorTypes Specify the set of traits to leverage when building selectors in precedence order
256
322
  * @param {String[]} options.attributesToIgnore Specify a set of attributes to *not* leverage when building selectors
257
323
  * @param {Filter} options.filter Provide a filter function to conditionally reject various traits when building selectors.
258
- * @param {Map<Element, String>} options.selectorCache Provide a cache to improve performance of repeated selector generation - it is the responsibility of the caller to handle cache invalidation. Caching is performed using the input Element as key. This cache handles Element -> Selector caching.
259
- * @param {Map<String, Boolean>} options.isUniqueCache Provide a cache to improve performance of repeated selector generation - it is the responsibility of the caller to handle cache invalidation. Caching is performed using the input Element as key. This cache handles Selector -> isUnique caching.
324
+ * @param {Map<Element, String>} options.selectorCache Cache for Element -> Selector mappings. Caller is responsible for invalidation.
325
+ * @param {Map<String, Boolean>} options.isUniqueCache Cache for Selector -> isUnique mappings. Caller is responsible for invalidation.
326
+ * @param {{ attributeNames: string[], filter?: Function, elementCache?: Map<Element, (string|null)[]> }} options.requiredAttributes Attributes that must appear in the generated selector. Specifies the attribute names to inject, an optional filter function to control which values are allowed, and an optional element cache. Matching attributes are woven into the selector chain and ancestor context.
260
327
  * @return {String}
261
- * @api private
262
328
  */
263
329
  function unique(el) {
264
330
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -268,9 +334,30 @@ function unique(el) {
268
334
  attributesToIgnore = _options$attributesTo === undefined ? ['id', 'class', 'length'] : _options$attributesTo,
269
335
  filter = options.filter,
270
336
  selectorCache = options.selectorCache,
271
- isUniqueCache = options.isUniqueCache;
272
- // If filter was provided wrap it to ensure a default value of `true` is returned if the provided function fails to return a value
273
-
337
+ isUniqueCache = options.isUniqueCache,
338
+ requiredAttributes = options.requiredAttributes;
339
+
340
+ var _ref2 = requiredAttributes || {},
341
+ requiredAttributeNames = _ref2.attributeNames,
342
+ requiredAttributesFilter = _ref2.filter,
343
+ requiredAttributesElementCache = _ref2.elementCache;
344
+
345
+ // Precompile required attribute patterns once per call to avoid repeated
346
+ // RegExp construction during the element walk.
347
+
348
+
349
+ var hasRequiredAttrs = requiredAttributeNames && requiredAttributeNames.length > 0;
350
+ var compiledRequiredAttrs = hasRequiredAttrs ? requiredAttributeNames.map(function (attributeName) {
351
+ // Escape regex metacharacters: - [ ] / { } ( ) * + ? . \ ^ $ |
352
+ var escaped = attributeName.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
353
+ return {
354
+ attributeName: attributeName,
355
+ // Case-insensitive: catches any casing the base selector builder may have used for the attribute name.
356
+ dedupPattern: new RegExp('\\[' + escaped + '[=\\]]', 'i')
357
+ };
358
+ }) : null;
359
+
360
+ // Wrap filter to default to `true` when the provided function returns null/undefined
274
361
  var normalizedFilter = filter && function (type, key, value) {
275
362
  var result = filter(type, key, value);
276
363
  if (result === null || result === undefined) {
@@ -286,6 +373,13 @@ function unique(el) {
286
373
 
287
374
  if (!selector) {
288
375
  selector = getUniqueSelector(currentElement, selectorTypes, attributesToIgnore, normalizedFilter);
376
+
377
+ // Merge any matching required attributes into the element's selector
378
+ if (hasRequiredAttrs) {
379
+ var perAttrSelectors = getCachedPerAttrSelectors(currentElement, compiledRequiredAttrs, requiredAttributesFilter, requiredAttributesElementCache);
380
+ selector = insertRequiredAttrIntoSelector(selector, perAttrSelectors, compiledRequiredAttrs);
381
+ }
382
+
289
383
  if (selectorCache) {
290
384
  selectorCache.set(currentElement, selector);
291
385
  }
@@ -315,6 +409,22 @@ function unique(el) {
315
409
  }
316
410
 
317
411
  if (isUniqueSelector) {
412
+ // Prepend required attribute selectors from ancestors above the unique
413
+ // chain using descendant combinators (e.g. '[data-cy="app"] [data-cy="nav"] .btn').
414
+ if (hasRequiredAttrs) {
415
+ var ancestorSelectors = [];
416
+ var ancestor = currentElement.parentElement;
417
+ while (ancestor) {
418
+ var _perAttrSelectors = getCachedPerAttrSelectors(ancestor, compiledRequiredAttrs, requiredAttributesFilter, requiredAttributesElementCache);
419
+ var combined = _perAttrSelectors.filter(Boolean).join('');
420
+ if (combined) ancestorSelectors.unshift(combined);
421
+ ancestor = ancestor.parentElement;
422
+ }
423
+ if (ancestorSelectors.length > 0) {
424
+ return ancestorSelectors.join(' ') + ' ' + maybeUniqueSelector;
425
+ }
426
+ }
427
+
318
428
  return maybeUniqueSelector;
319
429
  }
320
430
 
package/lib/utils.js ADDED
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.escapeAttributeValue = escapeAttributeValue;
7
+ function escapeAttributeValue(value) {
8
+ // Ultra-minimal escaping purely for attribute values that will be used inside quotes
9
+ // Using `CSS.escape` would create valid but non-minimal strings (escaping things like spaces)
10
+ // whereas this only escapes absolutely necessary characters for attribute values that
11
+ // will be used inside quotes.
12
+ return value.replace(/\\/g, '\\\\') // backslash
13
+ .replace(/"/g, '\\"') // quote
14
+ .replace(/\n/g, '\\A ') // newline
15
+ .replace(/\r/g, '\\D ') // carriage return
16
+ .replace(/\f/g, '\\C '); // form feed
17
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cypress/unique-selector",
3
- "version": "2.1.3",
3
+ "version": "2.2.0",
4
4
  "description": "Given a DOM node, return a unique CSS selector matching only that element",
5
5
  "main": "./lib/index.js",
6
6
  "jsnext:main": "./src/index.js",