"""Prefix the designer's flat CSS rules without requiring browser @scope support.""" import re TOKENS = re.compile(r'''/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[{}]''') def selectors(value): """Split a selector list while preserving commas inside :is(), :has(), etc.""" start = depth = 0 for i, char in enumerate(value): if char in "([": depth += 1 elif char in ")]": depth -= 1 elif char == "," and depth == 0: yield value[start:i] start = i + 1 yield value[start:] def scope_css(source, scope, root=None): """Keep declarations/media queries; isolate selectors with zero-weight :where. The source contains ordinary style rules and @media only. Fail on other at-rules so a designer addition cannot silently produce invalid CSS. `root` replaces :scope with the same specificity as that pseudo-class. """ result, start, opening, depth = [], 0, None, 0 for token in TOKENS.finditer(source): if token[0] == "{": if depth == 0: opening = token.start() depth += 1 elif token[0] == "}": depth -= 1 if depth < 0: raise ValueError("Unbalanced CSS braces") if depth: continue header = source[start:opening] # Comments/whitespace remain verbatim outside the selector. prefix = re.match(r"(?:\s|/\*[\s\S]*?\*/)*", header)[0] header = header[len(prefix):] body = source[opening + 1:token.start()] if header.startswith("@media"): body = scope_css(body, scope, root) elif header.startswith("@"): raise ValueError(f"Unsupported CSS rule: {header}") else: header = ",".join( selector.replace(":scope", root or scope) if ":scope" in selector else f":where({scope}) {selector.strip()}" for selector in selectors(header) ) result.append(prefix + header + "{" + body + "}") start = token.end() if depth: raise ValueError("Unbalanced CSS braces") result.append(source[start:]) return "".join(result)