@atlaskit/eslint-plugin-ui-styling-standard 2.1.10 → 2.3.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +2 -0
  3. package/dist/cjs/presets/all-flat.codegen.js +3 -1
  4. package/dist/cjs/presets/all.codegen.js +3 -1
  5. package/dist/cjs/presets/recommended-flat.codegen.js +2 -1
  6. package/dist/cjs/presets/recommended.codegen.js +2 -1
  7. package/dist/cjs/rules/index.codegen.js +5 -1
  8. package/dist/cjs/rules/no-atlaskit-theme/index.js +34 -0
  9. package/dist/cjs/rules/no-top-layer-unsafe-selectors/find-template-selectors.js +232 -0
  10. package/dist/cjs/rules/no-top-layer-unsafe-selectors/index.js +425 -0
  11. package/dist/cjs/rules/no-top-layer-unsafe-selectors/preserve-list-layout.js +63 -0
  12. package/dist/cjs/rules/no-top-layer-unsafe-selectors/rewrite-selector.js +2415 -0
  13. package/dist/cjs/rules/utils/walk-style-call-properties.js +11 -24
  14. package/dist/cjs/rules/utils/walk-style-object-properties.js +47 -0
  15. package/dist/es2019/presets/all-flat.codegen.js +3 -1
  16. package/dist/es2019/presets/all.codegen.js +3 -1
  17. package/dist/es2019/presets/recommended-flat.codegen.js +2 -1
  18. package/dist/es2019/presets/recommended.codegen.js +2 -1
  19. package/dist/es2019/rules/index.codegen.js +5 -1
  20. package/dist/es2019/rules/no-atlaskit-theme/index.js +28 -0
  21. package/dist/es2019/rules/no-top-layer-unsafe-selectors/find-template-selectors.js +226 -0
  22. package/dist/es2019/rules/no-top-layer-unsafe-selectors/index.js +382 -0
  23. package/dist/es2019/rules/no-top-layer-unsafe-selectors/preserve-list-layout.js +57 -0
  24. package/dist/es2019/rules/no-top-layer-unsafe-selectors/rewrite-selector.js +2131 -0
  25. package/dist/es2019/rules/utils/walk-style-call-properties.js +12 -15
  26. package/dist/es2019/rules/utils/walk-style-object-properties.js +29 -0
  27. package/dist/esm/presets/all-flat.codegen.js +3 -1
  28. package/dist/esm/presets/all.codegen.js +3 -1
  29. package/dist/esm/presets/recommended-flat.codegen.js +2 -1
  30. package/dist/esm/presets/recommended.codegen.js +2 -1
  31. package/dist/esm/rules/index.codegen.js +5 -1
  32. package/dist/esm/rules/no-atlaskit-theme/index.js +28 -0
  33. package/dist/esm/rules/no-top-layer-unsafe-selectors/find-template-selectors.js +226 -0
  34. package/dist/esm/rules/no-top-layer-unsafe-selectors/index.js +419 -0
  35. package/dist/esm/rules/no-top-layer-unsafe-selectors/preserve-list-layout.js +57 -0
  36. package/dist/esm/rules/no-top-layer-unsafe-selectors/rewrite-selector.js +2409 -0
  37. package/dist/esm/rules/utils/walk-style-call-properties.js +11 -24
  38. package/dist/esm/rules/utils/walk-style-object-properties.js +41 -0
  39. package/dist/types/presets/all-flat.codegen.d.ts +1 -1
  40. package/dist/types/presets/all.codegen.d.ts +1 -1
  41. package/dist/types/presets/recommended-flat.codegen.d.ts +1 -1
  42. package/dist/types/presets/recommended.codegen.d.ts +1 -1
  43. package/dist/types/rules/index.codegen.d.ts +1 -1
  44. package/dist/types/rules/no-atlaskit-theme/index.d.ts +3 -0
  45. package/dist/types/rules/no-top-layer-unsafe-selectors/find-template-selectors.d.ts +29 -0
  46. package/dist/types/rules/no-top-layer-unsafe-selectors/index.d.ts +3 -0
  47. package/dist/types/rules/no-top-layer-unsafe-selectors/preserve-list-layout.d.ts +12 -0
  48. package/dist/types/rules/no-top-layer-unsafe-selectors/rewrite-selector.d.ts +164 -0
  49. package/dist/types/rules/utils/walk-style-call-properties.d.ts +1 -0
  50. package/dist/types/rules/utils/walk-style-object-properties.d.ts +18 -0
  51. package/package.json +1 -1
@@ -0,0 +1,2131 @@
1
+ import selectorParser from 'postcss-selector-parser';
2
+
3
+ /**
4
+ * # Top layer selector safety transform
5
+ *
6
+ * A pure function over selector text. The `no-top-layer-unsafe-selectors` ESLint rule drives it
7
+ * for its autofix. It is kept separate from the rule so that a bulk sweep over the sources an
8
+ * ESLint rule cannot see (`.css` files, `injectGlobal` bodies) can run the same code rather than
9
+ * a second copy of the rewrite.
10
+ *
11
+ * ## Why
12
+ *
13
+ * Design System layering surfaces (popup, tooltip, modal, drawer…) are moving out of React
14
+ * portals and into the browser top layer behind the `platform-dst-top-layer` gate. The host
15
+ * — a `<div popover>` or a `<dialog>` — becomes a real node in the consumer's DOM. Consumer
16
+ * CSS that could never reach a portalled surface now matches it, and positional selectors
17
+ * that counted only real children now count the host.
18
+ *
19
+ * The canonical guard forms, the specificity reasoning, and the list of patterns for which
20
+ * no guard form exists live in the decision doc:
21
+ *
22
+ * `platform/packages/design-system/top-layer/notes/decisions/top-layer-unsafe-selectors.md`
23
+ *
24
+ * ## Why a guard is the right fix at all
25
+ *
26
+ * The governing principle, and the cleanest statement of when this transform helps rather than
27
+ * harms:
28
+ *
29
+ * > A guard is safe when it **restores pre-flag behaviour**, and harmful when it **removes
30
+ * > something the host had pre-flag**. Global-scope selectors reached the portalled host;
31
+ * > consumer-scoped selectors did not.
32
+ *
33
+ * Pre-flag the host was portalled to `body`, so a consumer-scoped rule such as `& > div` never
34
+ * matched it. Post-flag it does — that is the damage, and guarding restores what the consumer
35
+ * used to render. A global rule such as `* { box-sizing: inherit }`, by contrast, matched the
36
+ * portalled host all along; guarding it would take away something the host already had, which
37
+ * is a behaviour change rather than a fix.
38
+ *
39
+ * The discriminator is **reach**, not property semantics — which is why no browser measurement
40
+ * can settle it. A browser can say what `box-sizing` does; it cannot say what the DOM looked
41
+ * like before the flag.
42
+ *
43
+ * Operationally, at `global` scope a compound with nothing but the document itself above it
44
+ * (`html`, `body`, `:root`, `*`, or no ancestor at all) is left alone: `div`, `body div` and
45
+ * `* + *` all reached the portalled surface's content already. A compound below a consumer's
46
+ * own ancestor (`.sidebar div`, `.x > div`) is guarded as usual, because the host inside that
47
+ * ancestor is a new match. See {@link isDocumentLevelCompound}.
48
+ *
49
+ * One ancestor is ambiguous: a bare `div`. The portal container and every surface wrapper were
50
+ * divs, so `div span` at global scope may well have reached the surface's content already, yet
51
+ * the author may equally have meant their own wrapper. The transform does not guess. A compound
52
+ * whose ancestors are all document-level or bare `div`, with at least one bare `div`, is returned
53
+ * as `excluded` with `reviewCause: 'div-ancestor'`, which a bulk caller can surface as a comment
54
+ * at the site for a human to decide. See {@link isBareDivCompound}.
55
+ *
56
+ * ## Contract
57
+ *
58
+ * `rewriteSelector(selector)` is pure, total and idempotent. It accepts both nested
59
+ * authoring selectors (containing `&`) and plain CSS selectors, so a `.css`-file sweep can
60
+ * reuse it. It never returns a partial rewrite: a selector is either fully rewritten, or
61
+ * provably already safe, or refused with a reason.
62
+ *
63
+ * A selector with no `&` reads differently depending on where it is written. Inside a style
64
+ * object or a `css` template the authoring API scopes it to the component's own element, so
65
+ * `:hover` means `&:hover` and `span` means `& span`. In a plain stylesheet it reaches the
66
+ * whole document. The caller says which with {@link RewriteOptions.scope}; the ESLint rule
67
+ * always passes `nested`.
68
+ *
69
+ * One family is **reported but not fixed**: any rewrite that would need an `of S` clause, which
70
+ * is every positional pseudo-class. Compiled's extract mode drops the CSS for such a selector
71
+ * outright, so the guard deletes styling instead of protecting it. See
72
+ * {@link WITHDRAWN_POSITIONAL_FORMS} for the measurement. The planner refuses the family in
73
+ * {@link planPositionals}, and a selector that already carries an `of` clause is refused
74
+ * before planning starts.
75
+ *
76
+ * Every rewrite is specificity-neutral. That is enforced structurally, not merely tested:
77
+ * the transform recomputes (a,b,c) branch-by-branch on its own output and downgrades the
78
+ * result to `residue` if it does not match the input. It also re-checks its own output for a
79
+ * nested `:has()`, which Chromium rejects outright.
80
+ *
81
+ * ## A note on the literal guard strings below
82
+ *
83
+ * The guard text is emitted *literally* into the rewritten selector at every site — never
84
+ * interpolated from a constant in the generated code. A ratcheting rule matches raw source
85
+ * text, so a guard interpolated from a constant in consumer code would make the ratchet's
86
+ * count assertions vacuous. The constants here are internal to this module; what lands in
87
+ * consumer source is always the full literal list.
88
+ */
89
+
90
+ /* -------------------------------------------------------------------------------------- */
91
+ /* Guard forms — authoritative, from the decision doc */
92
+ /* -------------------------------------------------------------------------------------- */
93
+
94
+ /**
95
+ * The narrow guard, `:not(:where(L))`. Appended where the matching element could *be* the
96
+ * host: child-combinator compounds, sibling-combinator right-hand compounds, and the
97
+ * leftmost compound of a selector.
98
+ *
99
+ * `[popover]` and `dialog` cover both routes into the top layer — `popover` for
100
+ * popover-based surfaces, and `dialog` for modal and drawer, which use `showModal()` and set
101
+ * no `popover` attribute.
102
+ *
103
+ * `style`, `script`, `template`, `link` and `noscript` are left out on purpose. They are
104
+ * `display: none`, so a style that reaches them has no visible effect unless it sets
105
+ * `display`, and that hazard predates the top layer. They only matter to positional
106
+ * selectors, which have no guard form (see `S`).
107
+ *
108
+ * Specificity: `:where()` is weightless and `:not()` inherits the specificity of its
109
+ * argument, so this contributes (0,0,0).
110
+ */
111
+ const NARROW_GUARD = ':not(:where([popover], dialog))';
112
+
113
+ /**
114
+ * The wide guard, `:not(:where(L_wide))`. Appended where the matching element could be the
115
+ * host *or anything inside its subtree*: `:has()` arguments, and descendant-combinator
116
+ * compounds where the host may be any intermediate ancestor.
117
+ *
118
+ * Specificity: (0,0,0), for the same reason as the narrow guard.
119
+ */
120
+ const WIDE_GUARD = ':not(:where([popover], dialog, [popover] *, dialog *))';
121
+
122
+ /**
123
+ * `S` — the weightless "is a real, non-host element" test used as the `of S` argument to
124
+ * `:nth-child()` / `:nth-last-child()`, where it re-bases sibling counting onto real
125
+ * elements only.
126
+ *
127
+ * Unlike `L`, `S` lists the non-rendered elements too, because SSR and dev-loop style
128
+ * injection add them as siblings and they shift the count exactly as a host does.
129
+ *
130
+ * `of S` must stay **narrow**. An `of` argument containing `[popover] *` would filter real
131
+ * descendants out of the sibling count, which is the opposite of the intent.
132
+ */
133
+ const S = ':not(:where([popover], dialog, style, script, template, link, noscript))';
134
+
135
+ /**
136
+ * `X:first-child` → `X:nth-child(1 of S)`
137
+ */
138
+ const NTH_FIRST = ':nth-child(1 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
139
+
140
+ /**
141
+ * `X:last-child` → `X:nth-last-child(1 of S)`
142
+ */
143
+ const NTH_LAST = ':nth-last-child(1 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
144
+
145
+ /**
146
+ * `X:not(:first-child)` → `X:nth-child(n+2 of S)`
147
+ */
148
+ const NTH_NOT_FIRST = ':nth-child(n+2 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
149
+
150
+ /**
151
+ * `X:not(:last-child)` → `X:nth-last-child(n+2 of S)`
152
+ */
153
+ const NTH_NOT_LAST = ':nth-last-child(n+2 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
154
+
155
+ /**
156
+ * `X:only-child` → `X:nth-child(1 of S):not(:where(:nth-last-child(n+2 of S)))`
157
+ *
158
+ * The naive form — `:nth-child(1 of S):nth-last-child(1 of S)` — is (0,2,0) against
159
+ * `:only-child`'s (0,1,0). So is `:nth-child(1 of S):not(:nth-last-child(n+2 of S))`, because
160
+ * `:not()` inherits its argument's weight. Wrapping the negation in `:where()` makes it
161
+ * weightless and brings the pair back to (0,1,0).
162
+ */
163
+ const NTH_ONLY = ':nth-child(1 of :not(:where([popover], dialog, style, script, template, link, noscript))):not(:where(:nth-last-child(n+2 of :not(:where([popover], dialog, style, script, template, link, noscript)))))';
164
+
165
+ /**
166
+ * # The `of S` family is WITHDRAWN — reported, never emitted
167
+ *
168
+ * Every form above stays in this file, and stays literal, because each is correct CSS and each
169
+ * is verified against real Chromium by the harness. None of them is emitted today, because the
170
+ * **build** loses them.
171
+ *
172
+ * `@compiled/react` in `extract: true` mode — platform's `.compiledcssrc`, which every
173
+ * Atlaspack build uses, including `gemini-vr` — writes the atomic class names for a rule whose
174
+ * selector contains `:nth-child(An+B of S)` or `:nth-last-child(An+B of S)` onto the element
175
+ * and **omits the CSS rules themselves**. No warning, no build error: the class is on the
176
+ * element and there is no rule behind it, so the declarations are silently gone.
177
+ *
178
+ * Measured on `@atlaskit/breadcrumbs` by a VR run:
179
+ *
180
+ * | Selector | Rules in page | Matching `::after` rules | `content` |
181
+ * | ----------------------------------------------- | ------------- | ------------------------ | --------- |
182
+ * | `&:not(:last-child)::after` (control) | 325 | 7 | `"/"` |
183
+ * | `&:nth-last-child(n+2 of S)::after` (guard) | 318 | **0** | `none` |
184
+ *
185
+ * 325 − 318 is exactly the seven dropped atomic rules, and every `/` separator disappeared from
186
+ * the page. The trigger is the `of <selector-list>` clause itself, not the guard: `of li` fails
187
+ * identically, and a plain `:nth-last-child(n+2)` survives. Ruled out everywhere else — the
188
+ * selector survives `@compiled/babel-plugin` in non-extract mode, `@compiled/css`'s `sort()`,
189
+ * lightningcss 1.32 at every browser target and with `cssModules` either way, cssnano,
190
+ * postcss-minify-selectors and postcss-selector-parser, and Chromium 143 matches it correctly
191
+ * against the real class list and the real DOM. Only the extract pipeline loses it.
192
+ *
193
+ * So for the positional family the guard does not merely fail to help — **it deletes working
194
+ * styling**. That is the one outcome worse than leaving the site unguarded, and it is why the
195
+ * fix is withheld rather than offered:
196
+ *
197
+ * - a selector that *would* need an `of` clause is refused as `residue` by
198
+ * {@link planPositionals}, so the ESLint rule reports it under `no-guard-form` and offers no
199
+ * autofix, and any bulk caller sharing this module inherits the refusal rather than being free
200
+ * to mass-apply the rewrite;
201
+ * - a selector that *already carries* an `of` clause is refused for the same reason rather than
202
+ * merged or extended, before planning starts in {@link rewriteSelector}. Its CSS is already
203
+ * being dropped in every extract build, so calling it `excluded` ("nothing to do") would
204
+ * assert a safety it does not have.
205
+ *
206
+ * {@link rewriteSelector} also checks its emitted text for an `of` clause as a backstop. Nothing
207
+ * emits one today, so that check firing is a bug in the transform, not a withdrawal.
208
+ *
209
+ * The other ~75% of the debt is unaffected: `> *`, `> div`, `:has()` and the descendant forms
210
+ * emit a plain `:not(:where(…))` with no `of` clause, and those extract normally.
211
+ */
212
+ const WITHDRAWN_POSITIONAL_FORMS = new Map([[':first-child', NTH_FIRST], [':last-child', NTH_LAST], [':only-child', NTH_ONLY], [':not(:first-child)', NTH_NOT_FIRST], [':not(:last-child)', NTH_NOT_LAST]]);
213
+
214
+ /**
215
+ * The term list of the narrow guard, in canonical order. Used when merging.
216
+ */
217
+ const NARROW_TERMS = ['[popover]', 'dialog'];
218
+
219
+ /**
220
+ * The term list of the wide guard, in canonical order. Used when merging.
221
+ */
222
+ const WIDE_TERMS = ['[popover]', 'dialog', '[popover] *', 'dialog *'];
223
+
224
+ /* -------------------------------------------------------------------------------------- */
225
+ /* Public types */
226
+ /* -------------------------------------------------------------------------------------- */
227
+
228
+ /**
229
+ * CSS specificity as `[ids, classes, types]`.
230
+ */
231
+
232
+ /**
233
+ * The rule body belonging to the selector, when the caller has it.
234
+ *
235
+ * Accepts either raw CSS declaration text — the shape the enumeration schema stores in its
236
+ * `declarations` column — or a style object with camelCase or kebab-case keys.
237
+ */
238
+
239
+ /**
240
+ * Where a selector is written, which decides how a branch with no `&` is read.
241
+ */
242
+
243
+ /**
244
+ * Why a selector was skipped rather than decided.
245
+ */
246
+
247
+ /**
248
+ * Why an `excluded` selector still needs a human decision.
249
+ */
250
+
251
+ /* -------------------------------------------------------------------------------------- */
252
+ /* Refusal sets */
253
+ /* -------------------------------------------------------------------------------------- */
254
+
255
+ /**
256
+ * `*-of-type` counts siblings by tag name and accepts no `of S` argument, so its counting
257
+ * cannot be re-based onto real elements. Note that the pre-existing ratcheting rule advises
258
+ * authors to migrate *towards* these; that advice is wrong for top layer.
259
+ */
260
+ const OF_TYPE_PSEUDOS = new Set([':first-of-type', ':last-of-type', ':only-of-type', ':nth-of-type', ':nth-last-of-type']);
261
+
262
+ /**
263
+ * These match an element *and its ancestors*, so the flip exists only while the pointer or
264
+ * focus is inside the surface and there is no guard form at any depth. Inside `:has()` the
265
+ * subject itself satisfies the argument; on a subject compound the element inherits the state
266
+ * from a surface nested inside it.
267
+ */
268
+ const ANCESTOR_PROPAGATING_PSEUDOS = new Set([':hover', ':active', ':focus-within']);
269
+
270
+ /**
271
+ * Positional pseudo-classes that count siblings, and so can be re-based with `of S`.
272
+ */
273
+ const POSITIONAL_PSEUDOS = new Set([':first-child', ':last-child', ':only-child', ':nth-child', ':nth-last-child']);
274
+ const LEGACY_PSEUDO_ELEMENTS = new Set([':before', ':after', ':first-line', ':first-letter']);
275
+
276
+ /**
277
+ * Element types a top layer host can have. The host is either a `<div popover>` or a
278
+ * `<dialog>`; nothing else.
279
+ */
280
+ const HOST_TAGS = new Set(['div', 'dialog']);
281
+
282
+ /**
283
+ * Tag names that appear as terms of `L` or `S`. Used to recognise a pre-existing guard, so a
284
+ * hand-written guard that lists `style` and the rest is still merged into, not doubled.
285
+ */
286
+ const GUARD_TERM_TAGS = new Set(['dialog', 'style', 'script', 'template', 'link', 'noscript']);
287
+
288
+ /**
289
+ * Pseudo-classes and pseudo-elements that only a top layer host can satisfy. A compound
290
+ * carrying one names a host as surely as `dialog` or `[popover]` does, so it is never guarded:
291
+ * every guard form would exclude exactly what the compound selects.
292
+ */
293
+ const HOST_PSEUDOS = new Set([':popover-open', ':modal', '::backdrop']);
294
+
295
+ /**
296
+ * The comparison key for a guard term. Tag and attribute names are ASCII case-insensitive in
297
+ * HTML, so `[POPOVER]` and `DIALOG` are the terms `[popover]` and `dialog`, and a guard spelled
298
+ * in uppercase must be recognised rather than have the lowercase terms merged in beside it.
299
+ */
300
+ const normalise = text => text.replace(/\s+/g, '').toLowerCase();
301
+ const NARROW_TERM_KEYS = new Set(NARROW_TERMS.map(normalise));
302
+ const WIDE_TERM_KEYS = new Set(WIDE_TERMS.map(normalise));
303
+
304
+ /* -------------------------------------------------------------------------------------- */
305
+ /* Public API */
306
+ /* -------------------------------------------------------------------------------------- */
307
+
308
+ /**
309
+ * Rewrite a selector so a top layer host can neither receive its declarations nor displace
310
+ * the real elements it targets.
311
+ *
312
+ * Pure and idempotent: feeding `after` back in yields `guardCount: 0` and `after: null`.
313
+ *
314
+ * @param selector A single selector or a comma-separated selector list. May contain the
315
+ * nesting selector `&`.
316
+ * @param declarations The rule body, if the caller has it. Used for exactly one decision — see
317
+ * {@link findResetSignal}. Omitting it never produces a *wrong* answer, only a lossier one.
318
+ * @param options See {@link RewriteOptions}.
319
+ */
320
+ export function rewriteSelector(selector, declarations, options) {
321
+ var _options$scope;
322
+ const skip = getSkipReason(selector);
323
+ if (skip) {
324
+ return skipped(selector, skip.reason, skip.cause);
325
+ }
326
+ let parsed;
327
+ try {
328
+ parsed = parse(selector);
329
+ } catch {
330
+ return skipped(selector, 'The selector could not be parsed, so it cannot be rewritten safely. This is most likely an authoring mistake.', 'malformed');
331
+ }
332
+ if (parsed.length === 0) {
333
+ return excluded(selector, [0, 0, 0], 'The selector is empty.');
334
+ }
335
+
336
+ /**
337
+ * In a nested context a branch with no `&` is scoped to the component's own element. It is
338
+ * rewritten under its explicit `&` spelling, so it reaches the same verdict, and the prefix is
339
+ * stripped again on the way out so the author's spelling is preserved.
340
+ */
341
+ const scope = (_options$scope = options === null || options === void 0 ? void 0 : options.scope) !== null && _options$scope !== void 0 ? _options$scope : 'global';
342
+ const scoped = applyScope(parsed, scope);
343
+ if (scoped === null) {
344
+ return skipped(selector, 'The selector could not be re-parsed under its nesting scope, so it cannot be rewritten safely.', 'malformed');
345
+ }
346
+ const {
347
+ branches,
348
+ prefixes
349
+ } = scoped;
350
+ const specificityBranchesBefore = branches.map(specificityOfSelector);
351
+ const specificityBefore = maxSpecificity(specificityBranchesBefore);
352
+
353
+ /**
354
+ * A bare universal at global scope. **The one class where guarding is actively harmful rather
355
+ * than merely useless**, so it is decided before anything else.
356
+ *
357
+ * `* { box-sizing: inherit }` is a reset. Guarding it excludes the host from the reset and
358
+ * makes it the only element in the document with a different box model — a layout bug
359
+ * introduced by the fix, with nothing to compensate, because the host surface reset covers
360
+ * text-layout properties and not the box model.
361
+ *
362
+ * `* { cursor: col-resize }` is an override with identical selector text, and it does need the
363
+ * guard. The selector cannot tell them apart, so this is a judgement call about the rule body.
364
+ *
365
+ * Note this is *not* the property-effect filter. That filter is about declarations that are
366
+ * inert on a `position: fixed` host (`flex`, `order`, `z-index`, …). Here the declaration is
367
+ * live on the host and *wanted* there.
368
+ */
369
+ if (branches.some(isBareGlobalUniversal)) {
370
+ const reset = findResetSignal(declarations);
371
+ if (reset) {
372
+ return excluded(selector, specificityBefore, `A bare universal selector at global scope carrying '${reset}', which is reset-shaped rather than an override. Guarding it would exclude the top layer host from the reset and leave it the only element in the document with different inherited defaults — a layout bug introduced by the fix. Left alone deliberately.`);
373
+ }
374
+ return residue(selector, specificityBefore, "A bare universal selector at global scope. Whether this needs the guard depends on the rule body, which the selector cannot reveal: `* { box-sizing: inherit }` is a reset and guarding it would exclude the host from the reset — a layout bug introduced by the fix — while `* { cursor: col-resize }` is an override and does need it. Decide from the declarations. A *scoped* universal ('& > *', '.foo > *') is unaffected and is rewritten normally.");
375
+ }
376
+
377
+ /**
378
+ * **Input gate for the `of S` withdrawal** — see {@link WITHDRAWN_POSITIONAL_FORMS}.
379
+ *
380
+ * A selector that already carries an `of` argument is emitting no CSS at all in an extract
381
+ * build, whichever list it carries and whoever wrote it. Refusing it here reports it for
382
+ * triage instead of merging its terms up to the canonical seven — a merge would leave the
383
+ * site exactly as dead as it was, while reading in review as a fix.
384
+ *
385
+ * This covers both a partial guard in the `of` list and an unrelated `of` list; neither is
386
+ * merged.
387
+ */
388
+ for (const branch of branches) {
389
+ const existing = findOfClause(branch);
390
+ if (existing) {
391
+ return residue(selector, specificityBefore, ofClausePresentReason(existing));
392
+ }
393
+ }
394
+ const plan = createPlan();
395
+ for (const branch of branches) {
396
+ planBranch(branch, plan, scope);
397
+ }
398
+
399
+ /**
400
+ * A hard refusal stands whether or not anything else in the selector is guardable.
401
+ * Refusing the whole selector — rather than rewriting the parts that do have a guard form
402
+ * — is deliberate. A partially rewritten selector reads as fixed and is not, which is the
403
+ * worst outcome available here.
404
+ */
405
+ if (plan.hardRefusals.length > 0) {
406
+ return residue(selector, specificityBefore, plan.hardRefusals[0]);
407
+ }
408
+
409
+ /**
410
+ * A compound the transform declined to decide hands the whole selector to a human. Guards
411
+ * that would have been written on its other compounds are withheld too: a partially
412
+ * rewritten selector next to a review comment would read as fixed.
413
+ */
414
+ if (plan.reviews.length > 0) {
415
+ return review(selector, specificityBefore, plan.reviews[0]);
416
+ }
417
+ if (plan.guardCount === 0) {
418
+ var _ref, _plan$softRefusals$;
419
+ /**
420
+ * Nothing needed writing. A soft refusal only matters when a guard would otherwise have
421
+ * been written next to it, because that is the case where the result would read as
422
+ * fixed. On its own it is reported but not queued for triage.
423
+ */
424
+ const why = (_ref = (_plan$softRefusals$ = plan.softRefusals[0]) !== null && _plan$softRefusals$ !== void 0 ? _plan$softRefusals$ : plan.reachSuppressions[0]) !== null && _ref !== void 0 ? _ref : plan.sawGeneralSibling ? 'The general sibling combinator is insensitive to insertion — a host inserted between siblings removes no real match — and no compound this selector matches can be a host. Already safe.' : 'No top layer host can be, contain, or displace any element this selector matches.';
425
+ if (plan.sawGeneralSibling && plan.softRefusals.length === 0 && plan.reachSuppressions.length === 0) {
426
+ return {
427
+ before: selector,
428
+ after: null,
429
+ population: 'guardable',
430
+ damageModes: [],
431
+ guardCount: 0,
432
+ reason: why,
433
+ specificityBefore,
434
+ specificityAfter: specificityBefore
435
+ };
436
+ }
437
+ return excluded(selector, specificityBefore, why);
438
+ }
439
+ if (plan.softRefusals.length > 0) {
440
+ return residue(selector, specificityBefore, plan.softRefusals[0]);
441
+ }
442
+ const emitted = branches.map((branch, index) => stripScopePrefix(emitSelector(branch, plan), prefixes[index]));
443
+ if (emitted.some(branch => branch === null)) {
444
+ return residue(selector, specificityBefore, 'The rewritten selector lost its implicit nesting prefix, so it was not emitted. This is a bug in the transform — please report it.');
445
+ }
446
+ const after = emitted.join(', ');
447
+
448
+ /**
449
+ * A bracket-level sanity check on the emitted text before anything downstream writes it to
450
+ * a file. `postcss-selector-parser` is lenient, so this catches a class of malformed output
451
+ * that would otherwise round-trip.
452
+ */
453
+ if (!isBalanced(after)) {
454
+ return residue(selector, specificityBefore, 'The rewritten selector does not have balanced brackets, so it was not emitted. This is a bug in the transform — please report it.');
455
+ }
456
+
457
+ /**
458
+ * Chromium rejects an entire selector containing a `:has()` inside a `:has()` argument,
459
+ * which silently stops the rule applying at all. Nothing in the guard forms contains a
460
+ * `:has()`, but verify rather than assume — this failure mode looks like a fix and
461
+ * disables the rule.
462
+ */
463
+ let afterBranches;
464
+ try {
465
+ afterBranches = parse(after);
466
+ } catch {
467
+ return residue(selector, specificityBefore, 'The rewritten selector could not be re-parsed, so it could not be verified.');
468
+ }
469
+
470
+ /**
471
+ * Backstop for the `of S` withdrawal — see {@link WITHDRAWN_POSITIONAL_FORMS}. The planner
472
+ * refuses every positional pseudo in {@link planPositionals}, so nothing reaching this point
473
+ * should carry an `of` clause. Checked on the emitted text so a future emit site cannot
474
+ * slip one past the planner.
475
+ */
476
+ for (const branch of afterBranches) {
477
+ if (findOfClause(branch)) {
478
+ return residue(selector, specificityBefore, `The rewrite would emit an \`of\` clause, which is withdrawn. ${EXTRACT_DEFECT} This is a bug in the transform — please report it.`);
479
+ }
480
+ }
481
+ for (const branch of afterBranches) {
482
+ if (hasNestedHas(branch)) {
483
+ return residue(selector, specificityBefore, 'The rewrite would produce a `:has()` nested inside a `:has()` argument, which Chromium rejects outright — the whole rule would silently stop applying.');
484
+ }
485
+ }
486
+
487
+ /**
488
+ * Structural specificity check. `:where()` being weightless, `:not()` inheriting its
489
+ * argument's weight, and `of S` contributing only the pseudo-class are all load-bearing —
490
+ * so verify, branch by branch, on the emitted text.
491
+ */
492
+ const specificityBranchesAfter = afterBranches.map(specificityOfSelector);
493
+ if (specificityBranchesAfter.length !== specificityBranchesBefore.length) {
494
+ return residue(selector, specificityBefore, 'The rewrite changed the number of selectors in the list, so it could not be verified.');
495
+ }
496
+ for (let index = 0; index < specificityBranchesBefore.length; index++) {
497
+ const from = specificityBranchesBefore[index];
498
+ const to = specificityBranchesAfter[index];
499
+ if (!sameSpecificity(from, to)) {
500
+ return residue(selector, specificityBefore, `The rewrite would change specificity from (${from.join(',')}) to (${to.join(',')}) for '${branches[index].toString().trim()}'. Every guard form must be specificity-neutral.`);
501
+ }
502
+ }
503
+ const damageModes = [];
504
+ if (plan.receives) {
505
+ damageModes.push('popover-receives');
506
+ }
507
+ const result = {
508
+ before: selector,
509
+ after,
510
+ population: 'guardable',
511
+ damageModes,
512
+ guardCount: plan.guardCount,
513
+ specificityBefore,
514
+ specificityAfter: maxSpecificity(specificityBranchesAfter)
515
+ };
516
+ if (plan.residualNotes.length > 0) {
517
+ result.reason = plan.residualNotes[0];
518
+ }
519
+ return result;
520
+ }
521
+
522
+ /* -------------------------------------------------------------------------------------- */
523
+ /* Result constructors */
524
+ /* -------------------------------------------------------------------------------------- */
525
+
526
+ function skipped(before, reason, cause) {
527
+ return {
528
+ before,
529
+ after: null,
530
+ population: 'skipped',
531
+ damageModes: [],
532
+ guardCount: 0,
533
+ reason,
534
+ skipCause: cause,
535
+ specificityBefore: [0, 0, 0],
536
+ specificityAfter: [0, 0, 0]
537
+ };
538
+ }
539
+ function residue(before, specificity, reason) {
540
+ return {
541
+ before,
542
+ after: null,
543
+ population: 'residue',
544
+ damageModes: [],
545
+ guardCount: 0,
546
+ reason,
547
+ specificityBefore: specificity,
548
+ specificityAfter: specificity
549
+ };
550
+ }
551
+ function excluded(before, specificity, reason) {
552
+ return {
553
+ before,
554
+ after: null,
555
+ population: 'excluded',
556
+ damageModes: [],
557
+ guardCount: 0,
558
+ reason,
559
+ specificityBefore: specificity,
560
+ specificityAfter: specificity
561
+ };
562
+ }
563
+ function review(before, specificity, reason) {
564
+ return {
565
+ ...excluded(before, specificity, reason),
566
+ reviewCause: 'div-ancestor'
567
+ };
568
+ }
569
+
570
+ /* -------------------------------------------------------------------------------------- */
571
+ /* Nesting scope */
572
+ /* -------------------------------------------------------------------------------------- */
573
+
574
+ /**
575
+ * Under `nested` scope, spell out the `&` the authoring API implies for every branch that has
576
+ * none, then re-parse. Under `global` scope the branches are returned untouched.
577
+ *
578
+ * The prefix is text rather than a synthetic AST node so the branch takes exactly the code path
579
+ * its explicit `&` spelling takes; nothing downstream needs to know the `&` was implied.
580
+ */
581
+ function applyScope(branches, scope) {
582
+ if (scope === 'global') {
583
+ return {
584
+ branches,
585
+ prefixes: branches.map(() => null)
586
+ };
587
+ }
588
+ const prefixes = branches.map(implicitNestingPrefix);
589
+ if (prefixes.every(prefix => prefix === null)) {
590
+ return {
591
+ branches,
592
+ prefixes
593
+ };
594
+ }
595
+ const text = branches.map((branch, index) => {
596
+ var _prefixes$index;
597
+ return `${(_prefixes$index = prefixes[index]) !== null && _prefixes$index !== void 0 ? _prefixes$index : ''}${branch.toString().trim()}`;
598
+ }).join(', ');
599
+ try {
600
+ const reparsed = parse(text);
601
+ if (reparsed.length !== branches.length) {
602
+ return null;
603
+ }
604
+ return {
605
+ branches: reparsed,
606
+ prefixes
607
+ };
608
+ } catch {
609
+ return null;
610
+ }
611
+ }
612
+
613
+ /**
614
+ * The `&` a nested authoring API prepends to a branch with no `&` of its own. A branch that
615
+ * opens with a pseudo attaches to the parent compound (`:hover` is `&:hover`); anything else is
616
+ * a descendant (`span` is `& span`, `> *` is `& > *`).
617
+ */
618
+ function implicitNestingPrefix(branch) {
619
+ let hasNesting = false;
620
+ branch.walk(node => {
621
+ if (node.type === 'nesting') {
622
+ hasNesting = true;
623
+ }
624
+ });
625
+ if (hasNesting) {
626
+ return null;
627
+ }
628
+ const first = nonEmptyNodes(branch)[0];
629
+ if (!first) {
630
+ return null;
631
+ }
632
+ if (first.type === 'pseudo') {
633
+ return '&';
634
+ }
635
+ return '& ';
636
+ }
637
+
638
+ /**
639
+ * Remove the prefix {@link applyScope} added. The `&` compound is never guarded or replaced, so
640
+ * the emitted branch always opens with it; `null` if it does not, which is a transform bug.
641
+ */
642
+ function stripScopePrefix(emitted, prefix) {
643
+ if (prefix === null) {
644
+ return emitted;
645
+ }
646
+ if (!emitted.startsWith(prefix)) {
647
+ return null;
648
+ }
649
+ return emitted.slice(prefix.length);
650
+ }
651
+
652
+ /* -------------------------------------------------------------------------------------- */
653
+ /* The `of S` withdrawal — see WITHDRAWN_POSITIONAL_FORMS */
654
+ /* -------------------------------------------------------------------------------------- */
655
+
656
+ /**
657
+ * The defect, stated once for the refusal reasons, so a developer reading the squiggle learns
658
+ * why the fix is missing rather than only that it is. The measurement behind it lives in the
659
+ * {@link WITHDRAWN_POSITIONAL_FORMS} docblock.
660
+ */
661
+ const EXTRACT_DEFECT = '`@compiled/react` in `extract: true` mode, which every Atlaspack build uses, emits the atomic class names for a rule whose selector carries an `of` argument but omits the CSS rules themselves. There is no warning and no build error, so the declarations are silently lost.';
662
+
663
+ /**
664
+ * Lowercased pseudo-class name. CSS pseudo-class names are ASCII case-insensitive, so every
665
+ * decision keyed on a name must normalise first: `:NTH-CHILD(1 of .foo)` is the same selector
666
+ * as `:nth-child(1 of .foo)` and must reach the same verdict.
667
+ */
668
+ function pseudoName(node) {
669
+ var _node$value;
670
+ return ((_node$value = node.value) !== null && _node$value !== void 0 ? _node$value : '').toLowerCase();
671
+ }
672
+
673
+ /**
674
+ * Find a `:nth-child()` / `:nth-last-child()` carrying an `of` argument, at any depth —
675
+ * including inside a `:has()`, `:is()`, `:where()` or `:not()` argument.
676
+ */
677
+ function findOfClause(branch) {
678
+ var _found$;
679
+ const found = [];
680
+ branch.walkPseudos(pseudo => {
681
+ const name = pseudoName(pseudo);
682
+ if (name !== ':nth-child' && name !== ':nth-last-child') {
683
+ return;
684
+ }
685
+ if (findOfKeyword(nthArgumentText(pseudo)) === -1) {
686
+ return;
687
+ }
688
+ found.push(pseudo);
689
+ });
690
+ return (_found$ = found[0]) !== null && _found$ !== void 0 ? _found$ : null;
691
+ }
692
+
693
+ /**
694
+ * The guard form that would have been emitted for a positional pseudo-class, spelled with `S`
695
+ * rather than the seven terms so the report stays readable. `null` when this pseudo is not one
696
+ * of the positional family.
697
+ */
698
+ function withdrawnFormFor(pseudo) {
699
+ const name = pseudoName(pseudo);
700
+ if (name === ':nth-child' || name === ':nth-last-child') {
701
+ return `${name}(${nthArgumentText(pseudo).trim()} of S)`;
702
+ }
703
+ if (name === ':not') {
704
+ const sole = solePseudoInside(pseudo);
705
+ const form = sole ? WITHDRAWN_POSITIONAL_FORMS.get(`:not(${pseudoName(sole)})`) : undefined;
706
+ return form ? abbreviate(form) : null;
707
+ }
708
+ const form = WITHDRAWN_POSITIONAL_FORMS.get(name);
709
+ return form ? abbreviate(form) : null;
710
+ }
711
+
712
+ /**
713
+ * Collapse the seven-term list back to `S`. The literal is what gets *written*; `S` is what
714
+ * gets *read*.
715
+ */
716
+ function abbreviate(form) {
717
+ return form.split(S).join('S');
718
+ }
719
+
720
+ /**
721
+ * Why a rewrite that needs an `of` clause is withheld. Names the pseudo-class and the form that
722
+ * would have been emitted for it, so the report is specific about what was withdrawn.
723
+ */
724
+ function ofClauseWithheldReason(pseudo) {
725
+ const form = withdrawnFormFor(pseudo);
726
+ const name = pseudoName(pseudo) === ':not' ? pseudo.toString().trim() : pseudo.value;
727
+ const subject = form ? `'${name}' can only be re-based onto real elements as \`${form}\`` : `'${name}' can only be re-based onto real elements with an \`of S\` clause`;
728
+ return `${subject}, and that form is currently withdrawn. ${EXTRACT_DEFECT} Applying the guard here would therefore delete this rule's styling rather than protect it — the one outcome worse than leaving the selector unguarded — so it is reported without a fix. Close the site another way: give the elements you actually mean a class or a \`data-\` attribute and select them directly. \`S = :not(:where([popover], dialog, style, script, template, link, noscript))\`.`;
729
+ }
730
+
731
+ /**
732
+ * Why a selector that *already* carries an `of` clause is refused rather than merged into the
733
+ * canonical list, or reported as already safe.
734
+ */
735
+ function ofClausePresentReason(pseudo) {
736
+ return `'${pseudo.value}' already carries an \`of\` argument, and any \`of\` argument is currently unsafe to ship. ${EXTRACT_DEFECT} This rule is therefore already dead in every extract build, whatever the \`of\` list contains — so the list is neither merged up to the canonical seven terms nor reported as safe. Revert it to a plain selector and close the site another way, or leave it for the owning team; two unrelated \`of\` lists could not have been combined into one specificity-neutral term anyway.`;
737
+ }
738
+
739
+ /* -------------------------------------------------------------------------------------- */
740
+ /* Skip detection — skip, never guess */
741
+ /* -------------------------------------------------------------------------------------- */
742
+
743
+ /**
744
+ * Statically detect a selector whose text is not fully known, or which is not a complete
745
+ * selector at all. Guessing at these is strictly worse than reporting them, because a guard
746
+ * inserted at the wrong end of an interpolation silently changes what the rule matches.
747
+ */
748
+ function getSkipReason(selector) {
749
+ if (selector.trim() === '') {
750
+ return {
751
+ cause: 'malformed',
752
+ reason: 'The selector is empty.'
753
+ };
754
+ }
755
+ if (/:has\([^)]*\$\{/.test(selector)) {
756
+ return {
757
+ cause: 'dynamic',
758
+ reason: 'The `:has()` argument contains a template-literal interpolation, so the branch structure inside it is not statically known. Skipped rather than guessed at.'
759
+ };
760
+ }
761
+ if (selector.includes('${')) {
762
+ return {
763
+ cause: 'dynamic',
764
+ reason: 'The selector contains a template-literal interpolation, so its full text is not statically known. Skipped rather than guessed at.'
765
+ };
766
+ }
767
+ if (selector.includes('#{')) {
768
+ return {
769
+ cause: 'dynamic',
770
+ reason: 'The selector contains a preprocessor interpolation, so its full text is not statically known. Skipped rather than guessed at.'
771
+ };
772
+ }
773
+ if (!isBalanced(selector)) {
774
+ return {
775
+ cause: 'malformed',
776
+ reason: 'The selector has an unterminated argument — its brackets or parentheses do not balance, so it spans more than the text given and cannot be parsed in isolation.'
777
+ };
778
+ }
779
+ return null;
780
+ }
781
+ function isBalanced(selector) {
782
+ let parens = 0;
783
+ let brackets = 0;
784
+ let quote = null;
785
+ for (let index = 0; index < selector.length; index++) {
786
+ const character = selector[index];
787
+ if (quote) {
788
+ if (character === '\\') {
789
+ index++;
790
+ } else if (character === quote) {
791
+ quote = null;
792
+ }
793
+ continue;
794
+ }
795
+ switch (character) {
796
+ case '"':
797
+ case "'":
798
+ quote = character;
799
+ break;
800
+ case '(':
801
+ parens++;
802
+ break;
803
+ case ')':
804
+ parens--;
805
+ break;
806
+ case '[':
807
+ brackets++;
808
+ break;
809
+ case ']':
810
+ brackets--;
811
+ break;
812
+ default:
813
+ break;
814
+ }
815
+ if (parens < 0 || brackets < 0) {
816
+ return false;
817
+ }
818
+ }
819
+ return parens === 0 && brackets === 0 && quote === null;
820
+ }
821
+
822
+ /* -------------------------------------------------------------------------------------- */
823
+ /* Parsing and compounds */
824
+ /* -------------------------------------------------------------------------------------- */
825
+
826
+ function parse(selector) {
827
+ const root = selectorParser().astSync(selector);
828
+ return root.nodes.filter(branch => nonEmptyNodes(branch).length > 0);
829
+ }
830
+ function nonEmptyNodes(container) {
831
+ return container.nodes.filter(node => !(node.type === 'string' && node.value.trim() === ''));
832
+ }
833
+ function positionOf(combinator) {
834
+ if (combinator === null) {
835
+ return 'first';
836
+ }
837
+ switch (combinator.value.trim()) {
838
+ case '':
839
+ return 'descendant';
840
+ case '>':
841
+ return 'child';
842
+ case '+':
843
+ return 'adjacent';
844
+ case '~':
845
+ return 'general';
846
+ default:
847
+ return 'descendant';
848
+ }
849
+ }
850
+ function splitCompounds(branch) {
851
+ const raw = [];
852
+ let current = {
853
+ nodes: [],
854
+ combinatorBefore: null
855
+ };
856
+ for (const node of branch.nodes) {
857
+ if (node.type === 'combinator') {
858
+ raw.push(current);
859
+ current = {
860
+ nodes: [],
861
+ combinatorBefore: node
862
+ };
863
+ } else {
864
+ current.nodes.push(node);
865
+ }
866
+ }
867
+ raw.push(current);
868
+ const kept = raw.filter(compound => compound.nodes.length > 0);
869
+ return kept.map((compound, index) => ({
870
+ nodes: compound.nodes,
871
+ combinatorBefore: compound.combinatorBefore,
872
+ position: positionOf(compound.combinatorBefore),
873
+ isSubject: index === kept.length - 1
874
+ }));
875
+ }
876
+
877
+ /* -------------------------------------------------------------------------------------- */
878
+ /* Trap 2 — the host-satisfiability predicate */
879
+ /* -------------------------------------------------------------------------------------- */
880
+
881
+ /**
882
+ * **This is the single predicate behind trap 2.** `& > div > div` needs two guards because
883
+ * both compounds satisfy it; `& > div > span` needs exactly one because `span` does not. The
884
+ * rule "guard every compound this returns true for, not just the rightmost" lives here and
885
+ * nowhere else, so it can be swapped wholesale if the Chromium verification of trap 2 comes
886
+ * back negative.
887
+ *
888
+ * Could a top layer host *be* the element this compound matches?
889
+ *
890
+ * A host is a `<div popover>` or a `<dialog>` rendered by Design System. So:
891
+ * - an explicit tag other than `div` / `dialog` proves it cannot — no host is a `<span>`;
892
+ * - a class or an id proves it cannot, because those are the consumer's own hooks and are not
893
+ * on the host. A consumer who deliberately puts their own class on a surface — via
894
+ * `className` / `xcss` — has targeted it on purpose, which the decision doc treats as the
895
+ * consumer's call rather than something to guard;
896
+ * - the nesting selector `&` proves it cannot, because `&` is the author's own element — and so
897
+ * does an `:is()` / `:where()` that resolves the same way, see {@link nestedMatchVerdict};
898
+ * - everything else — `*`, attribute-only, pseudo-only — could, so it is guarded.
899
+ */
900
+ function couldHostMatch(nodes) {
901
+ for (const node of nodes) {
902
+ switch (node.type) {
903
+ case 'nesting':
904
+ case 'class':
905
+ case 'id':
906
+ return false;
907
+ default:
908
+ break;
909
+ }
910
+ }
911
+ if (nestedMatchVerdictOf(nodes) === 'none') {
912
+ return false;
913
+ }
914
+ const tag = tagOf(nodes);
915
+ return tag === null || HOST_TAGS.has(tag);
916
+ }
917
+
918
+ /**
919
+ * Pseudo-classes that match an element when any one of their arguments does, so the element is
920
+ * whatever the arguments' subjects are. `:not()` is deliberately absent: `:not(&)` matches every
921
+ * element *except* the author's own, which is the opposite of ownership, so a `:not()` carrying
922
+ * `&` is read like any other pseudo-only compound and guarded.
923
+ */
924
+ const MATCHES_ANY_PSEUDOS = new Set([':is', ':where', ':matches', ':-webkit-any', ':-moz-any']);
925
+
926
+ /**
927
+ * What a compound's `:is(…&…)` / `:where(…&…)` argument says about the element it matches.
928
+ *
929
+ * `:is(&) > div` is `& > div` spelled differently, and `:is(& > span)` is `& > span`. Without
930
+ * this the `&` sits one level down, where {@link couldHostMatch} cannot see it, and the compound
931
+ * is guarded as if it were a bare pseudo: the author's own element picks up a wide guard and the
932
+ * rule stops applying inside every surface.
933
+ *
934
+ * - `none` — no argument's subject can be a host or sit inside somebody else's surface: every
935
+ * argument is a lone `&`, class or id compound, or `& > X` where no host can be `X`;
936
+ * - `narrow` — some argument is `& > X` where a host can be `X`, as `& > div` is;
937
+ * - `wide` — some argument is `& X`, whose `X` is always guarded, as in descendant position;
938
+ * - `null` — no such argument, or one shaped otherwise, which keeps the ordinary reading.
939
+ */
940
+
941
+ function nestedMatchVerdictOf(nodes) {
942
+ let verdict = null;
943
+ for (const node of nodes) {
944
+ const next = nestedMatchVerdict(node);
945
+ if (next !== null && (verdict === null || rankOf(next) > rankOf(verdict))) {
946
+ verdict = next;
947
+ }
948
+ }
949
+ return verdict;
950
+ }
951
+ function nestedMatchVerdict(node) {
952
+ if (node.type !== 'pseudo' || !MATCHES_ANY_PSEUDOS.has(pseudoName(node))) {
953
+ return null;
954
+ }
955
+ let hasNesting = false;
956
+ node.walk(inner => {
957
+ if (inner.type === 'nesting') {
958
+ hasNesting = true;
959
+ }
960
+ });
961
+ if (!hasNesting) {
962
+ return null;
963
+ }
964
+ let verdict = 'none';
965
+ for (const argument of node.nodes) {
966
+ const next = argumentVerdict(argument);
967
+ if (next === null) {
968
+ return null;
969
+ }
970
+ if (rankOf(next) > rankOf(verdict)) {
971
+ verdict = next;
972
+ }
973
+ }
974
+ return verdict;
975
+ }
976
+ function argumentVerdict(argument) {
977
+ const compounds = splitCompounds(argument);
978
+ if (compounds.length === 1) {
979
+ return couldMatchForeignElement(compounds[0].nodes) ? null : 'none';
980
+ }
981
+ const [owner, subject] = compounds;
982
+ const ownerIsNesting = owner.nodes.some(node => node.type === 'nesting');
983
+ if (compounds.length !== 2 || !ownerIsNesting) {
984
+ return null;
985
+ }
986
+ switch (subject.position) {
987
+ case 'child':
988
+ return couldHostMatch(subject.nodes) ? 'narrow' : 'none';
989
+ case 'descendant':
990
+ return 'wide';
991
+ default:
992
+ return null;
993
+ }
994
+ }
995
+ function rankOf(verdict) {
996
+ return verdict === 'none' ? 0 : verdict === 'narrow' ? 1 : 2;
997
+ }
998
+
999
+ /**
1000
+ * There used to be a `couldHostShareType` predicate here, gating the of-type refusal on whether a
1001
+ * host could carry the compound's tag — so `& > span:nth-of-type(2)` was treated as safe.
1002
+ *
1003
+ * It is gone deliberately. The of-type family has no guard form at all, and the gate meant that in
1004
+ * descendant position, where guards are unconditional, of-type selectors were being guarded anyway:
1005
+ * 18 measured pairs across 8 selectors. The family is now refused outright by
1006
+ * {@link planWholeBranchRefusals}, whatever its tag.
1007
+ */
1008
+
1009
+ /**
1010
+ * Could this compound match an element that is not the author's own — that is, Design System
1011
+ * internals, or content belonging to somebody else?
1012
+ *
1013
+ * This is the **ownership question**, and it is the real discriminator between the two guard
1014
+ * forms. A class or an id answers "no": those only ever match elements the author wrote, so if
1015
+ * such an element is inside a surface it is inside *the author's own* surface content.
1016
+ * `[popover] *` and `dialog *` would then remove a style the author put there on purpose.
1017
+ *
1018
+ * `*`, a bare tag, and an attribute-only compound answer "yes": each can match a DS-internal
1019
+ * element rendered inside somebody else's surface.
1020
+ */
1021
+ function couldMatchForeignElement(nodes) {
1022
+ for (const node of nodes) {
1023
+ switch (node.type) {
1024
+ case 'nesting':
1025
+ case 'class':
1026
+ case 'id':
1027
+ return false;
1028
+ default:
1029
+ break;
1030
+ }
1031
+ }
1032
+ const nested = nestedMatchVerdictOf(nodes);
1033
+ return nested === null || nested === 'wide';
1034
+ }
1035
+
1036
+ /**
1037
+ * Narrow or wide, for one compound. **The single place this choice is made.**
1038
+ *
1039
+ * The subtree terms `[popover] <universal>` and `dialog <universal>` do not mean "not the host's
1040
+ * subtree". They mean **"not inside ANY surface"** — so a wide guard disables its own rule for
1041
+ * any subject that legitimately lives inside a popover, dialog or drawer. Consumer content
1042
+ * inside a surface is the common case, not an edge case, which is why wide is NOT the safe
1043
+ * default.
1044
+ *
1045
+ * The governing rule, from the decision doc:
1046
+ *
1047
+ * > Wide when the matched element could be inside someone *else's* surface. Narrow when it
1048
+ * > could be inside the subject's *own* surface. Where both are possible, the site is residue.
1049
+ *
1050
+ * Operationally that turns on whether a surface can sit **strictly between** the previous
1051
+ * compound and this one:
1052
+ *
1053
+ * - **descendant** — the gap is unbounded, so a surface can sit inside the previous compound
1054
+ * and above this one. That surface is somebody else's, and its internals match here. Wide.
1055
+ * - **child, adjacent, general** — there is no gap. The only exposure is "this element *is*
1056
+ * the host", which narrow already closes. Wide would buy nothing and would additionally
1057
+ * break the case where the whole selector is rendered inside a surface — then the previous
1058
+ * compound's own real child *is* `[popover] *`. Narrow, always. This is what
1059
+ * `.x:has(> div)` measured.
1060
+ * - **first** — there is no previous compound, so the gap question does not arise and the
1061
+ * ownership question is asked directly, via {@link couldMatchForeignElement}. At global
1062
+ * scope a first compound is never given a *fresh* guard, because with nothing above it the
1063
+ * rule reached the portalled surface before the flag (see {@link isDocumentLevelCompound});
1064
+ * the form still decides which list a pre-existing partial guard is merged up to.
1065
+ */
1066
+ function guardFormFor(compound) {
1067
+ switch (compound.position) {
1068
+ case 'descendant':
1069
+ return 'wide';
1070
+ case 'first':
1071
+ return couldMatchForeignElement(compound.nodes) ? 'wide' : 'narrow';
1072
+ default:
1073
+ return 'narrow';
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * Is this branch a bare universal selector at global scope — `*`, `*::before`, `*::after`?
1079
+ *
1080
+ * "Bare" means the compound is nothing but the universal selector, optionally with a
1081
+ * pseudo-element. "Global scope" means there is no ancestor constraint at all, so the rule reaches
1082
+ * every element in the document including a top layer host.
1083
+ *
1084
+ * Deliberately narrow, so it cannot over-fire:
1085
+ * - `& > *`, `.foo > *`, `& *`, `& > *:first-child` all have an ancestor constraint and are
1086
+ * rewritten normally;
1087
+ * - `*:first-child` is not bare — the pseudo-class makes it a positional rule, not a reset — and is
1088
+ * rewritten normally;
1089
+ * - `> *` is the nested spelling of `& > *`, so it is scoped too.
1090
+ *
1091
+ * ## Why this is not wider — the question every reader asks
1092
+ *
1093
+ * A *scoped* reset looks like it shares the mechanism: guarding `& > div { box-sizing: inherit }`
1094
+ * also excludes the host from a reset. It does not, and the reason is **reach**, not the property:
1095
+ *
1096
+ * - global `* { box-sizing: inherit }` matched the host **before** the flag too, because `*`
1097
+ * reaches surface content sitting in a portal at `body` level. Guarding it *removes* something
1098
+ * the host already had — a behaviour change, and the layout bug;
1099
+ * - scoped `& > * { box-sizing: inherit }` did **not** match the host pre-flag, because the host
1100
+ * was portalled away and was not a child of `&`. Post-flag it does. That is exactly the
1101
+ * `popover-receives` damage, and guarding *restores* the pre-flag rendering.
1102
+ *
1103
+ * Same declaration, opposite dispositions. This is also why no browser measurement can settle it:
1104
+ * a browser can say what `box-sizing` does, but not what the DOM looked like before the flag.
1105
+ */
1106
+ function isBareGlobalUniversal(branch) {
1107
+ const compounds = splitCompounds(branch);
1108
+ if (compounds.length !== 1) {
1109
+ return false;
1110
+ }
1111
+ const [compound] = compounds;
1112
+ if (compound.position !== 'first') {
1113
+ return false;
1114
+ }
1115
+ let sawUniversal = false;
1116
+ for (const node of compound.nodes) {
1117
+ if (node.type === 'universal') {
1118
+ sawUniversal = true;
1119
+ continue;
1120
+ }
1121
+ if (isPseudoElement(node)) {
1122
+ continue;
1123
+ }
1124
+ return false;
1125
+ }
1126
+ return sawUniversal;
1127
+ }
1128
+
1129
+ /**
1130
+ * Declarations that mark a rule as a **reset** rather than an override, meaning a guard would take
1131
+ * the declaration away from the host and break it.
1132
+ *
1133
+ * Deliberately minimal — only signals that are unambiguous on their face:
1134
+ * - `box-sizing`, the canonical global reset and the measured case;
1135
+ * - any of the cascade keywords, whose whole purpose is to normalise inherited values.
1136
+ *
1137
+ * The asymmetry here is the point, and it is why this is safe to act on automatically. Wrongly
1138
+ * calling an override a reset leaves a `popover-receives` exposure on a bare `*` rule, which is
1139
+ * cheap. Wrongly calling a reset an override *introduces* a layout bug, which is not. So this
1140
+ * function only ever moves a row **out** of the guarded set, and a row it does not recognise stays
1141
+ * `residue` for a human rather than being guarded on a guess.
1142
+ */
1143
+ function findResetSignal(declarations) {
1144
+ if (!declarations) {
1145
+ return null;
1146
+ }
1147
+ const pairs = typeof declarations === 'string' ? parseDeclarationText(declarations) : Object.entries(declarations).map(([property, value]) => [property, String(value !== null && value !== void 0 ? value : '')]);
1148
+ for (const [rawProperty, rawValue] of pairs) {
1149
+ const property = kebabCase(rawProperty).toLowerCase();
1150
+ const value = rawValue.trim().toLowerCase();
1151
+ if (property === 'box-sizing') {
1152
+ return `${property}: ${value}`;
1153
+ }
1154
+ if (CASCADE_KEYWORDS.has(value)) {
1155
+ return `${property}: ${value}`;
1156
+ }
1157
+ }
1158
+ return null;
1159
+ }
1160
+ const CASCADE_KEYWORDS = new Set(['inherit', 'initial', 'unset', 'revert', 'revert-layer']);
1161
+ function parseDeclarationText(text) {
1162
+ const pairs = [];
1163
+ for (const part of text.split(';')) {
1164
+ const colon = part.indexOf(':');
1165
+ if (colon === -1) {
1166
+ continue;
1167
+ }
1168
+ const property = part.slice(0, colon).trim();
1169
+ const value = part.slice(colon + 1).trim();
1170
+ if (property !== '') {
1171
+ pairs.push([property, value]);
1172
+ }
1173
+ }
1174
+ return pairs;
1175
+ }
1176
+ function kebabCase(property) {
1177
+ return property.replace(/[A-Z]/g, character => `-${character.toLowerCase()}`);
1178
+ }
1179
+
1180
+ /**
1181
+ * Does this compound name a top layer host or a non-rendered tag outright, such as `dialog`?
1182
+ *
1183
+ * Then the author is targeting that element deliberately. For a host, **both** guard forms
1184
+ * would make the rule match nothing at all, because the guard's own term list excludes exactly
1185
+ * what the compound selects. A non-rendered tag is `display: none`, so a guard would protect
1186
+ * nothing. Either way the compound is left alone.
1187
+ */
1188
+ function compoundNamesHost(nodes) {
1189
+ return nodes.some(isGuardTermNode);
1190
+ }
1191
+ function tagOf(nodes) {
1192
+ for (const node of nodes) {
1193
+ if (node.type === 'tag') {
1194
+ return node.value.toLowerCase();
1195
+ }
1196
+ }
1197
+ return null;
1198
+ }
1199
+ function isPseudoElement(node) {
1200
+ if (node.type !== 'pseudo') {
1201
+ return false;
1202
+ }
1203
+ return node.value.startsWith('::') || LEGACY_PSEUDO_ELEMENTS.has(pseudoName(node));
1204
+ }
1205
+
1206
+ /**
1207
+ * Guards must be inserted before any pseudo-element — `div:not(…)::before`, never after.
1208
+ */
1209
+ function guardInsertIndex(nodes) {
1210
+ const index = nodes.findIndex(isPseudoElement);
1211
+ return index === -1 ? nodes.length : index;
1212
+ }
1213
+
1214
+ /* -------------------------------------------------------------------------------------- */
1215
+ /* Plan */
1216
+ /* -------------------------------------------------------------------------------------- */
1217
+
1218
+ function createPlan() {
1219
+ return {
1220
+ replace: new Map(),
1221
+ appendAfter: new Map(),
1222
+ prependBefore: new Map(),
1223
+ touched: new Set(),
1224
+ guardCount: 0,
1225
+ receives: false,
1226
+ hardRefusals: [],
1227
+ softRefusals: [],
1228
+ residualNotes: [],
1229
+ reachSuppressions: [],
1230
+ reviews: [],
1231
+ sawGeneralSibling: false
1232
+ };
1233
+ }
1234
+ function setReplace(plan, node, text) {
1235
+ plan.replace.set(node, text);
1236
+ plan.touched.add(node);
1237
+ }
1238
+ function setAppendAfter(plan, node, text) {
1239
+ var _plan$appendAfter$get;
1240
+ plan.appendAfter.set(node, ((_plan$appendAfter$get = plan.appendAfter.get(node)) !== null && _plan$appendAfter$get !== void 0 ? _plan$appendAfter$get : '') + text);
1241
+ plan.touched.add(node);
1242
+ }
1243
+ function setPrependBefore(plan, node, text) {
1244
+ var _plan$prependBefore$g;
1245
+ plan.prependBefore.set(node, text + ((_plan$prependBefore$g = plan.prependBefore.get(node)) !== null && _plan$prependBefore$g !== void 0 ? _plan$prependBefore$g : ''));
1246
+ plan.touched.add(node);
1247
+ }
1248
+
1249
+ /* -------------------------------------------------------------------------------------- */
1250
+ /* Planning */
1251
+ /* -------------------------------------------------------------------------------------- */
1252
+
1253
+ function planBranch(branch, plan, scope) {
1254
+ var _compounds$;
1255
+ /**
1256
+ * Refusals that hold **wherever** the pseudo appears, at any nesting depth, before anything
1257
+ * is planned. These families have no guard form at all, so no part of a selector containing
1258
+ * one may be rewritten — a guard elsewhere in it would be a partial fix on a rule that stays
1259
+ * broken, and in a selector list it would leave the list partially guarded.
1260
+ */
1261
+ planWholeBranchRefusals(branch, plan);
1262
+
1263
+ /**
1264
+ * `:has()` next, wherever it appears. It may be nested inside `:not()` / `:is()` /
1265
+ * `:where()`, and in that case the guard is pushed *inside* the `:has()` argument rather
1266
+ * than onto the wrapping `:not()` — trap 5.
1267
+ */
1268
+ planHasArguments(branch, plan);
1269
+ const compounds = splitCompounds(branch);
1270
+
1271
+ /**
1272
+ * A branch that opens with a combinator (`> *`, `> :not([data-layout-slot])`) is the nested
1273
+ * spelling of `& > …` whatever scope the caller named: the parent it hangs off is implied,
1274
+ * and that parent is the consumer's own element, so nothing in the branch is document-level.
1275
+ */
1276
+ const opensWithCombinator = ((_compounds$ = compounds[0]) === null || _compounds$ === void 0 ? void 0 : _compounds$.combinatorBefore) !== null;
1277
+ compounds.forEach((compound, index) => {
1278
+ const ancestors = compounds.slice(0, index);
1279
+ const isGlobalRule = scope === 'global' && !opensWithCombinator;
1280
+
1281
+ /**
1282
+ * At global scope, a compound with nothing but the document itself above it reached the
1283
+ * portalled surface before the flag. Under `nested` scope every branch carries `&`, which
1284
+ * is never document-level, so the question does not arise.
1285
+ */
1286
+ const reachedPreFlag = isGlobalRule && ancestors.every(isDocumentLevelCompound);
1287
+
1288
+ /**
1289
+ * A bare `div` among otherwise document-level ancestors is the one case the transform
1290
+ * cannot settle. Any other consumer-owned ancestor (`.sidebar`, `div.x`, `[data-foo]`)
1291
+ * decides the question the usual way, so the review outcome needs every ancestor to be
1292
+ * document-level or a bare `div`.
1293
+ */
1294
+ const behindBareDivAncestor = isGlobalRule && !reachedPreFlag && ancestors.every(ancestor => isDocumentLevelCompound(ancestor) || isBareDivCompound(ancestor));
1295
+ planCompound(compound, plan, {
1296
+ reachedPreFlag,
1297
+ behindBareDivAncestor
1298
+ });
1299
+ });
1300
+ }
1301
+
1302
+ /**
1303
+ * Is this compound exactly the tag `div`, with no class, id, attribute or pseudo qualifier?
1304
+ *
1305
+ * Pre-flag, a surface portalled to `body` sat inside `@atlaskit/portal`'s container div, and
1306
+ * every surface wrapper is a div too, so a bare `div` ancestor was satisfied on the way down to
1307
+ * the surface's content. A qualified div (`div.x`, `div[data-foo]`) names the consumer's own
1308
+ * element and is not ambiguous.
1309
+ */
1310
+ function isBareDivCompound(compound) {
1311
+ const {
1312
+ nodes
1313
+ } = compound;
1314
+ return nodes.length === 1 && nodes[0].type === 'tag' && nodes[0].value.toLowerCase() === 'div';
1315
+ }
1316
+ function bareDivAncestorReason(nodes) {
1317
+ const compound = nodes.map(node => node.toString().trim()).join('');
1318
+ return `'${compound}' is at global scope below a bare div ancestor. The portal container and every surface wrapper were divs, so this rule may already have reached the surface's content when it was portalled to body, and a guard here could remove styling the surface had before the flag rather than restore any. Nothing is written; review by hand. Guard it if the div stands for your own wrapper, leave it if it stands for any div, and anchor the selector to your own element (a class, an id, or \`&\` in a style object) if you mean only your own content.`;
1319
+ }
1320
+
1321
+ /**
1322
+ * Is this compound satisfied by the document itself, rather than by anything the consumer
1323
+ * rendered — `html`, `body`, `:root`, each with any qualifiers, or a lone `*`?
1324
+ *
1325
+ * These are the ancestors every element has, including a surface portalled to `body`. A chain
1326
+ * of them above a compound constrains nothing, so the rule reached the portalled surface's
1327
+ * content before the flag and a guard would take away what that content already had. A
1328
+ * consumer-owned ancestor (`.sidebar`, `#app`, `&`) or any other tag did **not** contain the
1329
+ * portal, so below one of those the host is a new match and the guard restores.
1330
+ */
1331
+ function isDocumentLevelCompound(compound) {
1332
+ const {
1333
+ nodes
1334
+ } = compound;
1335
+ if (isDocumentRootCompound(nodes)) {
1336
+ return true;
1337
+ }
1338
+ return nodes.length === 1 && nodes[0].type === 'universal';
1339
+ }
1340
+
1341
+ /**
1342
+ * `html`, `body` or `:root`, with any qualifiers — an element of the document itself, which is
1343
+ * never a host and never inside one.
1344
+ */
1345
+ function isDocumentRootCompound(nodes) {
1346
+ const tag = tagOf(nodes);
1347
+ if (tag === 'html' || tag === 'body') {
1348
+ return true;
1349
+ }
1350
+ return nodes.some(node => node.type === 'pseudo' && pseudoName(node) === ':root');
1351
+ }
1352
+ function reachedPreFlagReason(nodes) {
1353
+ const compound = nodes.map(node => node.toString().trim()).join('');
1354
+ return `'${compound}' is at global scope with nothing but the document itself above it (html, body, :root or *), so this rule already reached the surface's content when it was portalled to body. Guarding it would remove styling the surface had before the flag rather than restore any, so it is left alone. Anchor the selector to your own element (a class, an id, or \`&\` in a style object) if you mean only your own content.`;
1355
+ }
1356
+
1357
+ /**
1358
+ * The two families with no guard form at any depth.
1359
+ *
1360
+ * Both are matched against the **full** pseudo-class name via a set, never by substring. Four of
1361
+ * the five of-type pseudos do not contain the text `nth-of-type`, and `:first-of-type` alone is 926
1362
+ * occurrences in the monorepo, so a substring test would silently miss almost the whole family.
1363
+ */
1364
+ function planWholeBranchRefusals(branch, plan) {
1365
+ branch.walkPseudos(pseudo => {
1366
+ if (OF_TYPE_PSEUDOS.has(pseudoName(pseudo))) {
1367
+ /**
1368
+ * The of-type family is type-scoped by definition: it counts siblings by tag name and
1369
+ * accepts no `of S` selector argument, so its counting cannot be re-based onto real
1370
+ * elements. A guard anywhere in such a selector cannot fix the counting and changes
1371
+ * behaviour inside surfaces for nothing.
1372
+ */
1373
+ plan.hardRefusals.push(`'${pseudo.value}' has no guard form: the of-type family counts siblings by tag name and accepts no \`of S\` selector argument, so its counting cannot be re-based onto real elements. Nothing in this selector is rewritten, because a guard elsewhere in it could not fix the counting.`);
1374
+ return;
1375
+ }
1376
+ if (pseudoName(pseudo) === ':empty') {
1377
+ /**
1378
+ * `:empty` is true of an element with no children *of any kind* and takes no selector
1379
+ * argument, so a host rendered inside the element cannot be excluded from it. A compound
1380
+ * carrying both `:empty` and a positional pseudo must refuse rather than take the
1381
+ * positional rewrite — `& > div:has(> div:only-child:empty)` is the measured case.
1382
+ */
1383
+ plan.hardRefusals.push("':empty' has no guard form: it is true of an element with no children of any kind and takes no selector argument, so a host rendered inside the element cannot be excluded from it. Nothing in this selector is rewritten, including any positional pseudo compounded with it.");
1384
+ }
1385
+ });
1386
+ }
1387
+ function planCompound(compound, plan, options) {
1388
+ const {
1389
+ nodes,
1390
+ position,
1391
+ isSubject
1392
+ } = compound;
1393
+ if (position === 'general') {
1394
+ plan.sawGeneralSibling = true;
1395
+ }
1396
+
1397
+ /* --- Refusals local to this compound ------------------------------------------------ */
1398
+
1399
+ for (const node of nodes) {
1400
+ if (node.type !== 'pseudo') {
1401
+ continue;
1402
+ }
1403
+ if (isSubject && ANCESTOR_PROPAGATING_PSEUDOS.has(pseudoName(node))) {
1404
+ plan.softRefusals.push(`'${node.value}' on the subject compound has no guard form: it matches an element *and its ancestors*, so a surface rendered inside this element hands it the state while the pointer or focus is in the surface. No guard expresses "not originating inside a top layer surface", at any depth.`);
1405
+ }
1406
+ }
1407
+ const merges = planPreExistingGuards(compound, plan);
1408
+
1409
+ /* --- Sibling combinators ------------------------------------------------------------ */
1410
+
1411
+ /**
1412
+ * The two damage modes split cleanly on a sibling combinator:
1413
+ *
1414
+ * - if a host could match the right-hand compound, the damage is that the host receives
1415
+ * the declaration — `popover-receives` — and the guard goes on that compound. This is
1416
+ * what shipped code does for `* + *` and `div + div`;
1417
+ * - if it could not, the only remaining damage is a host inserted *between* A and B,
1418
+ * which breaks `A + B` and which no guard restores. That is `real-element-loses` and it
1419
+ * is refused.
1420
+ *
1421
+ * `~` has no `real-element-loses` mode at all: it matches every following sibling, so an
1422
+ * inserted host removes no real match.
1423
+ */
1424
+ if (position === 'adjacent' && !couldHostMatch(nodes)) {
1425
+ plan.hardRefusals.push('The adjacent sibling combinator has no guard form here: no host can match the right-hand compound, so the only exposure left is a host inserted *between* the two siblings, which breaks the adjacency and which no guard restores.');
1426
+ return;
1427
+ }
1428
+ if (position === 'adjacent' && couldHostMatch(nodes)) {
1429
+ plan.residualNotes.push('The guard closes `popover-receives` on this adjacent sibling combinator, but a host inserted *between* the two siblings still breaks the adjacency for real elements. No guard form restores that; review the site.');
1430
+ }
1431
+
1432
+ /* --- Positional pseudo-classes ------------------------------------------------------ */
1433
+
1434
+ /**
1435
+ * A positional pseudo refuses the whole selector while the `of S` family is withdrawn, so
1436
+ * there is nothing left to plan for this compound.
1437
+ */
1438
+ if (planPositionals(compound, plan)) {
1439
+ return;
1440
+ }
1441
+
1442
+ /* --- Compound guard ---------------------------------------------------------------- */
1443
+
1444
+ /* A merged or pre-existing guard already satisfies this compound — never add a second. */
1445
+ const formName = guardFormFor(compound);
1446
+ const alreadyGuarded = merges > 0 || isCompoundGuarded(nodes, formName);
1447
+ const form = formName === 'wide' ? WIDE_GUARD : NARROW_GUARD;
1448
+ let guard = null;
1449
+ if (alreadyGuarded) {
1450
+ guard = null;
1451
+ } else if (nodes.some(node => node.type === 'nesting') || nestedMatchVerdictOf(nodes) === 'none') {
1452
+ /**
1453
+ * **Never guard the `&` compound, in any position.** `&` is the enclosing rule's own
1454
+ * subject, and the host is created *inside* `&`, never *as* `&`. So `&` can never be the
1455
+ * host, and a guard on it can only ever subtract legitimate matches.
1456
+ *
1457
+ * Measured: `html:not([data-color-mode=dark]) &` rewritten with a guard on `&` matches
1458
+ * outside a surface and matches **nothing** inside a popover or a dialog — so a theme rule
1459
+ * stops applying to every component rendered inside any surface.
1460
+ *
1461
+ * This is the mirror image of the host-naming case below. There a compound *names* a host
1462
+ * and the guard destroys it; here a compound provably *cannot be* a host and the guard
1463
+ * destroys it. Both are guarding something that is not the enemy, and both look like
1464
+ * diligence.
1465
+ *
1466
+ * `:is(&)` and `:is(& > span)` resolve to the same verdict, see {@link nestedMatchVerdict}.
1467
+ */
1468
+ guard = null;
1469
+ } else if (isDocumentRootCompound(nodes)) {
1470
+ /**
1471
+ * `html`, `body` and `:root` are the document's own elements. No surface can contain them
1472
+ * and no host can be one, so a guard on them excludes nothing and is only noise.
1473
+ */
1474
+ guard = null;
1475
+ } else if (compoundNamesHost(nodes)) {
1476
+ /**
1477
+ * `& dialog`, `& > [popover]`, `& style`: the author is targeting a surface or a
1478
+ * non-rendered element on purpose. For a host, every guard form excludes exactly what the
1479
+ * compound selects, so guarding would leave a rule that matches nothing. For a
1480
+ * non-rendered tag, a guard would protect nothing.
1481
+ */
1482
+ plan.softRefusals.push(`'${nodes.map(node => node.toString().trim()).join('')}' names a top layer host or a non-rendered tag directly, so it targets that element deliberately. A guard would either exclude exactly what it selects or protect nothing, so it is left alone.`);
1483
+ } else if (options.reachedPreFlag) {
1484
+ /**
1485
+ * The reach principle from the module docblock, applied. `div`, `body div` and `* + *` at
1486
+ * global scope all matched the surface's content in its portal before the flag, so the
1487
+ * guard that would otherwise be written here would remove something the surface had.
1488
+ * Recorded only where a guard would have been written, so the reason is never attached
1489
+ * to a compound that needed nothing.
1490
+ */
1491
+ if (position === 'descendant' || couldHostMatch(nodes)) {
1492
+ plan.reachSuppressions.push(reachedPreFlagReason(nodes));
1493
+ }
1494
+ } else if (options.behindBareDivAncestor) {
1495
+ /**
1496
+ * The ambiguous ancestor from the module docblock. Recorded only where a guard would have
1497
+ * been written, exactly as the reach suppression above, so a compound that needed nothing
1498
+ * never asks for a review.
1499
+ */
1500
+ if (position === 'descendant' || couldHostMatch(nodes)) {
1501
+ plan.reviews.push(bareDivAncestorReason(nodes));
1502
+ }
1503
+ } else if (position === 'descendant') {
1504
+ /**
1505
+ * Always guarded: a surface can sit anywhere in the unbounded gap above this compound, and
1506
+ * its internals match here. That is somebody else's surface, so the wide form applies.
1507
+ */
1508
+ guard = form;
1509
+ } else if (couldHostMatch(nodes)) {
1510
+ /**
1511
+ * Everywhere else, guard when a host could *be* this element.
1512
+ */
1513
+ guard = form;
1514
+ }
1515
+ if (guard) {
1516
+ const at = guardInsertIndex(nodes);
1517
+ if (at === 0) {
1518
+ setPrependBefore(plan, nodes[0], guard);
1519
+ } else {
1520
+ setAppendAfter(plan, nodes[at - 1], guard);
1521
+ }
1522
+ plan.receives = true;
1523
+ plan.guardCount += 1;
1524
+ }
1525
+ }
1526
+
1527
+ /**
1528
+ * Handle a guard that is already present.
1529
+ *
1530
+ * Earlier hand fixes carry partial or longer guards, such as `:not(:where(dialog))` or one that
1531
+ * also lists `style` and the rest. Missing terms are **merged into** that list, never replaced,
1532
+ * and never joined by a second guard. Extra terms are kept.
1533
+ * Merging keeps idempotency across the boundary: once the list is canonical, running again
1534
+ * changes nothing.
1535
+ *
1536
+ * A host-term `:not()` with no `:where()` around it is refused instead of merged, because it
1537
+ * carries real weight and unifying it would change the rule's specificity — this covers the
1538
+ * editor's `:not(style, .ProseMirror-gapcursor, .ProseMirror-widget, span)`, which is the same
1539
+ * shape and additionally lists genuinely rendered elements.
1540
+ *
1541
+ * A partial guard inside an `of` argument is not handled here. Any selector carrying an `of`
1542
+ * argument is refused by `rewriteSelector` before planning starts, because Compiled's extract
1543
+ * mode drops such a rule outright (see {@link WITHDRAWN_POSITIONAL_FORMS}).
1544
+ *
1545
+ * The merged list is written in canonical order: the required terms as `L` lists them, then
1546
+ * any extra terms the author added. {@link isCompoundGuarded} recognises the result as complete
1547
+ * on the next pass. A list that already has every required term is left as written, in any
1548
+ * order and with or without a `*`: the two spellings match the same elements, and the ratchet
1549
+ * counts only positional pseudo-classes, so rewriting them would be churn.
1550
+ */
1551
+ function planPreExistingGuards(compound, plan) {
1552
+ const wide = guardFormFor(compound) === 'wide';
1553
+ let merges = 0;
1554
+ for (const node of compound.nodes) {
1555
+ if (node.type !== 'pseudo') {
1556
+ continue;
1557
+ }
1558
+ if (pseudoName(node) !== ':not') {
1559
+ continue;
1560
+ }
1561
+
1562
+ /**
1563
+ * Classify from the `:not()`'s *direct* content only. Looking deeper would misread any
1564
+ * `:not()` that merely contains a guard somewhere inside it — including
1565
+ * `:not(:has(button:not(:where(L))))` and the `:not(:where(:nth-last-child(n+2 of S)))`
1566
+ * tail of the `:only-child` form, both of which this transform emits itself.
1567
+ */
1568
+ const direct = node.nodes;
1569
+
1570
+ /**
1571
+ * Trap 1. `S` is itself a `:not()`, so `X:not(S)` is a double negative that matches
1572
+ * only* hosts. Appending a guard to it would make it match nothing at all.
1573
+ */
1574
+ const soleNot = soleNotInside(node);
1575
+ if (soleNot && mentionsGuardTerm(soleNot)) {
1576
+ plan.hardRefusals.push(`'${node.toString().trim()}' is a double negative: the guard \`S\` is itself a \`:not()\`, so this matches *only* top layer hosts and nothing else. Appending another guard would make it match nothing. The intended form appends \`:not(:where(L))\` directly.`);
1577
+ continue;
1578
+ }
1579
+ const where = soleWhereInside(node);
1580
+ if (!where) {
1581
+ /**
1582
+ * Not wrapped in `:where()`. Only a refusal if it is actually an element exclusion
1583
+ * list that mentions a guard term — otherwise it is an ordinary `:not()`.
1584
+ */
1585
+ if (direct.every(isSimpleTerm) && direct.some(termIsGuardTerm)) {
1586
+ plan.hardRefusals.push(`'${node.toString().trim()}' is an existing top layer guard with no \`:where()\` around it, so it carries real specificity. Unifying it would change the rule's weight, and in the editor's case would also drop genuinely rendered elements from the exclusion list. This needs a hand edit and routing to the owning team.`);
1587
+ }
1588
+ continue;
1589
+ }
1590
+ const terms = where.nodes;
1591
+
1592
+ /**
1593
+ * Every term must be a simple selector, and at least one must be a guard term.
1594
+ * A `:where()` holding a functional pseudo is not an element exclusion list, and a
1595
+ * `:where()` of unrelated selectors is not a top layer guard to merge into.
1596
+ */
1597
+ if (!terms.every(isSimpleTerm) || !terms.some(termIsGuardTerm)) {
1598
+ continue;
1599
+ }
1600
+ const existing = terms.map(term => term.toString().trim()).filter(Boolean);
1601
+ const existingKeys = new Set(existing.map(normalise));
1602
+ const required = wide ? WIDE_TERMS : NARROW_TERMS;
1603
+ const requiredKeys = wide ? WIDE_TERM_KEYS : NARROW_TERM_KEYS;
1604
+ const missing = required.filter(term => !existingKeys.has(normalise(term)));
1605
+ if (missing.length === 0) {
1606
+ continue;
1607
+ }
1608
+
1609
+ /**
1610
+ * Canonical order: the required terms as `L` lists them, then any term the author added
1611
+ * that is not part of the list. A canonical term the author already had (in any order,
1612
+ * or as a wide term on a narrow position) is kept but re-ordered.
1613
+ */
1614
+ const extras = existing.filter(term => !requiredKeys.has(normalise(term)));
1615
+ const merged = [...required, ...extras];
1616
+ setReplace(plan, node, `:not(:where(${merged.join(', ')}))`);
1617
+
1618
+ /**
1619
+ * When a merge rewrites the guard, **add an explicit `*`** if the guard is all the
1620
+ * compound has. `& > *:not(:where(…))` and `& > :not(:where(…))` are semantically
1621
+ * identical. `*` is the form the guard-form table and the `child-universal` pair use.
1622
+ */
1623
+ if (compound.nodes.length === 1) {
1624
+ setPrependBefore(plan, node, '*');
1625
+ }
1626
+ merges += 1;
1627
+ plan.guardCount += 1;
1628
+ plan.receives = true;
1629
+ }
1630
+ return merges;
1631
+ }
1632
+
1633
+ /**
1634
+ * A term of a guard's `:where()` list: simple selectors only, no functional pseudos.
1635
+ */
1636
+ function isSimpleTerm(term) {
1637
+ return !term.nodes.some(node => node.type === 'pseudo');
1638
+ }
1639
+
1640
+ /**
1641
+ * Guard every top-level comma branch of every `:has()`, at any depth.
1642
+ *
1643
+ * `:has()` matches if *any* branch matches, so a guard on one branch leaves the others open.
1644
+ * The parser has already split on top-level commas, so nested commas inside `:where()` /
1645
+ * `:is()` / `:not()` cannot be split by accident.
1646
+ *
1647
+ * Within a branch, every compound is planned by {@link planCompound}, exactly as a top-level
1648
+ * compound is. The branch's leftmost compound is a descendant of the subject, so it takes the
1649
+ * wide list whatever its tag: `.x:has(button, a)` gets two guards even though no host is a
1650
+ * `<button>`, because the button can be inside a surface that is inside `.x`. A compound after
1651
+ * `>` takes the narrow list only if a host could be that element: `:has(> div > span)` guards
1652
+ * the `div` and leaves the `span` alone.
1653
+ */
1654
+ function planHasArguments(branch, plan) {
1655
+ branch.walkPseudos(pseudo => {
1656
+ if (pseudoName(pseudo) !== ':has') {
1657
+ return;
1658
+ }
1659
+
1660
+ /**
1661
+ * Chromium rejects the entire selector when a `:has()` appears inside a `:has()`
1662
+ * argument, so the rule has already stopped applying. Never emit one, and never
1663
+ * pretend to fix one.
1664
+ */
1665
+ if (hasAncestorPseudo(pseudo, ':has')) {
1666
+ plan.hardRefusals.push('A `:has()` nested inside another `:has()` argument is rejected outright by Chromium, so the whole rule already does not apply. This cannot be guarded — it has to be restructured by hand.');
1667
+ return;
1668
+ }
1669
+ let selfReferential = false;
1670
+ pseudo.walk(inner => {
1671
+ if (inner.type === 'nesting') {
1672
+ selfReferential = true;
1673
+ }
1674
+ });
1675
+ if (selfReferential) {
1676
+ plan.hardRefusals.push('A self-referential `:has()` — `:has(&)` or `:has(> &)` — has no guard form: the argument resolves to the subject itself, so there is no descendant compound to place a guard on.');
1677
+ return;
1678
+ }
1679
+
1680
+ /**
1681
+ * `:has(+ X)` and `:has(X + Y)` are adjacency inside the argument, with no selector
1682
+ * argument to re-base it onto real elements. `:has(~ X)` reaches the subject's siblings
1683
+ * rather than its descendants, so neither the wide form nor the narrow one is the right
1684
+ * guard there. Both are refused.
1685
+ */
1686
+ let sibling = null;
1687
+ pseudo.each(argument => {
1688
+ for (const inner of argument.nodes) {
1689
+ if (inner.type !== 'combinator') {
1690
+ continue;
1691
+ }
1692
+ const value = inner.value.trim();
1693
+ if (!sibling && (value === '+' || value === '~')) {
1694
+ sibling = value;
1695
+ }
1696
+ }
1697
+ });
1698
+ if (sibling) {
1699
+ plan.hardRefusals.push(`\`:has()\` with a sibling combinator ('${sibling}') has no guard form: adjacency inside the argument takes no selector argument to re-base onto real elements, and the argument reaches the subject's siblings rather than its descendants, so neither guard form applies.`);
1700
+ return;
1701
+ }
1702
+ let propagating = null;
1703
+ pseudo.walkPseudos(inner => {
1704
+ if (!propagating && ANCESTOR_PROPAGATING_PSEUDOS.has(pseudoName(inner))) {
1705
+ propagating = inner.value;
1706
+ }
1707
+ });
1708
+ if (propagating) {
1709
+ plan.hardRefusals.push(`\`:has()\` containing '${propagating}' has no guard form: '${propagating}' matches an element *and its ancestors*, so the subject itself satisfies the argument whenever the pointer or focus is inside the surface. No guard on the argument can help, at any depth.`);
1710
+ return;
1711
+ }
1712
+ for (const argument of pseudo.nodes) {
1713
+ const compounds = splitCompounds(argument);
1714
+ if (compounds.length === 0) {
1715
+ continue;
1716
+ }
1717
+
1718
+ /**
1719
+ * A positional pseudo inside the argument refuses the whole selector while the `of S`
1720
+ * family is withdrawn, at any depth, so there is nothing left to plan for this branch.
1721
+ */
1722
+ if (compounds.some(compound => planPositionals(compound, plan))) {
1723
+ continue;
1724
+ }
1725
+
1726
+ /**
1727
+ * Every compound of the argument is checked, not only the last. `:has(dialog button)`
1728
+ * matches only buttons inside a dialog, so a wide guard on `button` would exclude
1729
+ * every element the argument can match and leave the `:has()` unsatisfiable.
1730
+ */
1731
+ if (compounds.some(compound => compoundNamesHost(compound.nodes))) {
1732
+ plan.softRefusals.push('A `:has()` argument that names a top layer host or a non-rendered tag directly targets that element deliberately. A guard would either exclude exactly what it selects or protect nothing, so it is left alone.');
1733
+ continue;
1734
+ }
1735
+
1736
+ /**
1737
+ * Every compound of the argument is planned exactly as a top-level compound is, by the
1738
+ * same code. `:has(> div > span)` therefore guards the host-capable `div` and skips
1739
+ * the `span`, as `& > div > span` does; a guard on the `span` alone would be inert,
1740
+ * because no host is a span, and the argument would still match popup content through
1741
+ * the unguarded `div`.
1742
+ *
1743
+ * The argument's leftmost compound carries no combinator of its own, but it is a
1744
+ * descendant of the subject: `:has(button)` is "a button anywhere inside", so it is
1745
+ * planned in descendant position and takes the wide list. A leading combinator is kept
1746
+ * as written, so `:has(> div)` is a child and takes the narrow list.
1747
+ */
1748
+ for (const compound of compounds) {
1749
+ const position = compound.position === 'first' ? 'descendant' : compound.position;
1750
+ planCompound({
1751
+ ...compound,
1752
+ position
1753
+ }, plan, {
1754
+ reachedPreFlag: false,
1755
+ behindBareDivAncestor: false
1756
+ });
1757
+ }
1758
+ }
1759
+ });
1760
+ }
1761
+
1762
+ /**
1763
+ * Refuse every positional pseudo-class on this compound. Returns true if one was found.
1764
+ *
1765
+ * Each of these has a verified guard form in the decision doc's table, and every one of those
1766
+ * forms needs an `of S` clause, which is **withdrawn**: Compiled's extract mode drops the rule
1767
+ * outright, so the guard would delete styling rather than protect it — see
1768
+ * {@link WITHDRAWN_POSITIONAL_FORMS}. The refusal reason names the form that was withheld, so
1769
+ * it can be restored from the report once Compiled is fixed.
1770
+ *
1771
+ * A positional pseudo nested inside `:is()`, `:where()` or `:not()` has no form even in the
1772
+ * table: sibling counting there is relative to a different subject. Inside `:has()` the
1773
+ * argument's compounds are handed back to this function by `planHasArguments`, so that case is
1774
+ * refused with the same reason as a top-level compound.
1775
+ */
1776
+ function planPositionals(compound, plan) {
1777
+ let found = false;
1778
+ for (const node of compound.nodes) {
1779
+ if (node.type !== 'pseudo') {
1780
+ continue;
1781
+ }
1782
+ const name = pseudoName(node);
1783
+ if (POSITIONAL_PSEUDOS.has(name)) {
1784
+ plan.hardRefusals.push(ofClauseWithheldReason(node));
1785
+ found = true;
1786
+ continue;
1787
+ }
1788
+ if (name === ':not') {
1789
+ const sole = solePseudoInside(node);
1790
+ const soleName = sole ? pseudoName(sole) : null;
1791
+ if (soleName === ':first-child' || soleName === ':last-child') {
1792
+ plan.hardRefusals.push(ofClauseWithheldReason(node));
1793
+ found = true;
1794
+ continue;
1795
+ }
1796
+ if (sole && soleName !== null && POSITIONAL_PSEUDOS.has(soleName)) {
1797
+ plan.hardRefusals.push(`\`:not(${sole.value}…)\` has no guard form. Only \`:not(:first-child)\` and \`:not(:last-child)\` can be expressed as a single specificity-neutral term, and even those are withdrawn while Compiled's extract mode drops any selector carrying an \`of\` clause. Close the site by giving the elements you mean a class or a \`data-\` attribute and selecting them directly.`);
1798
+ found = true;
1799
+ continue;
1800
+ }
1801
+ /* Any other `:not()` falls through to the nested check below. */
1802
+ }
1803
+ if (name === ':has') {
1804
+ continue;
1805
+ }
1806
+ node.walkPseudos(inner => {
1807
+ if (!POSITIONAL_PSEUDOS.has(pseudoName(inner)) || hasAncestorPseudo(inner, ':has')) {
1808
+ return;
1809
+ }
1810
+ plan.hardRefusals.push(`The positional pseudo '${inner.value}' is nested inside '${node.value}()', where sibling counting is relative to a different subject. The decision doc's \`of S\` forms do not apply, so this needs triage.`);
1811
+ found = true;
1812
+ });
1813
+ }
1814
+ return found;
1815
+ }
1816
+
1817
+ /* -------------------------------------------------------------------------------------- */
1818
+ /* Emission */
1819
+ /* -------------------------------------------------------------------------------------- */
1820
+
1821
+ function emitSelector(branch, plan) {
1822
+ const parts = [];
1823
+ for (const node of branch.nodes) {
1824
+ if (node.type === 'combinator') {
1825
+ const value = node.value.trim();
1826
+ parts.push(value === '' ? ' ' : ` ${value} `);
1827
+ continue;
1828
+ }
1829
+ const before = plan.prependBefore.get(node);
1830
+ if (before) {
1831
+ parts.push(before);
1832
+ }
1833
+ parts.push(emitNode(node, plan));
1834
+ const after = plan.appendAfter.get(node);
1835
+ if (after) {
1836
+ parts.push(after);
1837
+ }
1838
+ }
1839
+ return parts.join('').trim();
1840
+ }
1841
+ function emitNode(node, plan) {
1842
+ const replacement = plan.replace.get(node);
1843
+ if (replacement !== undefined) {
1844
+ return replacement;
1845
+ }
1846
+
1847
+ /**
1848
+ * Only re-emit a functional pseudo from its parsed parts when something inside it changed.
1849
+ * Anything untouched is passed through verbatim, which keeps micro-syntaxes such as
1850
+ * `:nth-child(2n+1)` byte-exact.
1851
+ */
1852
+ if (node.type === 'pseudo' && node.nodes.length > 0 && subtreeTouched(node, plan)) {
1853
+ const inner = node.nodes.map(argument => emitSelector(argument, plan)).join(', ');
1854
+ return `${node.value}(${inner})`;
1855
+ }
1856
+ return node.toString().trim();
1857
+ }
1858
+ function subtreeTouched(node, plan) {
1859
+ let found = false;
1860
+ if (node.type !== 'pseudo') {
1861
+ return false;
1862
+ }
1863
+ node.walk(inner => {
1864
+ if (plan.touched.has(inner)) {
1865
+ found = true;
1866
+ }
1867
+ });
1868
+ return found;
1869
+ }
1870
+
1871
+ /* -------------------------------------------------------------------------------------- */
1872
+ /* Guard recognition */
1873
+ /* -------------------------------------------------------------------------------------- */
1874
+
1875
+ /**
1876
+ * Already carries a guard that covers this compound: a `:not(:where(…))` whose term list is a
1877
+ * superset of the terms the compound's position needs, in any order and with any extra terms
1878
+ * the author added. Byte-exact matching is not enough here, because the merge in
1879
+ * {@link planPreExistingGuards} preserves author terms, and a guard the transform itself wrote
1880
+ * must be recognised as complete on the next pass.
1881
+ */
1882
+ function isCompoundGuarded(nodes, form) {
1883
+ const required = form === 'wide' ? WIDE_TERM_KEYS : NARROW_TERM_KEYS;
1884
+ return nodes.some(node => {
1885
+ const terms = guardTermKeysOf(node);
1886
+ if (terms === null) {
1887
+ return false;
1888
+ }
1889
+ for (const key of required) {
1890
+ if (!terms.has(key)) {
1891
+ return false;
1892
+ }
1893
+ }
1894
+ return true;
1895
+ });
1896
+ }
1897
+
1898
+ /**
1899
+ * The normalised term keys of a `:not(:where(<simple terms>))` that mentions at least one term
1900
+ * of `L`, or `null` when the node is not such a guard.
1901
+ */
1902
+ function guardTermKeysOf(node) {
1903
+ if (node.type !== 'pseudo' || pseudoName(node) !== ':not') {
1904
+ return null;
1905
+ }
1906
+ const where = soleWhereInside(node);
1907
+ if (!where) {
1908
+ return null;
1909
+ }
1910
+ const terms = where.nodes;
1911
+ if (!terms.every(isSimpleTerm) || !terms.some(termIsGuardTerm)) {
1912
+ return null;
1913
+ }
1914
+ return new Set(terms.map(term => normalise(term.toString())));
1915
+ }
1916
+
1917
+ /**
1918
+ * Does this pseudo mention any term of `L` anywhere inside it?
1919
+ */
1920
+ function mentionsGuardTerm(pseudo) {
1921
+ let found = false;
1922
+ pseudo.walk(node => {
1923
+ if (isGuardTermNode(node)) {
1924
+ found = true;
1925
+ }
1926
+ });
1927
+ return found;
1928
+ }
1929
+
1930
+ /**
1931
+ * Is this one term of an exclusion list a term of `L` or `S`, such as `dialog` or `style`?
1932
+ */
1933
+ function termIsGuardTerm(term) {
1934
+ return term.nodes.some(isGuardTermNode);
1935
+ }
1936
+
1937
+ /**
1938
+ * Does this node name a top layer host, or an element `L` lists, outright?
1939
+ */
1940
+ function isGuardTermNode(node) {
1941
+ if (node.type === 'attribute') {
1942
+ return node.attribute.toLowerCase() === 'popover';
1943
+ }
1944
+ if (node.type === 'tag') {
1945
+ return GUARD_TERM_TAGS.has(node.value.toLowerCase());
1946
+ }
1947
+ if (node.type === 'pseudo') {
1948
+ return HOST_PSEUDOS.has(pseudoName(node));
1949
+ }
1950
+ return false;
1951
+ }
1952
+
1953
+ /**
1954
+ * The single `:where()` inside `:not(…)` when that is all it contains, otherwise `null`.
1955
+ */
1956
+ function soleWhereInside(pseudo) {
1957
+ const only = solePseudoInside(pseudo);
1958
+ return only && pseudoName(only) === ':where' ? only : null;
1959
+ }
1960
+
1961
+ /**
1962
+ * The single `:not()` inside `:not(…)` when that is all it contains, otherwise `null`.
1963
+ */
1964
+ function soleNotInside(pseudo) {
1965
+ const only = solePseudoInside(pseudo);
1966
+ return only && pseudoName(only) === ':not' ? only : null;
1967
+ }
1968
+
1969
+ /**
1970
+ * The single pseudo inside `:not(…)` when that is all it contains, otherwise `null`.
1971
+ */
1972
+ function solePseudoInside(pseudo) {
1973
+ if (pseudo.nodes.length !== 1) {
1974
+ return null;
1975
+ }
1976
+ const inner = nonEmptyNodes(pseudo.nodes[0]);
1977
+ if (inner.length !== 1) {
1978
+ return null;
1979
+ }
1980
+ const only = inner[0];
1981
+ return only.type === 'pseudo' ? only : null;
1982
+ }
1983
+
1984
+ /* -------------------------------------------------------------------------------------- */
1985
+ /* Specificity */
1986
+ /* -------------------------------------------------------------------------------------- */
1987
+
1988
+ /**
1989
+ * Compute (a,b,c) for one selector.
1990
+ *
1991
+ * - an id is (1,0,0); a class, attribute or pseudo-class is (0,1,0); a type or pseudo-element
1992
+ * is (0,0,1); the universal selector is (0,0,0);
1993
+ * - `:where()` is always (0,0,0), whatever it contains;
1994
+ * - `:not()`, `:is()` and `:has()` take the specificity of their most specific argument and
1995
+ * add nothing of their own;
1996
+ * - `:nth-child()` / `:nth-last-child()` count as one pseudo-class *plus* the specificity of
1997
+ * the most specific selector in an `of S` argument. With `S` weightless that is (0,1,0),
1998
+ * which is what makes the positional rewrites neutral;
1999
+ * - the nesting selector `&` is treated as (0,0,0). It is never modified by this transform,
2000
+ * so whatever its real value is, it is the same before and after.
2001
+ */
2002
+ function specificityOfSelector(branch) {
2003
+ let a = 0;
2004
+ let b = 0;
2005
+ let c = 0;
2006
+ for (const node of branch.nodes) {
2007
+ const [na, nb, nc] = specificityOfNode(node);
2008
+ a += na;
2009
+ b += nb;
2010
+ c += nc;
2011
+ }
2012
+ return [a, b, c];
2013
+ }
2014
+ function specificityOfNode(node) {
2015
+ switch (node.type) {
2016
+ case 'id':
2017
+ return [1, 0, 0];
2018
+ case 'class':
2019
+ case 'attribute':
2020
+ return [0, 1, 0];
2021
+ case 'tag':
2022
+ return [0, 0, 1];
2023
+ case 'pseudo':
2024
+ return specificityOfPseudo(node);
2025
+ default:
2026
+ return [0, 0, 0];
2027
+ }
2028
+ }
2029
+ function specificityOfPseudo(pseudo) {
2030
+ if (isPseudoElement(pseudo)) {
2031
+ return [0, 0, 1];
2032
+ }
2033
+ switch (pseudoName(pseudo)) {
2034
+ case ':where':
2035
+ return [0, 0, 0];
2036
+ case ':not':
2037
+ case ':is':
2038
+ case ':has':
2039
+ case ':matches':
2040
+ case ':-moz-any':
2041
+ case ':-webkit-any':
2042
+ return maxSpecificity(pseudo.nodes.map(specificityOfSelector));
2043
+ case ':nth-child':
2044
+ case ':nth-last-child':
2045
+ {
2046
+ const inner = nthArgumentText(pseudo);
2047
+ const ofIndex = findOfKeyword(inner);
2048
+ if (ofIndex === -1) {
2049
+ return [0, 1, 0];
2050
+ }
2051
+ let argument = [0, 0, 0];
2052
+ try {
2053
+ argument = maxSpecificity(parse(inner.slice(ofIndex + 2)).map(specificityOfSelector));
2054
+ } catch {
2055
+ argument = [0, 0, 0];
2056
+ }
2057
+ return [argument[0], argument[1] + 1, argument[2]];
2058
+ }
2059
+ default:
2060
+ return [0, 1, 0];
2061
+ }
2062
+ }
2063
+ function maxSpecificity(list) {
2064
+ let best = [0, 0, 0];
2065
+ for (const candidate of list) {
2066
+ if (compareSpecificity(candidate, best) > 0) {
2067
+ best = candidate;
2068
+ }
2069
+ }
2070
+ return best;
2071
+ }
2072
+ function compareSpecificity(left, right) {
2073
+ for (let index = 0; index < 3; index++) {
2074
+ if (left[index] !== right[index]) {
2075
+ return left[index] - right[index];
2076
+ }
2077
+ }
2078
+ return 0;
2079
+ }
2080
+ function sameSpecificity(left, right) {
2081
+ return compareSpecificity(left, right) === 0;
2082
+ }
2083
+
2084
+ /* -------------------------------------------------------------------------------------- */
2085
+ /* Small AST helpers */
2086
+ /* -------------------------------------------------------------------------------------- */
2087
+
2088
+ /**
2089
+ * The raw text between the parentheses of a functional pseudo.
2090
+ */
2091
+ function nthArgumentText(pseudo) {
2092
+ const text = pseudo.toString().trim();
2093
+ const open = text.indexOf('(');
2094
+ if (open === -1 || !text.endsWith(')')) {
2095
+ return '';
2096
+ }
2097
+ return text.slice(open + 1, -1);
2098
+ }
2099
+
2100
+ /**
2101
+ * Index of the `of` keyword in an `An+B [of S]` argument, or -1. The `An+B` part can only
2102
+ * contain digits, `n`, `+`, `-` and whitespace, so the first `of` word is the separator. The
2103
+ * selector list may follow it with no whitespace at all, as in `2 of:not(…)`, so only the
2104
+ * boundary after the word is required, not a space.
2105
+ */
2106
+ function findOfKeyword(inner) {
2107
+ const match = /(^|\s)of\b/i.exec(inner);
2108
+ if (!match) {
2109
+ return -1;
2110
+ }
2111
+ return match.index + match[1].length;
2112
+ }
2113
+ function hasAncestorPseudo(node, value) {
2114
+ let current = node.parent;
2115
+ while (current) {
2116
+ if (current.type === 'pseudo' && pseudoName(current) === value) {
2117
+ return true;
2118
+ }
2119
+ current = current.parent;
2120
+ }
2121
+ return false;
2122
+ }
2123
+ function hasNestedHas(branch) {
2124
+ let found = false;
2125
+ branch.walkPseudos(pseudo => {
2126
+ if (pseudoName(pseudo) === ':has' && hasAncestorPseudo(pseudo, ':has')) {
2127
+ found = true;
2128
+ }
2129
+ });
2130
+ return found;
2131
+ }