@fluixi-css/core 1.0.0-next.3 → 1.0.0-next.5

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.
@@ -382,1354 +382,677 @@ function write(node, depth, opts, w) {
382
382
  w.emit("".concat(pad, "}").concat(nl));
383
383
  }
384
384
 
385
- // Parses one raw utility (e.g. `md:hover:-bg-red-500/50!` or `[&_p]:text-[13px]`)
386
- // into a structured Atom in a single pass. Splitting is bracket/paren aware,
387
- // so `:` `/` `-` inside arbitrary values are left alone — no regex, no
388
- // backtracking. Which part is the root and which is the value can't be known from
389
- // the string alone (`text-red-500` vs `grid-cols-3`), so that split is resolved
390
- // against the registry through AtomContext.
385
+ // ─── Charcode constants (avoids string allocation on hot paths) ───────────────
386
+ var CC_TAB = 9,
387
+ CC_LF = 10,
388
+ CC_CR = 13,
389
+ CC_FF = 12,
390
+ CC_SPACE = 32;
391
+ var CC_DQUOTE = 34,
392
+ CC_HASH = 35,
393
+ CC_AMP = 38,
394
+ CC_SQUOTE = 39;
395
+ var CC_LPAREN = 40,
396
+ CC_RPAREN = 41,
397
+ CC_STAR = 42,
398
+ CC_PLUS = 43;
399
+ var CC_COMMA = 44,
400
+ CC_MINUS = 45,
401
+ CC_DOT = 46,
402
+ CC_SLASH = 47;
403
+ var CC_COLON = 58,
404
+ CC_SEMI = 59,
405
+ CC_GT = 62;
406
+ var CC_AT = 64,
407
+ CC_LBRACK = 91,
408
+ CC_BSLASH = 92,
409
+ CC_RBRACK = 93;
410
+ var CC_UNDER = 95,
411
+ CC_LBRACE = 123,
412
+ CC_RBRACE = 125,
413
+ CC_TILDE = 126;
391
414
 
392
- // Split on `sep` at depth 0 only; `[...]` and `(...)` are opaque, and `\` escapes
393
- // the next character.
394
- function splitAtTopLevel(input, sep) {
395
- var out = [];
396
- var depthBracket = 0;
397
- var depthParen = 0;
398
- var start = 0;
399
- for (var i = 0; i < input.length; i++) {
400
- var c = input[i];
401
- if (c === '\\') {
402
- i++; // skip the escaped char
403
- continue;
404
- }
405
- if (c === '[') depthBracket++;else if (c === ']') depthBracket = Math.max(0, depthBracket - 1);else if (c === '(') depthParen++;else if (c === ')') depthParen = Math.max(0, depthParen - 1);else if (c === sep && depthBracket === 0 && depthParen === 0) {
406
- out.push(input.slice(start, i));
407
- start = i + 1;
408
- }
409
- }
410
- out.push(input.slice(start));
411
- return out;
412
- }
415
+ // ─── Character predicates (charcode-based, no regex) ─────────────────────────
413
416
 
414
- // Content of a `[...]` or `(...)` wrapper, or null when `s` isn't wrapped.
415
- function unwrap(s, open) {
416
- var close = open === '[' ? ']' : ')';
417
- return s.length >= 2 && s[0] === open && s[s.length - 1] === close ? s.slice(1, -1) : null;
418
- }
419
- function parseModifier(raw) {
420
- if (!raw) return null;
421
- var arb = unwrap(raw, '[');
422
- if (arb !== null) return {
423
- kind: 'arbitrary',
424
- value: arb
425
- };
426
- // `(--name)` is shorthand for the custom property it references.
427
- var paren = unwrap(raw, '(');
428
- if (paren !== null) return {
429
- kind: 'arbitrary',
430
- value: "var(".concat(paren, ")")
431
- };
432
- return {
433
- kind: 'named',
434
- value: raw
435
- };
417
+ function isWS(c) {
418
+ return c === CC_SPACE || c === CC_TAB || c === CC_LF || c === CC_CR || c === CC_FF;
436
419
  }
437
- function splitModifier(base) {
438
- var parts = splitAtTopLevel(base, '/');
439
- if (parts.length === 1) return {
440
- base: base,
441
- modifier: null
442
- };
443
- var modifier = parseModifier(parts.slice(1).join('/'));
444
- return {
445
- base: parts[0],
446
- modifier: modifier
447
- };
420
+ function isDigit(c) {
421
+ return c >= 48 && c <= 57;
448
422
  }
449
-
450
- // In arbitrary values `_` stands in for a space; `\_` is a literal underscore.
451
- function decodeUnderscores(value) {
452
- // `_` → space, `\_` → literal `_`. But a URL may legitimately contain underscores,
453
- // so leave the inside of `url(...)` verbatim (the split keeps url() at odd indices).
454
- return value.split(/(url\([^)]*\))/g).map(function (part, i) {
455
- return i % 2 === 1 ? part : part.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
456
- }).join('');
423
+ function isAlpha(c) {
424
+ return c >= 65 && c <= 90 || c >= 97 && c <= 122;
457
425
  }
458
-
459
- // An arbitrary value may lead with a `type:` hint, e.g. `[length:12px]`.
460
- function parseArbitraryValue(body) {
461
- var colon = body.indexOf(':');
462
- if (colon > 0) {
463
- var maybeType = body.slice(0, colon);
464
- if (/^[a-z-]+$/.test(maybeType)) {
465
- return {
466
- dataType: maybeType,
467
- value: decodeUnderscores(body.slice(colon + 1))
468
- };
469
- }
470
- }
471
- return {
472
- dataType: null,
473
- value: decodeUnderscores(body)
474
- };
426
+ function isHex(c) {
427
+ return isDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
475
428
  }
476
-
477
- // The `(--name)` shorthand, optionally typed: `(length:--size)`. The custom
478
- // property name keeps its underscores.
479
- function parseParenValue(paren) {
480
- var colon = paren.indexOf(':');
481
- if (colon > 0 && /^[a-z-]+$/.test(paren.slice(0, colon))) {
482
- return {
483
- dataType: paren.slice(0, colon),
484
- value: "var(".concat(paren.slice(colon + 1), ")")
485
- };
486
- }
487
- return {
488
- dataType: null,
489
- value: "var(".concat(paren, ")")
490
- };
429
+ /**
430
+ * CSS ident-start: letter | underscore | non-ASCII | hyphen.
431
+ * A leading hyphen is valid (vendor prefixes, custom properties).
432
+ */
433
+ function isNameStart(c) {
434
+ return isAlpha(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
491
435
  }
492
- function parseVariant(raw) {
493
- var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
494
- if (!raw) return null;
495
-
496
- // `[&:hover]`, `[@media(...)]` — the selector is written out; a `&` means it's
497
- // relative to the element.
498
- var arb = unwrap(raw, '[');
499
- if (arb !== null) {
500
- return {
501
- kind: 'arbitrary',
502
- selector: arb,
503
- relative: arb.includes('&')
504
- };
505
- }
506
- var _splitModifier = splitModifier(raw),
507
- base = _splitModifier.base,
508
- modifier = _splitModifier.modifier;
509
-
510
- // A variant carrying a value: `group-hover`, `data-[open]`, `supports-[display:grid]`.
511
- var dash = base.indexOf('-');
512
- if (dash > 0) {
513
- var _ctx$isDynamicVariant, _ctx$isDynamicVariant2;
514
- var _root = base.slice(0, dash);
515
- var rest = base.slice(dash + 1);
516
- if ((_ctx$isDynamicVariant = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant !== void 0 && _ctx$isDynamicVariant.call(ctx, _root) || (_ctx$isDynamicVariant2 = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant2 !== void 0 && _ctx$isDynamicVariant2.call(ctx, _root + '-')) {
517
- // A variant's `[...]` is a raw condition/attribute, not a typed value.
518
- var arbVal = unwrap(rest, '[');
519
- var value = arbVal !== null ? {
520
- kind: 'arbitrary',
521
- value: arbVal,
522
- dataType: null
523
- } : {
524
- kind: 'named',
525
- value: rest
526
- };
527
- return {
528
- kind: 'functional',
529
- root: _root,
530
- value: value,
531
- modifier: modifier
532
- };
533
- }
534
- }
535
- return {
536
- kind: 'functional',
537
- root: base,
538
- value: null,
539
- modifier: modifier
540
- };
436
+ /** CSS ident-char: ident-start | digit */
437
+ function isNameChar(c) {
438
+ return isAlpha(c) || isDigit(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
541
439
  }
542
440
 
543
- // Returns null for structurally invalid input (empty or dangling segments).
544
- // Without a context the root/value split falls back to the first dash, which is
545
- // enough to test the scanner on its own.
546
- function parseAtom(raw) {
547
- var _ctx$isRule, _ctx$isRule2;
548
- var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
549
- if (!raw) return null;
550
- var segments = splitAtTopLevel(raw, ':');
551
- var utility = segments.pop();
552
- if (utility === undefined || utility === '') return null;
553
- var variants = [];
554
- var _iterator = _createForOfIteratorHelper(segments),
555
- _step;
556
- try {
557
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
558
- var seg = _step.value;
559
- if (seg === '') return null; // dangling `::`
560
- var v = parseVariant(seg, ctx);
561
- if (!v) return null;
562
- variants.push(v);
563
- }
564
- // Written left-to-right (outermost first), stored innermost-first so consumers
565
- // can wrap the declaration outward.
566
- } catch (err) {
567
- _iterator.e(err);
568
- } finally {
569
- _iterator.f();
570
- }
571
- variants.reverse();
441
+ // ─── Block context ────────────────────────────────────────────────────────────
572
442
 
573
- // `!` marks important, accepted on either end.
574
- var body = utility;
575
- var important = false;
576
- if (body.endsWith('!')) {
577
- important = true;
578
- body = body.slice(0, -1);
579
- } else if (body.startsWith('!')) {
580
- important = true;
581
- body = body.slice(1);
582
- }
583
- if (body === '') return null;
443
+ /**
444
+ * Determines what may legally appear inside a block:
445
+ * stylesheet – top-level: rules + at-rules
446
+ * mixed – @media/@supports/@container/@layer: rules + at-rules
447
+ * rule – inside a style rule: declarations + optional CSS nesting
448
+ * keyframes – inside @keyframes: keyframe stops (from/to/%)
449
+ * declarations– @font-face/@page/etc.: declarations only
450
+ */
584
451
 
585
- // Split off a trailing `/modifier` once, up front — it applies uniformly to
586
- // arbitrary-property, static, and functional atoms.
587
- var _splitModifier2 = splitModifier(body),
588
- core0 = _splitModifier2.base,
589
- modifier = _splitModifier2.modifier;
452
+ // ─── CssParser ────────────────────────────────────────────────────────────────
590
453
 
591
- // Arbitrary property: `[color:red]`, `[--my-var:0]` (optionally with modifier).
592
- var arbProp = unwrap(core0, '[');
593
- if (arbProp !== null && arbProp.includes(':')) {
594
- var colon = arbProp.indexOf(':');
595
- if (colon <= 0) return null;
596
- // The head must be a real CSS property or custom property. Scanners pull
597
- // `[...]` runs out of JS/TS too (array/object literals like
598
- // `[...prev, { value } as T]`); rejecting a non-property head keeps those
599
- // from emitting broken rules that later crash the CSS parser.
600
- var property = arbProp.slice(0, colon);
601
- if (!/^-{0,2}[a-zA-Z][a-zA-Z0-9-]*$/.test(property)) return null;
602
- return {
603
- kind: 'arbitrary-property',
604
- property: property,
605
- value: decodeUnderscores(arbProp.slice(colon + 1)),
606
- modifier: modifier,
607
- important: important,
608
- variants: variants,
609
- raw: raw
610
- };
611
- }
612
-
613
- // Negative.
614
- var negative = false;
615
- var base = core0;
616
- if (base[0] === '-') {
617
- negative = true;
618
- base = base.slice(1);
619
- if (base === '') return null;
620
- }
621
-
622
- // Static utility (only when unambiguous: no negative/modifier).
623
- if (!negative && modifier === null && (_ctx$isRule = ctx.isRule) !== null && _ctx$isRule !== void 0 && _ctx$isRule.call(ctx, base)) {
624
- return {
625
- kind: 'static',
626
- root: base,
627
- important: important,
628
- variants: variants,
629
- raw: raw
630
- };
454
+ var CssParser = /*#__PURE__*/function () {
455
+ function CssParser() {
456
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
457
+ _classCallCheck(this, CssParser);
458
+ _defineProperty(this, "input", '');
459
+ _defineProperty(this, "pos", 0);
460
+ _defineProperty(this, "length", 0);
461
+ _defineProperty(this, "line", 1);
462
+ _defineProperty(this, "col", 1);
463
+ _defineProperty(this, "errors", []);
464
+ _defineProperty(this, "warnings", []);
465
+ _defineProperty(this, "stats", CssParser.emptyStats());
466
+ this.options = _objectSpread2({
467
+ parseAtrulePrelude: true,
468
+ parseValue: true,
469
+ parseCustomProperty: true,
470
+ parseRulePrelude: true,
471
+ parseSelector: true,
472
+ includeComments: true,
473
+ includeSourceMaps: true,
474
+ includeSpecificity: true,
475
+ includeVendorPrefixes: true,
476
+ onError: function onError() {/* noop */},
477
+ onWarning: function onWarning() {/* noop */},
478
+ maxDepth: 100,
479
+ maxNodes: 100000,
480
+ enableNesting: true,
481
+ enableCustomProperties: true,
482
+ enableLogicalProperties: true,
483
+ enableContainerQueries: true,
484
+ enableLayerQueries: true,
485
+ enableSupportsQueries: true,
486
+ // middleware — undefined by default (fast path skips them)
487
+ onRule: undefined,
488
+ onAtRule: undefined,
489
+ onDeclaration: undefined,
490
+ onComment: undefined,
491
+ onKeyframe: undefined
492
+ }, options);
631
493
  }
632
494
 
633
- // Functional: split root ↔ value. Prefer the longest known functional root;
634
- // fall back to the first-dash split when no context is supplied.
635
- var _splitRootValue = splitRootValue(base, ctx),
636
- root = _splitRootValue.root,
637
- valueStr = _splitRootValue.valueStr;
638
- if (root === '') return null;
639
- var value = null;
640
- if (valueStr !== null && valueStr !== '') {
641
- var arbVal = unwrap(valueStr, '[');
642
- if (arbVal !== null) {
643
- value = _objectSpread2({
644
- kind: 'arbitrary'
645
- }, parseArbitraryValue(arbVal));
646
- } else {
647
- var paren = unwrap(valueStr, '(');
648
- value = paren !== null ? _objectSpread2({
649
- kind: 'arbitrary'
650
- }, parseParenValue(paren)) : {
651
- kind: 'named',
652
- value: valueStr,
653
- fraction: null
654
- };
495
+ // ── Public API ────────────────────────────────────────────────────────────
496
+ return _createClass(CssParser, [{
497
+ key: "parse",
498
+ value: function parse(css) {
499
+ var t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
500
+ this.reset(css);
501
+ var sheet = this.parseStylesheet();
502
+ this.stats.parseTime = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0;
503
+ return sheet;
655
504
  }
656
- } else if ((_ctx$isRule2 = ctx.isRule) !== null && _ctx$isRule2 !== void 0 && _ctx$isRule2.call(ctx, base)) {
657
- // A bare root that is registered static (reached here due to a modifier).
658
- return {
659
- kind: 'static',
660
- root: base,
661
- important: important,
662
- variants: variants,
663
- raw: raw
664
- };
665
- }
666
- return {
667
- kind: 'functional',
668
- root: root,
669
- value: value,
670
- modifier: modifier,
671
- important: important,
672
- negative: negative,
673
- variants: variants,
674
- raw: raw
675
- };
676
- }
677
-
678
- // Splits `bg-red-500` into a root and value. The longest registered root wins
679
- // (`grid-cols-3` → `grid-cols` + `3`); with no context, split at the first dash.
680
- function splitRootValue(base, ctx) {
681
- if (ctx.isDynamicRule) {
682
- // The whole class is itself the longest possible root (`rounded-t`, `border-x`);
683
- // prefer it before splitting off a shorter registered prefix (`rounded` + `t`).
684
- if (ctx.isDynamicRule(base)) return {
685
- root: base,
686
- valueStr: null
687
- };
688
- var dashes = [];
689
- for (var i = 0; i < base.length; i++) if (base[i] === '-') dashes.push(i);
690
- for (var d = dashes.length - 1; d >= 0; d--) {
691
- var idx = dashes[d];
692
- var _root2 = base.slice(0, idx);
693
- if (ctx.isDynamicRule(_root2)) return {
694
- root: _root2,
695
- valueStr: base.slice(idx + 1)
696
- };
505
+ }, {
506
+ key: "getErrors",
507
+ value: function getErrors() {
508
+ return _toConsumableArray(this.errors);
697
509
  }
698
- }
699
- var first = base.indexOf('-');
700
- if (first <= 0) return {
701
- root: base,
702
- valueStr: null
703
- };
704
- return {
705
- root: base.slice(0, first),
706
- valueStr: base.slice(first + 1)
707
- };
708
- }
709
-
710
- // Turns a parsed atom into CSS. Returns null when the utility or any of its
711
- // variants aren't registered, so an unknown class simply produces nothing.
712
- function compileAtom(atom, reg) {
713
- var produced = producedFor(atom, reg);
714
- if (!produced || produced.length === 0) return null;
715
- var flat = [];
716
- var nested = [];
717
- var _iterator = _createForOfIteratorHelper(produced),
718
- _step;
719
- try {
720
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
721
- var node = _step.value;
722
- if (node.kind === 'declaration') flat.push(node);else nested.push(node);
510
+ }, {
511
+ key: "getWarnings",
512
+ value: function getWarnings() {
513
+ return _toConsumableArray(this.warnings);
723
514
  }
724
- } catch (err) {
725
- _iterator.e(err);
726
- } finally {
727
- _iterator.f();
728
- }
729
- if (atom.important) {
730
- var _iterator2 = _createForOfIteratorHelper(flat),
731
- _step2;
732
- try {
733
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
734
- var d = _step2.value;
735
- d.important = true;
736
- }
737
- } catch (err) {
738
- _iterator2.e(err);
739
- } finally {
740
- _iterator2.f();
515
+ }, {
516
+ key: "getStats",
517
+ value: function getStats() {
518
+ return _objectSpread2({}, this.stats);
741
519
  }
742
- var _iterator3 = _createForOfIteratorHelper(nested),
743
- _step3;
744
- try {
745
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
746
- var n = _step3.value;
747
- markImportant$1(n.nodes);
748
- }
749
- } catch (err) {
750
- _iterator3.e(err);
751
- } finally {
752
- _iterator3.f();
520
+ }, {
521
+ key: "toLegacyFormat",
522
+ value: function toLegacyFormat(stylesheet) {
523
+ var _this = this;
524
+ return stylesheet.children.map(function (c) {
525
+ return _this.toLegacyNode(c);
526
+ }).filter(Boolean);
753
527
  }
754
- }
755
- var selector = '.' + escapeClass(atom.raw);
756
- var atRules = [];
757
- var _iterator4 = _createForOfIteratorHelper(atom.variants),
758
- _step4;
759
- try {
760
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
761
- var variant = _step4.value;
762
- var wrap = resolveVariant(variant, reg);
763
- if (!wrap) return null;
764
- if (wrap.selector) selector = substitute(wrap.selector, selector);
765
- if (wrap.atRule) atRules.push(wrap.atRule);
528
+
529
+ // ── Reset ─────────────────────────────────────────────────────────────────
530
+ }, {
531
+ key: "reset",
532
+ value: function reset(css) {
533
+ this.input = css;
534
+ this.pos = 0;
535
+ this.length = css.length;
536
+ this.line = 1;
537
+ this.col = 1;
538
+ this.errors = [];
539
+ this.warnings = [];
540
+ this.stats = CssParser.emptyStats();
766
541
  }
542
+ }, {
543
+ key: "parseStylesheet",
544
+ value:
545
+ // ── Stylesheet ────────────────────────────────────────────────────────────
767
546
 
768
- // Flat declarations sit on the utility's own selector; nested rules weave that
769
- // selector into their `&` (`space-x-4` → `.space-x-4 > :not([hidden]) ~ …`).
770
- } catch (err) {
771
- _iterator4.e(err);
772
- } finally {
773
- _iterator4.f();
774
- }
775
- var nodes = [];
776
- if (flat.length) nodes.push(rule(selector, flat));
777
- for (var _i = 0, _nested = nested; _i < _nested.length; _i++) {
778
- var _n = _nested[_i];
779
- nodes.push(rule(substitute(_n.selector, selector), _n.nodes));
780
- }
781
- for (var _i2 = 0, _atRules = atRules; _i2 < _atRules.length; _i2++) {
782
- var ar = _atRules[_i2];
783
- nodes = [atRule(ar.name, ar.params, nodes)];
784
- }
785
- return nodes;
786
- }
787
- function markImportant$1(nodes) {
788
- var _iterator5 = _createForOfIteratorHelper(nodes),
789
- _step5;
790
- try {
791
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
792
- var n = _step5.value;
793
- if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant$1(n.nodes);
794
- }
795
- } catch (err) {
796
- _iterator5.e(err);
797
- } finally {
798
- _iterator5.f();
799
- }
800
- }
801
- function producedFor(atom, reg) {
802
- if (atom.kind === 'arbitrary-property') {
803
- return [decl(atom.property, atom.value)];
804
- }
805
- if (atom.kind === 'static') {
806
- // Clone: static templates are shared, and `!important` / `&`-weaving mutate.
807
- var products = reg.getRule(atom.root);
808
- return products ? products.map(cloneProduct) : null;
809
- }
810
- var handler = reg.getDynamicRule(atom.root);
811
- if (!handler) return null;
812
- return handler({
813
- value: atom.value,
814
- modifier: atom.modifier,
815
- negative: atom.negative,
816
- theme: reg.theme
817
- });
818
- }
819
- function cloneProduct(n) {
820
- return n.kind === 'declaration' ? _objectSpread2({}, n) : cloneNode(n);
821
- }
822
- function cloneNode(n) {
823
- if (n.kind === 'declaration') return _objectSpread2({}, n);
824
- if (n.kind === 'rule') return rule(n.selector, n.nodes.map(cloneNode));
825
- if (n.kind === 'at-rule') return atRule(n.name, n.params, n.nodes.map(cloneNode));
826
- return _objectSpread2({}, n);
827
- }
828
- function resolveVariant(variant, reg) {
829
- if (variant.kind === 'arbitrary') return arbitraryVariant(variant.selector);
830
- if (variant.kind === 'static') return reg.getVariant(variant.root);
831
- // functional: a null value means it's really a static variant (hover, md, …).
832
- if (variant.value === null) return reg.getVariant(variant.root);
833
- var handler = reg.getDynamicVariant(variant.root);
834
- return handler ? handler(variant.value, variant.modifier) : null;
835
- }
836
-
837
- // `[&_p]` → `& p`, `[.parent_&]` → `.parent &`, `[@media(...)]` → an at-rule.
838
- // A bare selector with no `&` is attached to the element.
839
- function arbitraryVariant(source) {
840
- if (source[0] === '@') {
841
- var cut = source.search(/[\s(]/);
842
- var name = cut === -1 ? source.slice(1) : source.slice(1, cut);
843
- var params = cut === -1 ? '' : source.slice(cut).trim();
844
- return {
845
- atRule: {
846
- name: name,
847
- params: params
547
+ function parseStylesheet() {
548
+ var locStart = this.locPos();
549
+ var ss = {
550
+ type: 'stylesheet',
551
+ source: this.input,
552
+ children: [],
553
+ charset: undefined,
554
+ imports: [],
555
+ namespaces: [],
556
+ mediaQueries: [],
557
+ keyframes: [],
558
+ fontFaces: [],
559
+ layers: [],
560
+ containers: [],
561
+ supports: [],
562
+ documents: [],
563
+ pages: [],
564
+ counterStyles: [],
565
+ fontFeatureValues: [],
566
+ viewports: [],
567
+ charsets: []
568
+ };
569
+ while (this.pos < this.length) {
570
+ this.skipWS();
571
+ if (this.pos >= this.length) break;
572
+ var node = this.parseTopNode();
573
+ if (node) {
574
+ ss.children.push(node);
575
+ this.categorize(ss, node);
576
+ this.stats.totalNodes++;
577
+ }
848
578
  }
849
- };
850
- }
851
- var sel = spacesFromUnderscores(source);
852
- return {
853
- selector: sel.includes('&') ? sel : "&".concat(sel)
854
- };
855
- }
856
- function spacesFromUnderscores(s) {
857
- return s.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
858
- }
859
- function substitute(template, current) {
860
- return template.replace(/&/g, current);
861
- }
862
-
863
- // Backslash-escape everything outside [A-Za-z0-9_-] so a utility name is a valid
864
- // class selector (`hover:bg-red-500/50` → `hover\:bg-red-500\/50`).
865
- function escapeClass(name) {
866
- return name.replace(/[^a-zA-Z0-9_-]/g, function (c) {
867
- return '\\' + c;
868
- });
869
- }
870
-
871
- // `@apply a b c;` — inline the declarations those utilities produce into the
872
- // surrounding rule. Operates on author-CSS text (which `transform` passes through
873
- // verbatim), replacing each `@apply` at-rule in place. Flat utilities inline as
874
- // declarations; utilities that need their own selector (variants like `hover:` /
875
- // `group-hover:`, child-combinators like `space-x`, at-rule variants like `md:`)
876
- // emit a nested rule with `&` bound to the applying selector.
877
- var APPLY_RE = /@apply\s+([^;{}]+);/g;
878
- function expandApply(css, reg) {
879
- if (!css.includes('@apply')) return css;
880
- return css.replace(APPLY_RE, function (_match, listRaw) {
881
- var list = listRaw.trim();
882
- // A trailing `!important` marks every inlined declaration (Tailwind semantics).
883
- var important = false;
884
- var bang = list.match(/!important\s*$/);
885
- if (bang) {
886
- important = true;
887
- list = list.slice(0, bang.index).trim();
888
- }
889
- var decls = [];
890
- var rules = [];
891
- var _iterator = _createForOfIteratorHelper(list.split(/\s+/)),
892
- _step;
893
- try {
894
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
895
- var token = _step.value;
896
- if (!token) continue;
897
- var out = compileForApply(token, reg, important);
898
- if (!out) continue;
899
- if (out.decls) decls.push.apply(decls, _toConsumableArray(out.decls));
900
- if (out.rule) rules.push(out.rule);
579
+ if (this.options.includeSourceMaps) {
580
+ ss.loc = {
581
+ start: locStart,
582
+ end: this.locPos(),
583
+ source: this.input
584
+ };
901
585
  }
902
- // Flat declarations first, then nested rules — same order as authored.
903
- } catch (err) {
904
- _iterator.e(err);
905
- } finally {
906
- _iterator.f();
586
+ return ss;
907
587
  }
908
- return [].concat(decls, rules).join(' ');
909
- });
910
- }
911
- function compileForApply(cls, reg, important) {
912
- var atom = parseAtom(cls, reg);
913
- if (!atom) return null;
914
- var compiled = compileAtom(atom, reg);
915
- if (!compiled || compiled.length === 0) return null;
916
- var classSelector = '.' + escapeClass(atom.raw);
917
588
 
918
- // A plain utility — one rule on the class itself with only declarations — inlines
919
- // straight into the applying rule.
920
- if (compiled.length === 1 && compiled[0].kind === 'rule' && compiled[0].selector === classSelector) {
921
- var flat = compiled[0].nodes;
922
- if (flat.every(function (n) {
923
- return n.kind === 'declaration';
924
- })) {
925
- return {
926
- decls: flat.map(function (n) {
927
- return declText(n, important);
928
- })
929
- };
589
+ // ── Top-level node dispatch ───────────────────────────────────────────────
590
+ }, {
591
+ key: "parseTopNode",
592
+ value: function parseTopNode() {
593
+ var c = this.peek();
594
+ if (c === CC_SLASH && this.peek(1) === CC_STAR) {
595
+ var comment = this.parseComment();
596
+ return this.options.includeComments ? comment : null;
597
+ }
598
+ if (c === CC_AT) return this.parseAtRule();
599
+ // Skip stray closing braces that can appear in malformed CSS
600
+ if (c === CC_RBRACE) {
601
+ this.advance();
602
+ return null;
603
+ }
604
+ return this.parseRule();
930
605
  }
931
- }
932
606
 
933
- // Everything else keeps its structure but nests: swap the class's own selector
934
- // for `&`, so `hover:` → `&:hover`, `group-hover:` → `.group:hover &`, `md:` →
935
- // `@media(...) { & { … } }`.
936
- if (important) markImportant(compiled);
937
- var text = stringify(compiled, {
938
- minify: false
939
- }).split(classSelector).join('&');
940
- return {
941
- rule: text
942
- };
943
- }
944
- function declText(d, important) {
945
- return "".concat(d.property, ": ").concat(d.value).concat(important || d.important ? ' !important' : '', ";");
946
- }
947
- function markImportant(nodes) {
948
- var _iterator2 = _createForOfIteratorHelper(nodes),
949
- _step2;
950
- try {
951
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
952
- var n = _step2.value;
953
- if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant(n.nodes);
607
+ // ── Block-level node dispatch ─────────────────────────────────────────────
608
+ }, {
609
+ key: "parseBlockNode",
610
+ value: function parseBlockNode(mode) {
611
+ this.skipWS();
612
+ if (this.pos >= this.length || this.peek() === CC_RBRACE) return null;
613
+ var c = this.peek();
614
+ if (c === CC_SLASH && this.peek(1) === CC_STAR) {
615
+ var comment = this.parseComment();
616
+ return this.options.includeComments ? comment : null;
617
+ }
618
+ if (c === CC_AT) return this.parseAtRule(mode);
619
+ switch (mode) {
620
+ case 'keyframes':
621
+ return this.parseKeyframeStop();
622
+ case 'declarations':
623
+ return this.parseDeclaration();
624
+ case 'mixed':
625
+ case 'stylesheet':
626
+ if (c === CC_RBRACE) return null;
627
+ return this.parseRule();
628
+ case 'rule':
629
+ default:
630
+ // Unambiguous nesting-selector starters
631
+ if (this.isNestingStart(c)) return this.parseRule();
632
+ // Lookahead: first unescaped { at depth 0 → rule, ; or } → declaration
633
+ if (this.lookaheadIsRule()) return this.parseRule();
634
+ // console.log('parse block', c, mode);
635
+ return this.parseDeclaration();
636
+ }
954
637
  }
955
- } catch (err) {
956
- _iterator2.e(err);
957
- } finally {
958
- _iterator2.f();
959
- }
960
- }
961
-
962
- // Renders a `transform()` result as a compact, colourised build line for the
963
- // Vite/PostCSS plugins to print. Pure (returns a string) so css-core stays
964
- // side-effect free — the plugins own the actual `console.log`.
965
-
966
- var ANSI = {
967
- reset: '\x1b[0m',
968
- dim: '\x1b[2m',
969
- bold: '\x1b[1m',
970
- cyan: '\x1b[36m',
971
- green: '\x1b[32m',
972
- yellow: '\x1b[33m',
973
- red: '\x1b[31m'
974
- };
975
- function paint(code, s, color) {
976
- return color ? code + s + ANSI.reset : s;
977
- }
978
- function humanBytes(n) {
979
- return n < 1024 ? "".concat(n, " B") : "".concat((n / 1024).toFixed(1), " kB");
980
- }
981
- function humanMs(ms) {
982
- return ms < 1 ? "".concat(ms * 1000 | 0, " \xB5s") : ms < 1000 ? "".concat(ms.toFixed(1), " ms") : "".concat((ms / 1000).toFixed(2), " s");
983
- }
984
638
 
985
- // Green under 10 ms, yellow under 50 ms, red beyond — a quick "is it fast?" cue.
986
- function timeColor(ms) {
987
- return ms < 10 ? ANSI.green : ms < 50 ? ANSI.yellow : ANSI.red;
988
- }
989
- function formatBuildLog(label, stats) {
990
- var _options$color;
991
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
992
- var color = (_options$color = options.color) !== null && _options$color !== void 0 ? _options$color : true;
993
- var head = paint(ANSI.cyan + ANSI.bold, '◆ fluixi', color);
994
- var name = paint(ANSI.bold, label, color);
995
- var time = paint(timeColor(stats.ms), humanMs(stats.ms), color);
996
- var parts = ["".concat(stats.utilities, " ").concat(stats.utilities === 1 ? 'utility' : 'utilities'), "".concat(stats.scanned, " scanned"), humanBytes(stats.bytes)];
997
- if (stats.sources) parts.push("".concat(stats.sources, " ").concat(stats.sources === 1 ? 'source' : 'sources'));
998
- var detail = paint(ANSI.dim, parts.join(' · '), color);
999
- return "".concat(head, " ").concat(name, " ").concat(time, "\n ").concat(detail);
1000
- }
639
+ // ── At-rule ───────────────────────────────────────────────────────────────
1001
640
 
1002
- // The resolved token table. Every entry is a CSS custom property (`--color-red-500`,
1003
- // `--spacing`, `--breakpoint-md`, …); utilities read them by namespace and emit
1004
- // `var()` references, so the tokens stay live and themeable at runtime.
641
+ /** `parent` is the block the at-rule sits in: inside a style rule, a conditional group's
642
+ * body follows the rule's grammar (CSS Nesting), declarations and nested rules. */
643
+ }, {
644
+ key: "parseAtRule",
645
+ value: function parseAtRule() {
646
+ var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'stylesheet';
647
+ if (this.peek() !== CC_AT) return null;
648
+ var locStart = this.locPos();
649
+ this.advance(); // '@'
1005
650
 
1006
- var Theme = /*#__PURE__*/function () {
1007
- function Theme() {
1008
- _classCallCheck(this, Theme);
1009
- _defineProperty(this, "values", new Map());
1010
- }
1011
- return _createClass(Theme, [{
1012
- key: "add",
1013
- value: function add(name, value) {
1014
- this.values.set(name, value);
1015
- return this;
1016
- }
1017
- }, {
1018
- key: "addAll",
1019
- value: function addAll(entries) {
1020
- for (var name in entries) this.add(name, entries[name]);
1021
- return this;
1022
- }
1023
- }, {
1024
- key: "get",
1025
- value: function get(name) {
1026
- return this.values.get(name);
1027
- }
1028
- }, {
1029
- key: "has",
1030
- value: function has(name) {
1031
- return this.values.has(name);
1032
- }
651
+ var name = this.readIdent();
652
+ if (!name) {
653
+ this.recoverPast(CC_SEMI, CC_RBRACE);
654
+ return null;
655
+ }
656
+ this.skipWS();
657
+ var preludeText = this.readPrelude();
658
+ this.skipWS();
659
+ var baseName = name.replace(/^-(webkit|moz|ms|o)-/, '');
660
+ var ar = {
661
+ type: 'atrule',
662
+ name: name,
663
+ preludeText: preludeText,
664
+ prelude: this.options.parseAtrulePrelude ? this.tokenizeValue(preludeText) : []
665
+ };
666
+ if (this.options.includeVendorPrefixes) {
667
+ var vp = name.match(/^-(webkit|moz|ms|o)-/);
668
+ if (vp) ar.vendorPrefix = vp[0];
669
+ }
670
+ if (this.peek() === CC_LBRACE) {
671
+ var mode = this.modeForAtRule(baseName, parent);
672
+ var blockStart = this.locPos();
673
+ var children = this.parseBlockChildren(mode);
674
+ var blockEnd = this.locPos();
675
+ ar.block = _objectSpread2({
676
+ type: 'block',
677
+ children: children
678
+ }, this.options.includeSourceMaps ? {
679
+ loc: {
680
+ start: blockStart,
681
+ end: blockEnd
682
+ }
683
+ } : {});
1033
684
 
1034
- // A `var()` reference to `--<namespace>-<key>` when that token exists.
685
+ // Populate keyframes shortcut
686
+ if (baseName === 'keyframes') {
687
+ ar.keyframes = children.filter(function (n) {
688
+ return n.type === 'keyframe';
689
+ });
690
+ }
691
+ } else if (this.peek() === CC_SEMI) {
692
+ this.advance();
693
+ }
694
+ this.stats.totalAtRules++;
695
+ if (this.options.includeSourceMaps) {
696
+ ar.loc = {
697
+ start: locStart,
698
+ end: this.locPos(),
699
+ source: this.input
700
+ };
701
+ }
702
+ if (this.options.onAtRule) {
703
+ var result = this.options.onAtRule(ar);
704
+ if (result === null) return null;
705
+ if (result) return result;
706
+ }
707
+ return ar;
708
+ }
1035
709
  }, {
1036
- key: "resolve",
1037
- value: function resolve(namespace, key) {
1038
- var name = "--".concat(namespace, "-").concat(key);
1039
- return this.values.has(name) ? "var(".concat(name, ")") : null;
710
+ key: "modeForAtRule",
711
+ value: function modeForAtRule(baseName) {
712
+ var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'stylesheet';
713
+ // AWC encodes comments as @comment-XXXXXXXX { --rule-...: "..."; }
714
+ // which contain only declarations — must NOT use mixed/rule mode or
715
+ // readUntilLBrace() will consume past the closing } and corrupt state.
716
+ if (baseName.startsWith('comment')) return 'declarations';
717
+ switch (baseName) {
718
+ case 'keyframes':
719
+ return 'keyframes';
720
+ case 'font-face':
721
+ case 'page':
722
+ case 'counter-style':
723
+ case 'viewport':
724
+ case 'theme':
725
+ return 'declarations';
726
+ // `@utility` bodies mix flat declarations with nested rules
727
+ // (`&:hover`, `&::-webkit-scrollbar`); `rule` mode does the
728
+ // declaration-vs-nesting lookahead. (`mixed` would read every line
729
+ // as a selector and corrupt the block.)
730
+ case 'utility':
731
+ return 'rule';
732
+ // Nested in a style rule, `@media { color: red }` holds declarations: read in
733
+ // `mixed` mode, `color: red` became a selector that ran past the closing brace
734
+ // and swallowed every rule after it.
735
+ case 'media':
736
+ case 'supports':
737
+ case 'container':
738
+ case 'layer':
739
+ case 'document':
740
+ default:
741
+ return parent === 'rule' ? 'rule' : 'mixed';
742
+ }
1040
743
  }
1041
744
 
1042
- // Bare keys registered under a namespace, e.g. every color name.
745
+ // ── Regular rule ──────────────────────────────────────────────────────────
1043
746
  }, {
1044
- key: "keysIn",
1045
- value: function keysIn(namespace) {
1046
- var prefix = "--".concat(namespace, "-");
1047
- var out = [];
1048
- var _iterator = _createForOfIteratorHelper(this.values.keys()),
747
+ key: "parseRule",
748
+ value: function parseRule() {
749
+ var locStart = this.locPos();
750
+ var rawSelector = this.readUntilLBrace().trim();
751
+ if (!rawSelector || this.peek() !== CC_LBRACE) {
752
+ // Malformed — skip to closing brace
753
+ if (this.peek() === CC_LBRACE) {
754
+ this.skipBalancedBraces();
755
+ }
756
+ return null;
757
+ }
758
+ var mode = this.options.enableNesting ? 'rule' : 'declarations';
759
+ var children = this.parseBlockChildren(mode);
760
+ var declarations = [];
761
+ var nested = [];
762
+ var _iterator = _createForOfIteratorHelper(children),
1049
763
  _step;
1050
764
  try {
1051
765
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
1052
- var name = _step.value;
1053
- if (name.startsWith(prefix)) out.push(name.slice(prefix.length));
766
+ var child = _step.value;
767
+ var t = child.type;
768
+ if (t === 'declaration') declarations.push(child);else if (t === 'rule') nested.push(child);else if (t === 'atrule') nested.push(child);
1054
769
  }
1055
770
  } catch (err) {
1056
771
  _iterator.e(err);
1057
772
  } finally {
1058
773
  _iterator.f();
1059
774
  }
1060
- return out;
775
+ var selectors = this.parseSelectorList(rawSelector);
776
+ this.stats.totalRules++;
777
+ this.stats.totalSelectors += selectors.length;
778
+ var rule = {
779
+ type: 'rule',
780
+ rawSelector: rawSelector,
781
+ selectors: selectors,
782
+ declarations: declarations
783
+ };
784
+ if (nested.length > 0) rule.children = nested;
785
+ if (this.options.includeSpecificity) {
786
+ rule.specificity = this.calcSpecificity(rawSelector);
787
+ }
788
+ if (this.options.includeSourceMaps) {
789
+ rule.loc = {
790
+ start: locStart,
791
+ end: this.locPos(),
792
+ source: this.input
793
+ };
794
+ }
795
+ if (this.options.onRule) {
796
+ var result = this.options.onRule(rule);
797
+ if (result === null) return null;
798
+ if (result) return result;
799
+ }
800
+ return rule;
1061
801
  }
802
+
803
+ // ── Keyframe stop (from / to / <percentage>) ──────────────────────────────
1062
804
  }, {
1063
- key: "entries",
1064
- value: function entries() {
1065
- return _toConsumableArray(this.values.entries());
805
+ key: "parseKeyframeStop",
806
+ value: function parseKeyframeStop() {
807
+ var locStart = this.locPos();
808
+ var selector = this.readUntilLBrace().trim();
809
+ if (!selector || this.peek() !== CC_LBRACE) return null;
810
+ var children = this.parseBlockChildren('declarations');
811
+ var declarations = children.filter(function (n) {
812
+ return n.type === 'declaration';
813
+ });
814
+ var kf = _objectSpread2({
815
+ type: 'keyframe',
816
+ selector: selector,
817
+ declarations: declarations
818
+ }, this.options.includeSourceMaps ? {
819
+ loc: {
820
+ start: locStart,
821
+ end: this.locPos()
822
+ }
823
+ } : {});
824
+ if (this.options.onKeyframe) {
825
+ var result = this.options.onKeyframe(kf);
826
+ if (result === null) return null;
827
+ if (result) return result;
828
+ }
829
+ return kf;
1066
830
  }
1067
- }]);
1068
- }();
1069
-
1070
- // ─── Charcode constants (avoids string allocation on hot paths) ───────────────
1071
- var CC_TAB = 9,
1072
- CC_LF = 10,
1073
- CC_CR = 13,
1074
- CC_FF = 12,
1075
- CC_SPACE = 32;
1076
- var CC_DQUOTE = 34,
1077
- CC_HASH = 35,
1078
- CC_AMP = 38,
1079
- CC_SQUOTE = 39;
1080
- var CC_LPAREN = 40,
1081
- CC_RPAREN = 41,
1082
- CC_STAR = 42,
1083
- CC_PLUS = 43;
1084
- var CC_COMMA = 44,
1085
- CC_MINUS = 45,
1086
- CC_DOT = 46,
1087
- CC_SLASH = 47;
1088
- var CC_COLON = 58,
1089
- CC_SEMI = 59,
1090
- CC_GT = 62;
1091
- var CC_AT = 64,
1092
- CC_LBRACK = 91,
1093
- CC_BSLASH = 92,
1094
- CC_RBRACK = 93;
1095
- var CC_UNDER = 95,
1096
- CC_LBRACE = 123,
1097
- CC_RBRACE = 125,
1098
- CC_TILDE = 126;
1099
831
 
1100
- // ─── Character predicates (charcode-based, no regex) ─────────────────────────
832
+ // ── Block (consumes { … }) ────────────────────────────────────────────────
833
+ }, {
834
+ key: "parseBlockChildren",
835
+ value: function parseBlockChildren(mode) {
836
+ if (this.peek() !== CC_LBRACE) return [];
837
+ this.advance(); // '{'
1101
838
 
1102
- function isWS(c) {
1103
- return c === CC_SPACE || c === CC_TAB || c === CC_LF || c === CC_CR || c === CC_FF;
1104
- }
1105
- function isDigit(c) {
1106
- return c >= 48 && c <= 57;
1107
- }
1108
- function isAlpha(c) {
1109
- return c >= 65 && c <= 90 || c >= 97 && c <= 122;
1110
- }
1111
- function isHex(c) {
1112
- return isDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
1113
- }
1114
- /**
1115
- * CSS ident-start: letter | underscore | non-ASCII | hyphen.
1116
- * A leading hyphen is valid (vendor prefixes, custom properties).
1117
- */
1118
- function isNameStart(c) {
1119
- return isAlpha(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
1120
- }
1121
- /** CSS ident-char: ident-start | digit */
1122
- function isNameChar(c) {
1123
- return isAlpha(c) || isDigit(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
1124
- }
1125
-
1126
- // ─── Block context ────────────────────────────────────────────────────────────
1127
-
1128
- /**
1129
- * Determines what may legally appear inside a block:
1130
- * stylesheet – top-level: rules + at-rules
1131
- * mixed – @media/@supports/@container/@layer: rules + at-rules
1132
- * rule – inside a style rule: declarations + optional CSS nesting
1133
- * keyframes – inside @keyframes: keyframe stops (from/to/%)
1134
- * declarations– @font-face/@page/etc.: declarations only
1135
- */
1136
-
1137
- // ─── CssParser ────────────────────────────────────────────────────────────────
1138
-
1139
- var CssParser = /*#__PURE__*/function () {
1140
- function CssParser() {
1141
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1142
- _classCallCheck(this, CssParser);
1143
- _defineProperty(this, "input", '');
1144
- _defineProperty(this, "pos", 0);
1145
- _defineProperty(this, "length", 0);
1146
- _defineProperty(this, "line", 1);
1147
- _defineProperty(this, "col", 1);
1148
- _defineProperty(this, "errors", []);
1149
- _defineProperty(this, "warnings", []);
1150
- _defineProperty(this, "stats", CssParser.emptyStats());
1151
- this.options = _objectSpread2({
1152
- parseAtrulePrelude: true,
1153
- parseValue: true,
1154
- parseCustomProperty: true,
1155
- parseRulePrelude: true,
1156
- parseSelector: true,
1157
- includeComments: true,
1158
- includeSourceMaps: true,
1159
- includeSpecificity: true,
1160
- includeVendorPrefixes: true,
1161
- onError: function onError() {/* noop */},
1162
- onWarning: function onWarning() {/* noop */},
1163
- maxDepth: 100,
1164
- maxNodes: 100000,
1165
- enableNesting: true,
1166
- enableCustomProperties: true,
1167
- enableLogicalProperties: true,
1168
- enableContainerQueries: true,
1169
- enableLayerQueries: true,
1170
- enableSupportsQueries: true,
1171
- // middleware — undefined by default (fast path skips them)
1172
- onRule: undefined,
1173
- onAtRule: undefined,
1174
- onDeclaration: undefined,
1175
- onComment: undefined,
1176
- onKeyframe: undefined
1177
- }, options);
1178
- }
1179
-
1180
- // ── Public API ────────────────────────────────────────────────────────────
1181
- return _createClass(CssParser, [{
1182
- key: "parse",
1183
- value: function parse(css) {
1184
- var t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
1185
- this.reset(css);
1186
- var sheet = this.parseStylesheet();
1187
- this.stats.parseTime = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0;
1188
- return sheet;
1189
- }
1190
- }, {
1191
- key: "getErrors",
1192
- value: function getErrors() {
1193
- return _toConsumableArray(this.errors);
1194
- }
1195
- }, {
1196
- key: "getWarnings",
1197
- value: function getWarnings() {
1198
- return _toConsumableArray(this.warnings);
1199
- }
1200
- }, {
1201
- key: "getStats",
1202
- value: function getStats() {
1203
- return _objectSpread2({}, this.stats);
1204
- }
1205
- }, {
1206
- key: "toLegacyFormat",
1207
- value: function toLegacyFormat(stylesheet) {
1208
- var _this = this;
1209
- return stylesheet.children.map(function (c) {
1210
- return _this.toLegacyNode(c);
1211
- }).filter(Boolean);
1212
- }
1213
-
1214
- // ── Reset ─────────────────────────────────────────────────────────────────
1215
- }, {
1216
- key: "reset",
1217
- value: function reset(css) {
1218
- this.input = css;
1219
- this.pos = 0;
1220
- this.length = css.length;
1221
- this.line = 1;
1222
- this.col = 1;
1223
- this.errors = [];
1224
- this.warnings = [];
1225
- this.stats = CssParser.emptyStats();
1226
- }
1227
- }, {
1228
- key: "parseStylesheet",
1229
- value:
1230
- // ── Stylesheet ────────────────────────────────────────────────────────────
1231
-
1232
- function parseStylesheet() {
1233
- var locStart = this.locPos();
1234
- var ss = {
1235
- type: 'stylesheet',
1236
- source: this.input,
1237
- children: [],
1238
- charset: undefined,
1239
- imports: [],
1240
- namespaces: [],
1241
- mediaQueries: [],
1242
- keyframes: [],
1243
- fontFaces: [],
1244
- layers: [],
1245
- containers: [],
1246
- supports: [],
1247
- documents: [],
1248
- pages: [],
1249
- counterStyles: [],
1250
- fontFeatureValues: [],
1251
- viewports: [],
1252
- charsets: []
1253
- };
839
+ var children = [];
1254
840
  while (this.pos < this.length) {
1255
841
  this.skipWS();
1256
- if (this.pos >= this.length) break;
1257
- var node = this.parseTopNode();
842
+ if (this.pos >= this.length || this.peek() === CC_RBRACE) break;
843
+ var prevPos = this.pos;
844
+ var node = this.parseBlockNode(mode);
845
+ // Guard against infinite loop: if nothing was consumed, force-advance
846
+ if (this.pos === prevPos) {
847
+ this.advance();
848
+ continue;
849
+ }
1258
850
  if (node) {
1259
- ss.children.push(node);
1260
- this.categorize(ss, node);
851
+ children.push(node);
1261
852
  this.stats.totalNodes++;
1262
853
  }
1263
854
  }
1264
- if (this.options.includeSourceMaps) {
1265
- ss.loc = {
1266
- start: locStart,
1267
- end: this.locPos(),
1268
- source: this.input
1269
- };
1270
- }
1271
- return ss;
855
+ if (this.pos < this.length && this.peek() === CC_RBRACE) this.advance(); // '}'
856
+ return children;
1272
857
  }
1273
858
 
1274
- // ── Top-level node dispatch ───────────────────────────────────────────────
859
+ // ── Declaration ───────────────────────────────────────────────────────────
1275
860
  }, {
1276
- key: "parseTopNode",
1277
- value: function parseTopNode() {
1278
- var c = this.peek();
1279
- if (c === CC_SLASH && this.peek(1) === CC_STAR) {
1280
- var comment = this.parseComment();
1281
- return this.options.includeComments ? comment : null;
861
+ key: "parseDeclaration",
862
+ value: function parseDeclaration() {
863
+ var locStart = this.locPos();
864
+
865
+ // Property name (supports --custom-props and -vendor-prefixed)
866
+ var property = this.readIdent();
867
+ if (!property) {
868
+ this.recoverTo(CC_SEMI, CC_RBRACE);
869
+ return null;
1282
870
  }
1283
- if (c === CC_AT) return this.parseAtRule();
1284
- // Skip stray closing braces that can appear in malformed CSS
1285
- if (c === CC_RBRACE) {
1286
- this.advance();
871
+ this.skipWS();
872
+ if (this.peek() !== CC_COLON) {
873
+ this.recoverTo(CC_SEMI, CC_RBRACE);
1287
874
  return null;
1288
875
  }
1289
- return this.parseRule();
1290
- }
876
+ this.advance(); // ':'
877
+ this.skipWS();
878
+ var rawFull = this.readRawValue();
1291
879
 
1292
- // ── Block-level node dispatch ─────────────────────────────────────────────
1293
- }, {
1294
- key: "parseBlockNode",
1295
- value: function parseBlockNode(mode) {
880
+ // Strip !important
881
+ var rawValue = rawFull;
882
+ var important = false;
883
+ var impMatch = rawFull.match(/\s*!important\s*$/i);
884
+ if (impMatch) {
885
+ important = true;
886
+ rawValue = rawFull.slice(0, rawFull.length - impMatch[0].length).trimEnd();
887
+ }
1296
888
  this.skipWS();
1297
- if (this.pos >= this.length || this.peek() === CC_RBRACE) return null;
1298
- var c = this.peek();
1299
- if (c === CC_SLASH && this.peek(1) === CC_STAR) {
1300
- var comment = this.parseComment();
1301
- return this.options.includeComments ? comment : null;
889
+ if (this.pos < this.length && this.peek() === CC_SEMI) this.advance();
890
+ this.stats.totalDeclarations++;
891
+ var decl = {
892
+ type: 'declaration',
893
+ property: property,
894
+ rawValue: rawValue,
895
+ value: this.options.parseValue ? this.tokenizeValue(rawValue) : [],
896
+ important: important
897
+ };
898
+ if (this.options.enableCustomProperties && property.startsWith('--')) {
899
+ decl.customProperty = true;
1302
900
  }
1303
- if (c === CC_AT) return this.parseAtRule();
1304
- switch (mode) {
1305
- case 'keyframes':
1306
- return this.parseKeyframeStop();
1307
- case 'declarations':
1308
- return this.parseDeclaration();
1309
- case 'mixed':
1310
- case 'stylesheet':
1311
- if (c === CC_RBRACE) return null;
1312
- return this.parseRule();
1313
- case 'rule':
1314
- default:
1315
- // Unambiguous nesting-selector starters
1316
- if (this.isNestingStart(c)) return this.parseRule();
1317
- // Lookahead: first unescaped { at depth 0 → rule, ; or } → declaration
1318
- if (this.lookaheadIsRule()) return this.parseRule();
1319
- // console.log('parse block', c, mode);
1320
- return this.parseDeclaration();
901
+ if (this.options.includeVendorPrefixes) {
902
+ var vp = property.match(/^-(webkit|moz|ms|o)-/);
903
+ if (vp) decl.vendorPrefix = vp[0];
904
+ }
905
+ if (this.options.includeSourceMaps) {
906
+ decl.loc = {
907
+ start: locStart,
908
+ end: this.locPos(),
909
+ source: this.input
910
+ };
911
+ }
912
+ if (this.options.onDeclaration) {
913
+ var result = this.options.onDeclaration(decl);
914
+ if (result === null) return null;
915
+ if (result) return result;
1321
916
  }
917
+ return decl;
1322
918
  }
1323
919
 
1324
- // ── At-rule ───────────────────────────────────────────────────────────────
920
+ // ── Comment ───────────────────────────────────────────────────────────────
1325
921
  }, {
1326
- key: "parseAtRule",
1327
- value: function parseAtRule() {
1328
- if (this.peek() !== CC_AT) return null;
1329
- var locStart = this.locPos();
1330
- this.advance(); // '@'
1331
-
1332
- var name = this.readIdent();
1333
- if (!name) {
1334
- this.recoverPast(CC_SEMI, CC_RBRACE);
1335
- return null;
1336
- }
1337
- this.skipWS();
1338
- var preludeText = this.readPrelude();
1339
- this.skipWS();
1340
- var baseName = name.replace(/^-(webkit|moz|ms|o)-/, '');
1341
- var ar = {
1342
- type: 'atrule',
1343
- name: name,
1344
- preludeText: preludeText,
1345
- prelude: this.options.parseAtrulePrelude ? this.tokenizeValue(preludeText) : []
1346
- };
1347
- if (this.options.includeVendorPrefixes) {
1348
- var vp = name.match(/^-(webkit|moz|ms|o)-/);
1349
- if (vp) ar.vendorPrefix = vp[0];
1350
- }
1351
- if (this.peek() === CC_LBRACE) {
1352
- var mode = this.modeForAtRule(baseName);
1353
- var blockStart = this.locPos();
1354
- var children = this.parseBlockChildren(mode);
1355
- var blockEnd = this.locPos();
1356
- ar.block = _objectSpread2({
1357
- type: 'block',
1358
- children: children
1359
- }, this.options.includeSourceMaps ? {
1360
- loc: {
1361
- start: blockStart,
1362
- end: blockEnd
922
+ key: "parseComment",
923
+ value: function parseComment() {
924
+ var locStart = this.locPos();
925
+ this.advance(); // '/'
926
+ this.advance(); // '*'
927
+ var start = this.pos;
928
+ while (this.pos < this.length - 1) {
929
+ if (this.peek() === CC_STAR && this.peek(1) === CC_SLASH) {
930
+ var _value = this.input.slice(start, this.pos);
931
+ this.advance();
932
+ this.advance(); // '*/'
933
+ this.stats.totalComments++;
934
+ var _c = _objectSpread2({
935
+ type: 'comment',
936
+ value: _value,
937
+ style: _value.includes('\n') ? 'multi-line' : 'single-line'
938
+ }, this.options.includeSourceMaps ? {
939
+ loc: {
940
+ start: locStart,
941
+ end: this.locPos()
942
+ }
943
+ } : {});
944
+ if (this.options.onComment) {
945
+ var result = this.options.onComment(_c);
946
+ if (result === null) return null;
947
+ if (result) return result;
1363
948
  }
1364
- } : {});
1365
-
1366
- // Populate keyframes shortcut
1367
- if (baseName === 'keyframes') {
1368
- ar.keyframes = children.filter(function (n) {
1369
- return n.type === 'keyframe';
1370
- });
949
+ return _c;
1371
950
  }
1372
- } else if (this.peek() === CC_SEMI) {
1373
951
  this.advance();
1374
952
  }
1375
- this.stats.totalAtRules++;
1376
- if (this.options.includeSourceMaps) {
1377
- ar.loc = {
1378
- start: locStart,
1379
- end: this.locPos(),
1380
- source: this.input
1381
- };
1382
- }
1383
- if (this.options.onAtRule) {
1384
- var result = this.options.onAtRule(ar);
1385
- if (result === null) return null;
1386
- if (result) return result;
953
+
954
+ // Unterminated comment
955
+ var value = this.input.slice(start);
956
+ this.pos = this.length;
957
+ this.stats.totalComments++;
958
+ var c = {
959
+ type: 'comment',
960
+ value: value,
961
+ style: 'multi-line'
962
+ };
963
+ if (this.options.onComment) {
964
+ var _result = this.options.onComment(c);
965
+ if (_result === null) return null;
966
+ if (_result) return _result;
1387
967
  }
1388
- return ar;
968
+ return c;
1389
969
  }
970
+
971
+ // ── Selectors ─────────────────────────────────────────────────────────────
972
+
973
+ /**
974
+ * Splits a raw selector string on commas (respecting parentheses depth)
975
+ * and returns one CssSelector per part.
976
+ */
1390
977
  }, {
1391
- key: "modeForAtRule",
1392
- value: function modeForAtRule(baseName) {
1393
- // AWC encodes comments as @comment-XXXXXXXX { --rule-...: "..."; }
1394
- // which contain only declarations — must NOT use mixed/rule mode or
1395
- // readUntilLBrace() will consume past the closing } and corrupt state.
1396
- if (baseName.startsWith('comment')) return 'declarations';
1397
- switch (baseName) {
1398
- case 'keyframes':
1399
- return 'keyframes';
1400
- case 'font-face':
1401
- case 'page':
1402
- case 'counter-style':
1403
- case 'viewport':
1404
- case 'theme':
1405
- return 'declarations';
1406
- // `@utility` bodies mix flat declarations with nested rules
1407
- // (`&:hover`, `&::-webkit-scrollbar`); `rule` mode does the
1408
- // declaration-vs-nesting lookahead. (`mixed` would read every line
1409
- // as a selector and corrupt the block.)
1410
- case 'utility':
1411
- return 'rule';
1412
- case 'media':
1413
- case 'supports':
1414
- case 'container':
1415
- case 'layer':
1416
- case 'document':
1417
- default:
1418
- return 'mixed';
978
+ key: "parseSelectorList",
979
+ value: function parseSelectorList(raw) {
980
+ var parts = [];
981
+ var depth = 0,
982
+ start = 0;
983
+ for (var i = 0; i < raw.length; i++) {
984
+ var c = raw.charCodeAt(i);
985
+ if (c === CC_LPAREN || c === CC_LBRACK) depth++;else if (c === CC_RPAREN || c === CC_RBRACK) depth--;else if (c === CC_COMMA && depth === 0) {
986
+ parts.push(raw.slice(start, i).trim());
987
+ start = i + 1;
988
+ }
1419
989
  }
990
+ parts.push(raw.slice(start).trim());
991
+ return parts.filter(function (p) {
992
+ return p.length > 0;
993
+ }).map(function (p) {
994
+ return {
995
+ type: 'selector',
996
+ value: p
997
+ };
998
+ });
1420
999
  }
1421
1000
 
1422
- // ── Regular rule ──────────────────────────────────────────────────────────
1001
+ /**
1002
+ * Simple specificity scorer — counts IDs, classes/attributes/pseudos, elements.
1003
+ */
1423
1004
  }, {
1424
- key: "parseRule",
1425
- value: function parseRule() {
1426
- var locStart = this.locPos();
1427
- var rawSelector = this.readUntilLBrace().trim();
1428
- if (!rawSelector || this.peek() !== CC_LBRACE) {
1429
- // Malformed — skip to closing brace
1430
- if (this.peek() === CC_LBRACE) {
1431
- this.skipBalancedBraces();
1432
- }
1433
- return null;
1434
- }
1435
- var mode = this.options.enableNesting ? 'rule' : 'declarations';
1436
- var children = this.parseBlockChildren(mode);
1437
- var declarations = [];
1438
- var nested = [];
1439
- var _iterator = _createForOfIteratorHelper(children),
1440
- _step;
1441
- try {
1442
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1443
- var child = _step.value;
1444
- var t = child.type;
1445
- if (t === 'declaration') declarations.push(child);else if (t === 'rule') nested.push(child);else if (t === 'atrule') nested.push(child);
1005
+ key: "calcSpecificity",
1006
+ value: function calcSpecificity(sel) {
1007
+ var ids = 0,
1008
+ classes = 0,
1009
+ elements = 0;
1010
+ var i = 0;
1011
+ while (i < sel.length) {
1012
+ var c = sel.charCodeAt(i);
1013
+ if (c === CC_HASH) {
1014
+ ids++;
1015
+ i++;
1016
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1017
+ } else if (c === CC_DOT) {
1018
+ classes++;
1019
+ i++;
1020
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1021
+ } else if (c === CC_LBRACK) {
1022
+ classes++;
1023
+ while (i < sel.length && sel.charCodeAt(i) !== CC_RBRACK) i++;
1024
+ i++;
1025
+ } else if (c === CC_COLON) {
1026
+ if (sel.charCodeAt(i + 1) === CC_COLON) {
1027
+ elements++;
1028
+ i += 2;
1029
+ } else {
1030
+ // :not(), :is(), :has() — don't double-count the wrapper
1031
+ classes++;
1032
+ i++;
1033
+ }
1034
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1035
+ // skip argument parens
1036
+ if (i < sel.length && sel.charCodeAt(i) === CC_LPAREN) {
1037
+ var d = 1;
1038
+ i++;
1039
+ while (i < sel.length && d > 0) {
1040
+ if (sel.charCodeAt(i) === CC_LPAREN) d++;else if (sel.charCodeAt(i) === CC_RPAREN) d--;
1041
+ i++;
1042
+ }
1043
+ }
1044
+ } else if (isAlpha(c) || c === CC_UNDER) {
1045
+ elements++;
1046
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1047
+ } else {
1048
+ i++;
1446
1049
  }
1447
- } catch (err) {
1448
- _iterator.e(err);
1449
- } finally {
1450
- _iterator.f();
1451
1050
  }
1452
- var selectors = this.parseSelectorList(rawSelector);
1453
- this.stats.totalRules++;
1454
- this.stats.totalSelectors += selectors.length;
1455
- var rule = {
1456
- type: 'rule',
1457
- rawSelector: rawSelector,
1458
- selectors: selectors,
1459
- declarations: declarations
1460
- };
1461
- if (nested.length > 0) rule.children = nested;
1462
- if (this.options.includeSpecificity) {
1463
- rule.specificity = this.calcSpecificity(rawSelector);
1464
- }
1465
- if (this.options.includeSourceMaps) {
1466
- rule.loc = {
1467
- start: locStart,
1468
- end: this.locPos(),
1469
- source: this.input
1470
- };
1471
- }
1472
- if (this.options.onRule) {
1473
- var result = this.options.onRule(rule);
1474
- if (result === null) return null;
1475
- if (result) return result;
1476
- }
1477
- return rule;
1478
- }
1479
-
1480
- // ── Keyframe stop (from / to / <percentage>) ──────────────────────────────
1481
- }, {
1482
- key: "parseKeyframeStop",
1483
- value: function parseKeyframeStop() {
1484
- var locStart = this.locPos();
1485
- var selector = this.readUntilLBrace().trim();
1486
- if (!selector || this.peek() !== CC_LBRACE) return null;
1487
- var children = this.parseBlockChildren('declarations');
1488
- var declarations = children.filter(function (n) {
1489
- return n.type === 'declaration';
1490
- });
1491
- var kf = _objectSpread2({
1492
- type: 'keyframe',
1493
- selector: selector,
1494
- declarations: declarations
1495
- }, this.options.includeSourceMaps ? {
1496
- loc: {
1497
- start: locStart,
1498
- end: this.locPos()
1499
- }
1500
- } : {});
1501
- if (this.options.onKeyframe) {
1502
- var result = this.options.onKeyframe(kf);
1503
- if (result === null) return null;
1504
- if (result) return result;
1505
- }
1506
- return kf;
1507
- }
1508
-
1509
- // ── Block (consumes { … }) ────────────────────────────────────────────────
1510
- }, {
1511
- key: "parseBlockChildren",
1512
- value: function parseBlockChildren(mode) {
1513
- if (this.peek() !== CC_LBRACE) return [];
1514
- this.advance(); // '{'
1515
-
1516
- var children = [];
1517
- while (this.pos < this.length) {
1518
- this.skipWS();
1519
- if (this.pos >= this.length || this.peek() === CC_RBRACE) break;
1520
- var prevPos = this.pos;
1521
- var node = this.parseBlockNode(mode);
1522
- // Guard against infinite loop: if nothing was consumed, force-advance
1523
- if (this.pos === prevPos) {
1524
- this.advance();
1525
- continue;
1526
- }
1527
- if (node) {
1528
- children.push(node);
1529
- this.stats.totalNodes++;
1530
- }
1531
- }
1532
- if (this.pos < this.length && this.peek() === CC_RBRACE) this.advance(); // '}'
1533
- return children;
1534
- }
1535
-
1536
- // ── Declaration ───────────────────────────────────────────────────────────
1537
- }, {
1538
- key: "parseDeclaration",
1539
- value: function parseDeclaration() {
1540
- var locStart = this.locPos();
1541
-
1542
- // Property name (supports --custom-props and -vendor-prefixed)
1543
- var property = this.readIdent();
1544
- if (!property) {
1545
- this.recoverTo(CC_SEMI, CC_RBRACE);
1546
- return null;
1547
- }
1548
- this.skipWS();
1549
- if (this.peek() !== CC_COLON) {
1550
- this.recoverTo(CC_SEMI, CC_RBRACE);
1551
- return null;
1552
- }
1553
- this.advance(); // ':'
1554
- this.skipWS();
1555
- var rawFull = this.readRawValue();
1556
-
1557
- // Strip !important
1558
- var rawValue = rawFull;
1559
- var important = false;
1560
- var impMatch = rawFull.match(/\s*!important\s*$/i);
1561
- if (impMatch) {
1562
- important = true;
1563
- rawValue = rawFull.slice(0, rawFull.length - impMatch[0].length).trimEnd();
1564
- }
1565
- this.skipWS();
1566
- if (this.pos < this.length && this.peek() === CC_SEMI) this.advance();
1567
- this.stats.totalDeclarations++;
1568
- var decl = {
1569
- type: 'declaration',
1570
- property: property,
1571
- rawValue: rawValue,
1572
- value: this.options.parseValue ? this.tokenizeValue(rawValue) : [],
1573
- important: important
1574
- };
1575
- if (this.options.enableCustomProperties && property.startsWith('--')) {
1576
- decl.customProperty = true;
1577
- }
1578
- if (this.options.includeVendorPrefixes) {
1579
- var vp = property.match(/^-(webkit|moz|ms|o)-/);
1580
- if (vp) decl.vendorPrefix = vp[0];
1581
- }
1582
- if (this.options.includeSourceMaps) {
1583
- decl.loc = {
1584
- start: locStart,
1585
- end: this.locPos(),
1586
- source: this.input
1587
- };
1588
- }
1589
- if (this.options.onDeclaration) {
1590
- var result = this.options.onDeclaration(decl);
1591
- if (result === null) return null;
1592
- if (result) return result;
1593
- }
1594
- return decl;
1595
- }
1596
-
1597
- // ── Comment ───────────────────────────────────────────────────────────────
1598
- }, {
1599
- key: "parseComment",
1600
- value: function parseComment() {
1601
- var locStart = this.locPos();
1602
- this.advance(); // '/'
1603
- this.advance(); // '*'
1604
- var start = this.pos;
1605
- while (this.pos < this.length - 1) {
1606
- if (this.peek() === CC_STAR && this.peek(1) === CC_SLASH) {
1607
- var _value = this.input.slice(start, this.pos);
1608
- this.advance();
1609
- this.advance(); // '*/'
1610
- this.stats.totalComments++;
1611
- var _c = _objectSpread2({
1612
- type: 'comment',
1613
- value: _value,
1614
- style: _value.includes('\n') ? 'multi-line' : 'single-line'
1615
- }, this.options.includeSourceMaps ? {
1616
- loc: {
1617
- start: locStart,
1618
- end: this.locPos()
1619
- }
1620
- } : {});
1621
- if (this.options.onComment) {
1622
- var result = this.options.onComment(_c);
1623
- if (result === null) return null;
1624
- if (result) return result;
1625
- }
1626
- return _c;
1627
- }
1628
- this.advance();
1629
- }
1630
-
1631
- // Unterminated comment
1632
- var value = this.input.slice(start);
1633
- this.pos = this.length;
1634
- this.stats.totalComments++;
1635
- var c = {
1636
- type: 'comment',
1637
- value: value,
1638
- style: 'multi-line'
1639
- };
1640
- if (this.options.onComment) {
1641
- var _result = this.options.onComment(c);
1642
- if (_result === null) return null;
1643
- if (_result) return _result;
1644
- }
1645
- return c;
1646
- }
1647
-
1648
- // ── Selectors ─────────────────────────────────────────────────────────────
1649
-
1650
- /**
1651
- * Splits a raw selector string on commas (respecting parentheses depth)
1652
- * and returns one CssSelector per part.
1653
- */
1654
- }, {
1655
- key: "parseSelectorList",
1656
- value: function parseSelectorList(raw) {
1657
- var parts = [];
1658
- var depth = 0,
1659
- start = 0;
1660
- for (var i = 0; i < raw.length; i++) {
1661
- var c = raw.charCodeAt(i);
1662
- if (c === CC_LPAREN || c === CC_LBRACK) depth++;else if (c === CC_RPAREN || c === CC_RBRACK) depth--;else if (c === CC_COMMA && depth === 0) {
1663
- parts.push(raw.slice(start, i).trim());
1664
- start = i + 1;
1665
- }
1666
- }
1667
- parts.push(raw.slice(start).trim());
1668
- return parts.filter(function (p) {
1669
- return p.length > 0;
1670
- }).map(function (p) {
1671
- return {
1672
- type: 'selector',
1673
- value: p
1674
- };
1675
- });
1676
- }
1677
-
1678
- /**
1679
- * Simple specificity scorer — counts IDs, classes/attributes/pseudos, elements.
1680
- */
1681
- }, {
1682
- key: "calcSpecificity",
1683
- value: function calcSpecificity(sel) {
1684
- var ids = 0,
1685
- classes = 0,
1686
- elements = 0;
1687
- var i = 0;
1688
- while (i < sel.length) {
1689
- var c = sel.charCodeAt(i);
1690
- if (c === CC_HASH) {
1691
- ids++;
1692
- i++;
1693
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1694
- } else if (c === CC_DOT) {
1695
- classes++;
1696
- i++;
1697
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1698
- } else if (c === CC_LBRACK) {
1699
- classes++;
1700
- while (i < sel.length && sel.charCodeAt(i) !== CC_RBRACK) i++;
1701
- i++;
1702
- } else if (c === CC_COLON) {
1703
- if (sel.charCodeAt(i + 1) === CC_COLON) {
1704
- elements++;
1705
- i += 2;
1706
- } else {
1707
- // :not(), :is(), :has() — don't double-count the wrapper
1708
- classes++;
1709
- i++;
1710
- }
1711
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1712
- // skip argument parens
1713
- if (i < sel.length && sel.charCodeAt(i) === CC_LPAREN) {
1714
- var d = 1;
1715
- i++;
1716
- while (i < sel.length && d > 0) {
1717
- if (sel.charCodeAt(i) === CC_LPAREN) d++;else if (sel.charCodeAt(i) === CC_RPAREN) d--;
1718
- i++;
1719
- }
1720
- }
1721
- } else if (isAlpha(c) || c === CC_UNDER) {
1722
- elements++;
1723
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1724
- } else {
1725
- i++;
1726
- }
1727
- }
1728
- return {
1729
- ids: ids,
1730
- classes: classes,
1731
- elements: elements,
1732
- total: ids * 100 + classes * 10 + elements
1051
+ return {
1052
+ ids: ids,
1053
+ classes: classes,
1054
+ elements: elements,
1055
+ total: ids * 100 + classes * 10 + elements
1733
1056
  };
1734
1057
  }
1735
1058
 
@@ -2413,430 +1736,567 @@ function parseCss(css, options) {
2413
1736
  return new CssParser(options).parse(css);
2414
1737
  }
2415
1738
 
2416
- // Read `@theme { --color-red-500: …; --spacing: …; }` blocks from CSS into a
2417
- // Theme. This is the CSS-first way to define tokens; the registry is then
2418
- // built from the resulting theme.
2419
- function loadTheme(css) {
2420
- var theme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Theme();
2421
- var sheet = parseCss(css);
2422
- var _iterator = _createForOfIteratorHelper(sheet.children),
2423
- _step;
2424
- try {
2425
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2426
- var node = _step.value;
2427
- if (node.type === 'atrule' && node.name === 'theme' && node.block) {
2428
- collect(node, theme);
2429
- }
1739
+ // Parses one raw utility (e.g. `md:hover:-bg-red-500/50!` or `[&_p]:text-[13px]`)
1740
+ // into a structured Atom in a single pass. Splitting is bracket/paren aware,
1741
+ // so `:` `/` `-` inside arbitrary values are left alone — no regex, no
1742
+ // backtracking. Which part is the root and which is the value can't be known from
1743
+ // the string alone (`text-red-500` vs `grid-cols-3`), so that split is resolved
1744
+ // against the registry through AtomContext.
1745
+
1746
+ // Split on `sep` at depth 0 only; `[...]` and `(...)` are opaque, and `\` escapes
1747
+ // the next character.
1748
+ function splitAtTopLevel(input, sep) {
1749
+ var out = [];
1750
+ var depthBracket = 0;
1751
+ var depthParen = 0;
1752
+ var start = 0;
1753
+ for (var i = 0; i < input.length; i++) {
1754
+ var c = input[i];
1755
+ if (c === '\\') {
1756
+ i++; // skip the escaped char
1757
+ continue;
2430
1758
  }
2431
- } catch (err) {
2432
- _iterator.e(err);
2433
- } finally {
2434
- _iterator.f();
2435
- }
2436
- return theme;
2437
- }
2438
- function collect(atRule, theme) {
2439
- var _iterator2 = _createForOfIteratorHelper(atRule.block.children),
2440
- _step2;
2441
- try {
2442
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2443
- var child = _step2.value;
2444
- if (child.type === 'declaration' && isCustomProperty(child)) {
2445
- var _child$rawValue;
2446
- theme.add(child.property, ((_child$rawValue = child.rawValue) !== null && _child$rawValue !== void 0 ? _child$rawValue : '').trim());
2447
- }
1759
+ if (c === '[') depthBracket++;else if (c === ']') depthBracket = Math.max(0, depthBracket - 1);else if (c === '(') depthParen++;else if (c === ')') depthParen = Math.max(0, depthParen - 1);else if (c === sep && depthBracket === 0 && depthParen === 0) {
1760
+ out.push(input.slice(start, i));
1761
+ start = i + 1;
2448
1762
  }
2449
- } catch (err) {
2450
- _iterator2.e(err);
2451
- } finally {
2452
- _iterator2.f();
2453
1763
  }
2454
- }
2455
- function isCustomProperty(d) {
2456
- return d.customProperty === true || d.property.startsWith('--');
1764
+ out.push(input.slice(start));
1765
+ return out;
2457
1766
  }
2458
1767
 
2459
- // Emit the theme as `:root { --token: value; … }` so the tokens ship as live
2460
- // custom properties. Pass `used` to emit only the tokens actually referenced
2461
- // (plus any they transitively reference) — see {@link collectVarRefs}.
2462
- function emitTheme(theme) {
2463
- var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':root';
2464
- var used = arguments.length > 2 ? arguments[2] : undefined;
2465
- var entries = used ? usedEntries(theme, used) : theme.entries();
2466
- return rule(selector, entries.map(function (_ref) {
2467
- var _ref2 = _slicedToArray(_ref, 2),
2468
- name = _ref2[0],
2469
- value = _ref2[1];
2470
- return decl(name, value);
2471
- }));
1768
+ // Content of a `[...]` or `(...)` wrapper, or null when `s` isn't wrapped.
1769
+ function unwrap(s, open) {
1770
+ var close = open === '[' ? ']' : ')';
1771
+ return s.length >= 2 && s[0] === open && s[s.length - 1] === close ? s.slice(1, -1) : null;
1772
+ }
1773
+ function parseModifier(raw) {
1774
+ if (!raw) return null;
1775
+ var arb = unwrap(raw, '[');
1776
+ if (arb !== null) return {
1777
+ kind: 'arbitrary',
1778
+ value: arb
1779
+ };
1780
+ // `(--name)` is shorthand for the custom property it references.
1781
+ var paren = unwrap(raw, '(');
1782
+ if (paren !== null) return {
1783
+ kind: 'arbitrary',
1784
+ value: "var(".concat(paren, ")")
1785
+ };
1786
+ return {
1787
+ kind: 'named',
1788
+ value: raw
1789
+ };
1790
+ }
1791
+ function splitModifier(base) {
1792
+ var parts = splitAtTopLevel(base, '/');
1793
+ if (parts.length === 1) return {
1794
+ base: base,
1795
+ modifier: null
1796
+ };
1797
+ var modifier = parseModifier(parts.slice(1).join('/'));
1798
+ return {
1799
+ base: parts[0],
1800
+ modifier: modifier
1801
+ };
2472
1802
  }
2473
- var VAR_REF = /var\(\s*(--[\w-]+)/g;
2474
1803
 
2475
- // Every `--token` referenced through `var(--token)` across a compiled tree.
2476
- function collectVarRefs(nodes) {
2477
- var into = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();
2478
- var _iterator3 = _createForOfIteratorHelper(nodes),
2479
- _step3;
2480
- try {
2481
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2482
- var node = _step3.value;
2483
- if (node.kind === 'declaration') {
2484
- var _iterator4 = _createForOfIteratorHelper(node.value.matchAll(VAR_REF)),
2485
- _step4;
2486
- try {
2487
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2488
- var m = _step4.value;
2489
- into.add(m[1]);
2490
- }
2491
- } catch (err) {
2492
- _iterator4.e(err);
2493
- } finally {
2494
- _iterator4.f();
2495
- }
2496
- } else if (node.kind === 'raw') {
2497
- var _iterator5 = _createForOfIteratorHelper(node.text.matchAll(VAR_REF)),
2498
- _step5;
2499
- try {
2500
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2501
- var _m = _step5.value;
2502
- into.add(_m[1]);
2503
- }
2504
- } catch (err) {
2505
- _iterator5.e(err);
2506
- } finally {
2507
- _iterator5.f();
2508
- }
2509
- } else {
2510
- collectVarRefs(node.nodes, into);
2511
- }
2512
- }
2513
- } catch (err) {
2514
- _iterator3.e(err);
2515
- } finally {
2516
- _iterator3.f();
2517
- }
2518
- return into;
1804
+ // In arbitrary values `_` stands in for a space; `\_` is a literal underscore.
1805
+ function decodeUnderscores(value) {
1806
+ // `_` → space, `\_` → literal `_`. But a URL may legitimately contain underscores,
1807
+ // so leave the inside of `url(...)` verbatim (the split keeps url() at odd indices).
1808
+ return value.split(/(url\([^)]*\))/g).map(function (part, i) {
1809
+ return i % 2 === 1 ? part : part.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
1810
+ }).join('');
2519
1811
  }
2520
1812
 
2521
- // The theme entries to keep for `used`: the referenced tokens plus the transitive
2522
- // closure of any tokens their own values reference (e.g. `--color-primary:
2523
- // var(--color-blue-500)`). Insertion order is preserved.
2524
- function usedEntries(theme, used) {
2525
- var keep = new Set();
2526
- var stack = _toConsumableArray(used);
2527
- while (stack.length) {
2528
- var name = stack.pop();
2529
- if (keep.has(name)) continue;
2530
- var value = theme.get(name);
2531
- if (value === undefined) continue; // referenced but not a theme token
2532
- keep.add(name);
2533
- var _iterator6 = _createForOfIteratorHelper(value.matchAll(VAR_REF)),
2534
- _step6;
2535
- try {
2536
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
2537
- var m = _step6.value;
2538
- stack.push(m[1]);
2539
- }
2540
- } catch (err) {
2541
- _iterator6.e(err);
2542
- } finally {
2543
- _iterator6.f();
1813
+ // An arbitrary value may lead with a `type:` hint, e.g. `[length:12px]`.
1814
+ function parseArbitraryValue(body) {
1815
+ var colon = body.indexOf(':');
1816
+ if (colon > 0) {
1817
+ var maybeType = body.slice(0, colon);
1818
+ if (/^[a-z-]+$/.test(maybeType)) {
1819
+ return {
1820
+ dataType: maybeType,
1821
+ value: decodeUnderscores(body.slice(colon + 1))
1822
+ };
2544
1823
  }
2545
1824
  }
2546
- return theme.entries().filter(function (_ref3) {
2547
- var _ref4 = _slicedToArray(_ref3, 1),
2548
- name = _ref4[0];
2549
- return keep.has(name);
2550
- });
1825
+ return {
1826
+ dataType: null,
1827
+ value: decodeUnderscores(body)
1828
+ };
2551
1829
  }
2552
1830
 
2553
- // Reads `@utility` and `@custom-variant` blocks from CSS and registers them into
2554
- // the registry — the CSS-first way to add utilities and variants, alongside
2555
- // `@theme` for tokens. Call after loadTheme so functional utilities can resolve
2556
- // against the theme.
2557
- function loadDirectives(css, reg) {
2558
- var sheet = parseCss(css);
2559
- var _iterator = _createForOfIteratorHelper(sheet.children),
2560
- _step;
2561
- try {
2562
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2563
- var node = _step.value;
2564
- if (node.type !== 'atrule') continue;
2565
- if (node.name === 'utility') registerUtility(node, reg);else if (node.name === 'custom-variant') registerVariant(node, reg);
2566
- }
2567
- } catch (err) {
2568
- _iterator.e(err);
2569
- } finally {
2570
- _iterator.f();
1831
+ // The `(--name)` shorthand, optionally typed: `(length:--size)`. The custom
1832
+ // property name keeps its underscores.
1833
+ function parseParenValue(paren) {
1834
+ var colon = paren.indexOf(':');
1835
+ if (colon > 0 && /^[a-z-]+$/.test(paren.slice(0, colon))) {
1836
+ return {
1837
+ dataType: paren.slice(0, colon),
1838
+ value: "var(".concat(paren.slice(colon + 1), ")")
1839
+ };
2571
1840
  }
2572
- return reg;
1841
+ return {
1842
+ dataType: null,
1843
+ value: "var(".concat(paren, ")")
1844
+ };
2573
1845
  }
2574
- function registerUtility(atRule, reg) {
2575
- var _atRule$preludeText;
2576
- var name = ((_atRule$preludeText = atRule.preludeText) !== null && _atRule$preludeText !== void 0 ? _atRule$preludeText : '').trim();
2577
- if (!name || !atRule.block) return;
1846
+ function parseVariant(raw) {
1847
+ var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1848
+ if (!raw) return null;
2578
1849
 
2579
- // Flat declarations plus any nested rules (`&:hover`, `&::-webkit-scrollbar`);
2580
- // the nested `&` is later woven with the utility's own selector by the compiler.
2581
- var products = toProducts(atRule.block.children);
2582
- if (products.length === 0) return;
1850
+ // `[&:hover]`, `[@media(...)]` — the selector is written out; a `&` means it's
1851
+ // relative to the element.
1852
+ var arb = unwrap(raw, '[');
1853
+ if (arb !== null) {
1854
+ return {
1855
+ kind: 'arbitrary',
1856
+ selector: arb,
1857
+ relative: arb.includes('&')
1858
+ };
1859
+ }
1860
+ var _splitModifier = splitModifier(raw),
1861
+ base = _splitModifier.base,
1862
+ modifier = _splitModifier.modifier;
2583
1863
 
2584
- // A trailing `-*` marks a functional utility: `tab-*` handles `tab-2`, `tab-[3]`.
2585
- if (name.endsWith('-*')) {
2586
- var root = name.slice(0, -2);
2587
- if (root) reg.dynamicRule(root, function (ctx) {
2588
- return resolveProducts(products, ctx);
2589
- });
2590
- return;
2591
- }
2592
- reg.rule(name, products);
2593
- }
2594
- function toProducts(children) {
2595
- var out = [];
2596
- var _iterator2 = _createForOfIteratorHelper(children),
2597
- _step2;
2598
- try {
2599
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2600
- var c = _step2.value;
2601
- if (c.type === 'declaration') {
2602
- var _d$rawValue;
2603
- var d = c;
2604
- out.push(decl(d.property, ((_d$rawValue = d.rawValue) !== null && _d$rawValue !== void 0 ? _d$rawValue : '').trim(), d.important === true));
2605
- } else if (c.type === 'rule') {
2606
- var _r$declarations, _r$children, _r$rawSelector;
2607
- var r = c;
2608
- // The parser splits a rule's own declarations from its nested rules; a
2609
- // utility body wants both, declarations first.
2610
- var kids = [].concat(_toConsumableArray((_r$declarations = r.declarations) !== null && _r$declarations !== void 0 ? _r$declarations : []), _toConsumableArray((_r$children = r.children) !== null && _r$children !== void 0 ? _r$children : []));
2611
- out.push(rule(((_r$rawSelector = r.rawSelector) !== null && _r$rawSelector !== void 0 ? _r$rawSelector : '').trim(), toProducts(kids)));
2612
- }
1864
+ // A variant carrying a value: `group-hover`, `data-[open]`, `supports-[display:grid]`.
1865
+ var dash = base.indexOf('-');
1866
+ if (dash > 0) {
1867
+ var _ctx$isDynamicVariant, _ctx$isDynamicVariant2;
1868
+ var _root = base.slice(0, dash);
1869
+ var rest = base.slice(dash + 1);
1870
+ if ((_ctx$isDynamicVariant = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant !== void 0 && _ctx$isDynamicVariant.call(ctx, _root) || (_ctx$isDynamicVariant2 = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant2 !== void 0 && _ctx$isDynamicVariant2.call(ctx, _root + '-')) {
1871
+ // A variant's `[...]` is a raw condition/attribute, not a typed value.
1872
+ var arbVal = unwrap(rest, '[');
1873
+ var value = arbVal !== null ? {
1874
+ kind: 'arbitrary',
1875
+ value: arbVal,
1876
+ dataType: null
1877
+ } : {
1878
+ kind: 'named',
1879
+ value: rest
1880
+ };
1881
+ return {
1882
+ kind: 'functional',
1883
+ root: _root,
1884
+ value: value,
1885
+ modifier: modifier
1886
+ };
2613
1887
  }
2614
- } catch (err) {
2615
- _iterator2.e(err);
2616
- } finally {
2617
- _iterator2.f();
2618
1888
  }
2619
- return out;
1889
+ return {
1890
+ kind: 'functional',
1891
+ root: base,
1892
+ value: null,
1893
+ modifier: modifier
1894
+ };
2620
1895
  }
2621
1896
 
2622
- // Applies a functional utility's templates to one atom, walking nested rules too.
2623
- // `--value()` is required — if it can't resolve, the whole utility is dropped
2624
- // (returns null). `--modifier()` is optional — a declaration using it is skipped
2625
- // when there's no matching modifier, so `text-lg` and `text-lg/7` share one def.
2626
- function resolveProducts(templates, ctx) {
2627
- var out = [];
2628
- var _iterator3 = _createForOfIteratorHelper(templates),
2629
- _step3;
1897
+ // Returns null for structurally invalid input (empty or dangling segments).
1898
+ // Without a context the root/value split falls back to the first dash, which is
1899
+ // enough to test the scanner on its own.
1900
+ function parseAtom(raw) {
1901
+ var _ctx$isRule, _ctx$isRule2;
1902
+ var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1903
+ if (!raw) return null;
1904
+ var segments = splitAtTopLevel(raw, ':');
1905
+ var utility = segments.pop();
1906
+ if (utility === undefined || utility === '') return null;
1907
+ var variants = [];
1908
+ var _iterator = _createForOfIteratorHelper(segments),
1909
+ _step;
2630
1910
  try {
2631
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2632
- var t = _step3.value;
2633
- if (t.kind === 'declaration') {
2634
- var withValue = replaceFn(t.value, '--value', function (args) {
2635
- return resolveValue(args, ctx);
2636
- });
2637
- if (withValue === null) return null;
2638
- var withModifier = replaceFn(withValue, '--modifier', function (args) {
2639
- return resolveModifier(args, ctx);
2640
- });
2641
- if (withModifier === null) continue;
2642
- out.push(_objectSpread2(_objectSpread2({}, t), {}, {
2643
- value: withModifier
2644
- }));
2645
- } else {
2646
- var inner = resolveProducts(t.nodes, ctx);
2647
- if (inner === null) return null;
2648
- out.push(rule(t.selector, inner));
2649
- }
1911
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1912
+ var seg = _step.value;
1913
+ if (seg === '') return null; // dangling `::`
1914
+ var v = parseVariant(seg, ctx);
1915
+ if (!v) return null;
1916
+ variants.push(v);
2650
1917
  }
1918
+ // Written left-to-right (outermost first), stored innermost-first so consumers
1919
+ // can wrap the declaration outward.
2651
1920
  } catch (err) {
2652
- _iterator3.e(err);
1921
+ _iterator.e(err);
2653
1922
  } finally {
2654
- _iterator3.f();
1923
+ _iterator.f();
2655
1924
  }
2656
- return out.length ? out : null;
2657
- }
2658
- function resolveValue(args, ctx) {
2659
- var value = ctx.value;
2660
- if (!value) return null;
2661
- for (var _i = 0, _splitArgs = splitArgs(args); _i < _splitArgs.length; _i++) {
2662
- var arg = _splitArgs[_i];
2663
- var themed = fromTheme(arg, value.kind === 'named' ? value.value : null, ctx);
2664
- if (themed !== null) return themed;
2665
- if (value.kind === 'named') {
2666
- var lit = fromNamed(arg, value.value);
2667
- if (lit !== null) return lit;
2668
- } else {
2669
- var arb = fromArbitrary(arg, value.value, value.dataType);
2670
- if (arb !== null) return arb;
2671
- }
1925
+ variants.reverse();
1926
+
1927
+ // `!` marks important, accepted on either end.
1928
+ var body = utility;
1929
+ var important = false;
1930
+ if (body.endsWith('!')) {
1931
+ important = true;
1932
+ body = body.slice(0, -1);
1933
+ } else if (body.startsWith('!')) {
1934
+ important = true;
1935
+ body = body.slice(1);
2672
1936
  }
2673
- return null;
2674
- }
2675
- function resolveModifier(args, ctx) {
2676
- var modifier = ctx.modifier;
2677
- if (!modifier) return null;
2678
- for (var _i2 = 0, _splitArgs2 = splitArgs(args); _i2 < _splitArgs2.length; _i2++) {
2679
- var arg = _splitArgs2[_i2];
2680
- var themed = fromTheme(arg, modifier.kind === 'named' ? modifier.value : null, ctx);
2681
- if (themed !== null) return themed;
2682
- if (modifier.kind === 'named') {
2683
- var lit = fromNamed(arg, modifier.value);
2684
- if (lit !== null) return lit;
1937
+ if (body === '') return null;
1938
+
1939
+ // Split off a trailing `/modifier` once, up front — it applies uniformly to
1940
+ // arbitrary-property, static, and functional atoms.
1941
+ var _splitModifier2 = splitModifier(body),
1942
+ core0 = _splitModifier2.base,
1943
+ modifier = _splitModifier2.modifier;
1944
+
1945
+ // Arbitrary property: `[color:red]`, `[--my-var:0]` (optionally with modifier).
1946
+ var arbProp = unwrap(core0, '[');
1947
+ if (arbProp !== null && arbProp.includes(':')) {
1948
+ var colon = arbProp.indexOf(':');
1949
+ if (colon <= 0) return null;
1950
+ // The head must be a real CSS property or custom property. Scanners pull
1951
+ // `[...]` runs out of JS/TS too (array/object literals like
1952
+ // `[...prev, { value } as T]`); rejecting a non-property head keeps those
1953
+ // from emitting broken rules that later crash the CSS parser.
1954
+ var property = arbProp.slice(0, colon);
1955
+ if (!/^-{0,2}[a-zA-Z][a-zA-Z0-9-]*$/.test(property)) return null;
1956
+ return {
1957
+ kind: 'arbitrary-property',
1958
+ property: property,
1959
+ value: decodeUnderscores(arbProp.slice(colon + 1)),
1960
+ modifier: modifier,
1961
+ important: important,
1962
+ variants: variants,
1963
+ raw: raw
1964
+ };
1965
+ }
1966
+
1967
+ // Negative.
1968
+ var negative = false;
1969
+ var base = core0;
1970
+ if (base[0] === '-') {
1971
+ negative = true;
1972
+ base = base.slice(1);
1973
+ if (base === '') return null;
1974
+ }
1975
+
1976
+ // Static utility (only when unambiguous: no negative/modifier).
1977
+ if (!negative && modifier === null && (_ctx$isRule = ctx.isRule) !== null && _ctx$isRule !== void 0 && _ctx$isRule.call(ctx, base)) {
1978
+ return {
1979
+ kind: 'static',
1980
+ root: base,
1981
+ important: important,
1982
+ variants: variants,
1983
+ raw: raw
1984
+ };
1985
+ }
1986
+
1987
+ // Functional: split root ↔ value. Prefer the longest known functional root;
1988
+ // fall back to the first-dash split when no context is supplied.
1989
+ var _splitRootValue = splitRootValue(base, ctx),
1990
+ root = _splitRootValue.root,
1991
+ valueStr = _splitRootValue.valueStr;
1992
+ if (root === '') return null;
1993
+ var value = null;
1994
+ if (valueStr !== null && valueStr !== '') {
1995
+ var arbVal = unwrap(valueStr, '[');
1996
+ if (arbVal !== null) {
1997
+ value = _objectSpread2({
1998
+ kind: 'arbitrary'
1999
+ }, parseArbitraryValue(arbVal));
2685
2000
  } else {
2686
- var arb = fromArbitrary(arg, modifier.value, null);
2687
- if (arb !== null) return arb;
2001
+ var paren = unwrap(valueStr, '(');
2002
+ value = paren !== null ? _objectSpread2({
2003
+ kind: 'arbitrary'
2004
+ }, parseParenValue(paren)) : {
2005
+ kind: 'named',
2006
+ value: valueStr,
2007
+ fraction: null
2008
+ };
2688
2009
  }
2010
+ } else if ((_ctx$isRule2 = ctx.isRule) !== null && _ctx$isRule2 !== void 0 && _ctx$isRule2.call(ctx, base)) {
2011
+ // A bare root that is registered static (reached here due to a modifier).
2012
+ return {
2013
+ kind: 'static',
2014
+ root: base,
2015
+ important: important,
2016
+ variants: variants,
2017
+ raw: raw
2018
+ };
2689
2019
  }
2690
- return null;
2691
- }
2692
-
2693
- // `--foo` / `--foo-*` names a theme namespace; the atom's named value keys into
2694
- // it (`--value(--tab-size)` + `tab-2` → `var(--tab-size-2)`).
2695
- function fromTheme(arg, key, ctx) {
2696
- if (key === null || !arg.startsWith('--')) return null;
2697
- var ns = arg.replace(/-?\*$/, '').slice(2);
2698
- return ns ? ctx.theme.resolve(ns, key) : null;
2020
+ return {
2021
+ kind: 'functional',
2022
+ root: root,
2023
+ value: value,
2024
+ modifier: modifier,
2025
+ important: important,
2026
+ negative: negative,
2027
+ variants: variants,
2028
+ raw: raw
2029
+ };
2699
2030
  }
2700
2031
 
2701
- // A bare value against a data-type keyword (`integer`, `number`, `percentage`) or a
2702
- // quoted literal (`'inline'`).
2703
- function fromNamed(arg, value) {
2704
- if (isQuoted(arg)) return arg.slice(1, -1) === value ? value : null;
2705
- var rx = NUMERIC[arg];
2706
- return rx ? rx.test(value) ? value : null : null;
2707
- }
2708
-
2709
- // An arbitrary value against `[*]` (anything) or a typed bracket (`[integer]`,
2710
- // `[length]`), gated on the value's own `type:` hint when it carries one.
2711
- function fromArbitrary(arg, value, dataType) {
2712
- if (arg[0] !== '[' || arg[arg.length - 1] !== ']') return null;
2713
- var want = arg.slice(1, -1);
2714
- if (want === '*') return value;
2715
- if (dataType !== null) return dataType === want ? value : null;
2716
- // Untyped arbitrary: validate against the simple numeric types we can check.
2717
- var rx = NUMERIC[want];
2718
- return rx ? rx.test(value) ? value : null : value;
2719
- }
2720
- var NUMERIC = {
2721
- integer: /^-?\d+$/,
2722
- number: /^-?\d*\.?\d+$/,
2723
- percentage: /^-?\d*\.?\d+%$/
2724
- };
2725
- function isQuoted(s) {
2726
- return s.length >= 2 && (s[0] === '"' || s[0] === "'") && s[s.length - 1] === s[0];
2727
- }
2728
- function splitArgs(args) {
2729
- return splitAtTopLevel(args, ',').map(function (a) {
2730
- return a.trim();
2731
- }).filter(function (a) {
2732
- return a !== '';
2733
- });
2734
- }
2735
-
2736
- // Replaces every `name(...)` call in `input` (parens balanced, even when nested in
2737
- // `calc(...)`) with `resolve`'s result. Returns null if any call fails to resolve.
2738
- function replaceFn(input, name, resolve) {
2739
- var token = name + '(';
2740
- var out = '';
2741
- var i = 0;
2742
- for (;;) {
2743
- var start = input.indexOf(token, i);
2744
- if (start === -1) return out + input.slice(i);
2745
- out += input.slice(i, start);
2746
- var depth = 0;
2747
- var j = start + token.length - 1;
2748
- for (; j < input.length; j++) {
2749
- if (input[j] === '(') depth++;else if (input[j] === ')' && --depth === 0) break;
2032
+ // Splits `bg-red-500` into a root and value. The longest registered root wins
2033
+ // (`grid-cols-3` → `grid-cols` + `3`); with no context, split at the first dash.
2034
+ function splitRootValue(base, ctx) {
2035
+ if (ctx.isDynamicRule) {
2036
+ // The whole class is itself the longest possible root (`rounded-t`, `border-x`);
2037
+ // prefer it before splitting off a shorter registered prefix (`rounded` + `t`).
2038
+ if (ctx.isDynamicRule(base)) return {
2039
+ root: base,
2040
+ valueStr: null
2041
+ };
2042
+ var dashes = [];
2043
+ for (var i = 0; i < base.length; i++) if (base[i] === '-') dashes.push(i);
2044
+ for (var d = dashes.length - 1; d >= 0; d--) {
2045
+ var idx = dashes[d];
2046
+ var _root2 = base.slice(0, idx);
2047
+ if (ctx.isDynamicRule(_root2)) return {
2048
+ root: _root2,
2049
+ valueStr: base.slice(idx + 1)
2050
+ };
2750
2051
  }
2751
- if (j >= input.length) return null; // unbalanced
2752
- var resolved = resolve(input.slice(start + token.length, j));
2753
- if (resolved === null) return null;
2754
- out += resolved;
2755
- i = j + 1;
2756
2052
  }
2053
+ var first = base.indexOf('-');
2054
+ if (first <= 0) return {
2055
+ root: base,
2056
+ valueStr: null
2057
+ };
2058
+ return {
2059
+ root: base.slice(0, first),
2060
+ valueStr: base.slice(first + 1)
2061
+ };
2757
2062
  }
2758
- function registerVariant(atRule, reg) {
2759
- var _atRule$preludeText2;
2760
- var prelude = ((_atRule$preludeText2 = atRule.preludeText) !== null && _atRule$preludeText2 !== void 0 ? _atRule$preludeText2 : '').trim();
2761
- if (!prelude) return;
2762
2063
 
2763
- // Block form: `@custom-variant name { &:hover { @slot } }` — the prelude is just
2764
- // the name and the block describes the wrapping, marked by `@slot`.
2765
- if (atRule.block) {
2766
- var wrap = blockToWrap(atRule.block.children);
2767
- if (prelude && wrap) reg.variant(prelude, wrap);
2768
- return;
2064
+ // Turns a parsed atom into CSS. Returns null when the utility or any of its
2065
+ // variants aren't registered, so an unknown class simply produces nothing.
2066
+ function compileAtom(atom, reg) {
2067
+ var produced = producedFor(atom, reg);
2068
+ if (!produced || produced.length === 0) return null;
2069
+ var flat = [];
2070
+ var nested = [];
2071
+ var _iterator = _createForOfIteratorHelper(produced),
2072
+ _step;
2073
+ try {
2074
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2075
+ var node = _step.value;
2076
+ if (node.kind === 'declaration') flat.push(node);else nested.push(node);
2077
+ }
2078
+ } catch (err) {
2079
+ _iterator.e(err);
2080
+ } finally {
2081
+ _iterator.f();
2082
+ }
2083
+ if (atom.important) {
2084
+ var _iterator2 = _createForOfIteratorHelper(flat),
2085
+ _step2;
2086
+ try {
2087
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2088
+ var d = _step2.value;
2089
+ d.important = true;
2090
+ }
2091
+ } catch (err) {
2092
+ _iterator2.e(err);
2093
+ } finally {
2094
+ _iterator2.f();
2095
+ }
2096
+ var _iterator3 = _createForOfIteratorHelper(nested),
2097
+ _step3;
2098
+ try {
2099
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2100
+ var n = _step3.value;
2101
+ markImportant$1(n.nodes);
2102
+ }
2103
+ } catch (err) {
2104
+ _iterator3.e(err);
2105
+ } finally {
2106
+ _iterator3.f();
2107
+ }
2769
2108
  }
2109
+ var selector = '.' + escapeClass(atom.raw);
2110
+ var atRules = [];
2111
+ var _iterator4 = _createForOfIteratorHelper(atom.variants),
2112
+ _step4;
2113
+ try {
2114
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2115
+ var variant = _step4.value;
2116
+ var wrap = resolveVariant(variant, reg);
2117
+ if (!wrap) return null;
2118
+ if (wrap.selector) selector = substitute(wrap.selector, selector);
2119
+ if (wrap.atRule) atRules.push(wrap.atRule);
2120
+ }
2770
2121
 
2771
- // Shorthand: `@custom-variant name (condition)`.
2772
- var paren = prelude.indexOf('(');
2773
- if (paren === -1 || !prelude.endsWith(')')) return;
2774
- var name = prelude.slice(0, paren).trim();
2775
- var condition = prelude.slice(paren + 1, -1).trim();
2776
- if (!name || !condition) return;
2777
- reg.variant(name, wrapFor(condition));
2122
+ // Flat declarations sit on the utility's own selector; nested rules weave that
2123
+ // selector into their `&` (`space-x-4` → `.space-x-4 > :not([hidden]) ~ …`).
2124
+ } catch (err) {
2125
+ _iterator4.e(err);
2126
+ } finally {
2127
+ _iterator4.f();
2128
+ }
2129
+ var nodes = [];
2130
+ if (flat.length) nodes.push(rule(selector, flat));
2131
+ for (var _i = 0, _nested = nested; _i < _nested.length; _i++) {
2132
+ var _n = _nested[_i];
2133
+ nodes.push(rule(substitute(_n.selector, selector), _n.nodes));
2134
+ }
2135
+ for (var _i2 = 0, _atRules = atRules; _i2 < _atRules.length; _i2++) {
2136
+ var ar = _atRules[_i2];
2137
+ nodes = [atRule(ar.name, ar.params, nodes)];
2138
+ }
2139
+ return nodes;
2778
2140
  }
2779
-
2780
- // Walk the single path down to `@slot`, collecting the selector (nested rules,
2781
- // combined by `&` substitution) and/or the wrapping at-rule (`@media`, `@supports`).
2782
- // Supports one selector level, one at-rule level, or both nested.
2783
- function blockToWrap(children) {
2784
- var selector;
2785
- var at;
2786
- var node = firstBlockChild(children);
2787
- while (node) {
2788
- if (node.type === 'rule') {
2789
- var _rawSelector, _children;
2790
- var sel = ((_rawSelector = node.rawSelector) !== null && _rawSelector !== void 0 ? _rawSelector : '').trim();
2791
- selector = selector ? sel.replace(/&/g, selector) : sel;
2792
- node = firstBlockChild((_children = node.children) !== null && _children !== void 0 ? _children : []);
2793
- } else if (node.type === 'atrule') {
2794
- var _ar$preludeText;
2795
- var ar = node;
2796
- if (ar.name === 'slot') break;
2797
- at = {
2798
- name: ar.name,
2799
- params: ((_ar$preludeText = ar.preludeText) !== null && _ar$preludeText !== void 0 ? _ar$preludeText : '').trim()
2800
- };
2801
- node = ar.block ? firstBlockChild(ar.block.children) : undefined;
2802
- } else {
2803
- node = undefined;
2141
+ function markImportant$1(nodes) {
2142
+ var _iterator5 = _createForOfIteratorHelper(nodes),
2143
+ _step5;
2144
+ try {
2145
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2146
+ var n = _step5.value;
2147
+ if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant$1(n.nodes);
2804
2148
  }
2149
+ } catch (err) {
2150
+ _iterator5.e(err);
2151
+ } finally {
2152
+ _iterator5.f();
2805
2153
  }
2806
- var wrap = {};
2807
- if (selector) wrap.selector = selector.includes('&') ? selector : "&".concat(selector);
2808
- if (at) wrap.atRule = at;
2809
- return wrap.selector || wrap.atRule ? wrap : null;
2810
2154
  }
2811
- function firstBlockChild(children) {
2812
- return children.find(function (c) {
2813
- return c.type === 'rule' || c.type === 'atrule';
2155
+ function producedFor(atom, reg) {
2156
+ if (atom.kind === 'arbitrary-property') {
2157
+ return [decl(atom.property, atom.value)];
2158
+ }
2159
+ if (atom.kind === 'static') {
2160
+ // Clone: static templates are shared, and `!important` / `&`-weaving mutate.
2161
+ var products = reg.getRule(atom.root);
2162
+ return products ? products.map(cloneProduct) : null;
2163
+ }
2164
+ var handler = reg.getDynamicRule(atom.root);
2165
+ if (!handler) return null;
2166
+ return handler({
2167
+ value: atom.value,
2168
+ modifier: atom.modifier,
2169
+ negative: atom.negative,
2170
+ theme: reg.theme
2814
2171
  });
2815
2172
  }
2816
- function wrapFor(condition) {
2817
- if (condition[0] === '@') {
2818
- var cut = condition.search(/[\s(]/);
2819
- var at = cut === -1 ? condition.slice(1) : condition.slice(1, cut);
2820
- var params = cut === -1 ? '' : condition.slice(cut).trim();
2821
- return {
2822
- atRule: {
2823
- name: at,
2824
- params: params
2825
- }
2826
- };
2827
- }
2828
- return {
2829
- selector: condition.includes('&') ? condition : "&".concat(condition)
2830
- };
2173
+ function cloneProduct(n) {
2174
+ return n.kind === 'declaration' ? _objectSpread2({}, n) : cloneNode(n);
2831
2175
  }
2832
-
2833
- // A utility produces declarations on its own selector, and/or nested rules whose
2834
- // `&` is woven with that selector — the latter is how child-combinator utilities
2835
- // like `space-x`/`divide-y` reach `& > * + *`.
2836
-
2837
- // A variant either narrows the selector (`&:hover`, `.group:hover &`) or wraps
2838
- // the rule in an at-rule (`@media`, `@supports`). It may do both.
2839
-
2176
+ function cloneNode(n) {
2177
+ if (n.kind === 'declaration') return _objectSpread2({}, n);
2178
+ if (n.kind === 'rule') return rule(n.selector, n.nodes.map(cloneNode));
2179
+ if (n.kind === 'at-rule') return atRule(n.name, n.params, n.nodes.map(cloneNode));
2180
+ return _objectSpread2({}, n);
2181
+ }
2182
+ function resolveVariant(variant, reg) {
2183
+ if (variant.kind === 'arbitrary') return arbitraryVariant(variant.selector);
2184
+ if (variant.kind === 'static') return reg.getVariant(variant.root);
2185
+ // functional: a null value means it's really a static variant (hover, md, …).
2186
+ if (variant.value === null) return reg.getVariant(variant.root);
2187
+ var handler = reg.getDynamicVariant(variant.root);
2188
+ return handler ? handler(variant.value, variant.modifier) : null;
2189
+ }
2190
+
2191
+ // `[&_p]` → `& p`, `[.parent_&]` → `.parent &`, `[@media(...)]` → an at-rule.
2192
+ // A bare selector with no `&` is attached to the element.
2193
+ function arbitraryVariant(source) {
2194
+ if (source[0] === '@') {
2195
+ var cut = source.search(/[\s(]/);
2196
+ var name = cut === -1 ? source.slice(1) : source.slice(1, cut);
2197
+ var params = cut === -1 ? '' : source.slice(cut).trim();
2198
+ return {
2199
+ atRule: {
2200
+ name: name,
2201
+ params: params
2202
+ }
2203
+ };
2204
+ }
2205
+ var sel = spacesFromUnderscores(source);
2206
+ return {
2207
+ selector: sel.includes('&') ? sel : "&".concat(sel)
2208
+ };
2209
+ }
2210
+ function spacesFromUnderscores(s) {
2211
+ return s.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
2212
+ }
2213
+ function substitute(template, current) {
2214
+ return template.replace(/&/g, current);
2215
+ }
2216
+
2217
+ // Backslash-escape everything outside [A-Za-z0-9_-] so a utility name is a valid
2218
+ // class selector (`hover:bg-red-500/50` → `hover\:bg-red-500\/50`).
2219
+ function escapeClass(name) {
2220
+ return name.replace(/[^a-zA-Z0-9_-]/g, function (c) {
2221
+ return '\\' + c;
2222
+ });
2223
+ }
2224
+
2225
+ // The resolved token table. Every entry is a CSS custom property (`--color-red-500`,
2226
+ // `--spacing`, `--breakpoint-md`, …); utilities read them by namespace and emit
2227
+ // `var()` references, so the tokens stay live and themeable at runtime.
2228
+
2229
+ var Theme = /*#__PURE__*/function () {
2230
+ function Theme() {
2231
+ _classCallCheck(this, Theme);
2232
+ _defineProperty(this, "values", new Map());
2233
+ }
2234
+ return _createClass(Theme, [{
2235
+ key: "add",
2236
+ value: function add(name, value) {
2237
+ this.values.set(name, value);
2238
+ return this;
2239
+ }
2240
+ }, {
2241
+ key: "addAll",
2242
+ value: function addAll(entries) {
2243
+ for (var name in entries) this.add(name, entries[name]);
2244
+ return this;
2245
+ }
2246
+ }, {
2247
+ key: "get",
2248
+ value: function get(name) {
2249
+ return this.values.get(name);
2250
+ }
2251
+ }, {
2252
+ key: "has",
2253
+ value: function has(name) {
2254
+ return this.values.has(name);
2255
+ }
2256
+
2257
+ // A `var()` reference to `--<namespace>-<key>` when that token exists.
2258
+ }, {
2259
+ key: "resolve",
2260
+ value: function resolve(namespace, key) {
2261
+ var name = "--".concat(namespace, "-").concat(key);
2262
+ return this.values.has(name) ? "var(".concat(name, ")") : null;
2263
+ }
2264
+
2265
+ // Bare keys registered under a namespace, e.g. every color name.
2266
+ }, {
2267
+ key: "keysIn",
2268
+ value: function keysIn(namespace) {
2269
+ var prefix = "--".concat(namespace, "-");
2270
+ var out = [];
2271
+ var _iterator = _createForOfIteratorHelper(this.values.keys()),
2272
+ _step;
2273
+ try {
2274
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2275
+ var name = _step.value;
2276
+ if (name.startsWith(prefix)) out.push(name.slice(prefix.length));
2277
+ }
2278
+ } catch (err) {
2279
+ _iterator.e(err);
2280
+ } finally {
2281
+ _iterator.f();
2282
+ }
2283
+ return out;
2284
+ }
2285
+ }, {
2286
+ key: "entries",
2287
+ value: function entries() {
2288
+ return _toConsumableArray(this.values.entries());
2289
+ }
2290
+ }]);
2291
+ }();
2292
+
2293
+ // A utility produces declarations on its own selector, and/or nested rules whose
2294
+ // `&` is woven with that selector — the latter is how child-combinator utilities
2295
+ // like `space-x`/`divide-y` reach `& > * + *`.
2296
+
2297
+ // A variant either narrows the selector (`&:hover`, `.group:hover &`) or wraps
2298
+ // the rule in an at-rule (`@media`, `@supports`). It may do both.
2299
+
2840
2300
  // Holds the theme plus the rule and variant tables, and answers the keyword vs
2841
2301
  // value-taking questions the atom parser asks.
2842
2302
  var Registry = /*#__PURE__*/function () {
@@ -2886,6 +2346,18 @@ var Registry = /*#__PURE__*/function () {
2886
2346
  this.dynamicVariants.set(name, handler);
2887
2347
  return this;
2888
2348
  }
2349
+
2350
+ /** Every registered name, for tools that list them (completion, a utility reference). */
2351
+ }, {
2352
+ key: "names",
2353
+ value: function names() {
2354
+ return {
2355
+ rules: _toConsumableArray(this.rules.keys()),
2356
+ dynamicRules: _toConsumableArray(this.dynamicRules.keys()),
2357
+ variants: _toConsumableArray(this.variants.keys()),
2358
+ dynamicVariants: _toConsumableArray(this.dynamicVariants.keys())
2359
+ };
2360
+ }
2889
2361
  }, {
2890
2362
  key: "getRule",
2891
2363
  value: function getRule(root) {
@@ -4484,235 +3956,1098 @@ function resolveLeading(value, theme) {
4484
3956
  return [decl('line-height', "calc(var(--spacing) * ".concat(value.value, ")"))];
4485
3957
  }
4486
3958
  }
4487
- return null;
3959
+ return null;
3960
+ }
3961
+
3962
+ function registerUtilities(reg) {
3963
+ registerLayout(reg);
3964
+ registerFlexGrid(reg);
3965
+ registerSpacing(reg);
3966
+ registerSizing(reg);
3967
+ registerTypography(reg);
3968
+ registerBackgrounds(reg);
3969
+ registerBorders(reg);
3970
+ registerEffects(reg);
3971
+ registerTransforms(reg);
3972
+ registerTransitions(reg);
3973
+ registerFilters(reg);
3974
+ registerGradients(reg);
3975
+ }
3976
+
3977
+ function registerVariants(reg) {
3978
+ for (var _i = 0, _Object$entries = Object.entries(PSEUDO); _i < _Object$entries.length; _i++) {
3979
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
3980
+ name = _Object$entries$_i[0],
3981
+ sel = _Object$entries$_i[1];
3982
+ reg.variant(name, {
3983
+ selector: sel
3984
+ });
3985
+ }
3986
+ for (var _i2 = 0, _Object$entries2 = Object.entries(PSEUDO_ELEMENT); _i2 < _Object$entries2.length; _i2++) {
3987
+ var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
3988
+ _name = _Object$entries2$_i[0],
3989
+ _sel = _Object$entries2$_i[1];
3990
+ reg.variant(_name, {
3991
+ selector: _sel
3992
+ });
3993
+ }
3994
+ for (var _i3 = 0, _Object$entries3 = Object.entries(MEDIA); _i3 < _Object$entries3.length; _i3++) {
3995
+ var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
3996
+ _name2 = _Object$entries3$_i[0],
3997
+ params = _Object$entries3$_i[1];
3998
+ reg.variant(_name2, {
3999
+ atRule: {
4000
+ name: 'media',
4001
+ params: params
4002
+ }
4003
+ });
4004
+ }
4005
+ reg.variant('rtl', {
4006
+ selector: '&:where([dir="rtl"], [dir="rtl"] *)'
4007
+ });
4008
+ reg.variant('ltr', {
4009
+ selector: '&:where([dir="ltr"], [dir="ltr"] *)'
4010
+ });
4011
+ reg.variant('*', {
4012
+ selector: '& > *'
4013
+ }); // direct children
4014
+ reg.variant('**', {
4015
+ selector: '& *'
4016
+ }); // all descendants
4017
+ reg.variant('open', {
4018
+ selector: '&:is([open], :open)'
4019
+ });
4020
+ reg.variant('inert', {
4021
+ selector: '&:is([inert], [inert] *)'
4022
+ });
4023
+ registerBreakpointVariants(reg);
4024
+
4025
+ // `max-md`, `min-lg` resolve the named breakpoint from the theme; `max-[600px]`
4026
+ // takes the width verbatim. `max-*` overrides the `max-w`/`max-h` utilities here
4027
+ // because it's a variant, not a utility.
4028
+ var width = function width(v) {
4029
+ var _reg$theme$get;
4030
+ var value = named(v);
4031
+ if (!value) return null;
4032
+ return v.kind === 'arbitrary' ? value : (_reg$theme$get = reg.theme.get("--breakpoint-".concat(value))) !== null && _reg$theme$get !== void 0 ? _reg$theme$get : null;
4033
+ };
4034
+ reg.dynamicVariant('min', function (v) {
4035
+ return mediaWidth('min-width', width(v));
4036
+ });
4037
+ reg.dynamicVariant('max', function (v) {
4038
+ return mediaWidth('max-width', width(v));
4039
+ });
4040
+ reg.dynamicVariant('group', function (v, m) {
4041
+ return relational(v, m, '.group', ' &');
4042
+ });
4043
+ reg.dynamicVariant('peer', function (v, m) {
4044
+ return relational(v, m, '.peer', ' ~ &');
4045
+ });
4046
+ reg.dynamicVariant('data', function (v) {
4047
+ return named(v) ? {
4048
+ selector: "&[data-".concat(named(v), "]")
4049
+ } : null;
4050
+ });
4051
+ reg.dynamicVariant('aria', function (v) {
4052
+ return named(v) ? {
4053
+ selector: "&[aria-".concat(named(v), "]")
4054
+ } : null;
4055
+ });
4056
+ reg.dynamicVariant('has', function (v) {
4057
+ return named(v) ? {
4058
+ selector: "&:has(".concat(named(v), ")")
4059
+ } : null;
4060
+ });
4061
+ reg.dynamicVariant('not', function (v) {
4062
+ return notVariant(reg, v);
4063
+ });
4064
+ reg.dynamicVariant('supports', function (v) {
4065
+ return named(v) ? {
4066
+ atRule: {
4067
+ name: 'supports',
4068
+ params: "(".concat(named(v), ")")
4069
+ }
4070
+ } : null;
4071
+ });
4072
+ }
4073
+
4074
+ // The named breakpoints (`sm:`/`md:`/…) are static variants, so their media params
4075
+ // bake the theme value at registration. A `@theme { --breakpoint-md: … }` override
4076
+ // loaded later wouldn't reach them — so compile() re-runs this after loadTheme to
4077
+ // pick up overrides. (The dynamic `min-*`/`max-*` already resolve at apply time.)
4078
+ function registerBreakpointVariants(reg) {
4079
+ for (var _i4 = 0, _arr = ['sm', 'md', 'lg', 'xl', '2xl']; _i4 < _arr.length; _i4++) {
4080
+ var bp = _arr[_i4];
4081
+ var min = reg.theme.get("--breakpoint-".concat(bp));
4082
+ if (min) reg.variant(bp, {
4083
+ atRule: {
4084
+ name: 'media',
4085
+ params: "(min-width: ".concat(min, ")")
4086
+ }
4087
+ });
4088
+ }
4089
+ }
4090
+ function mediaWidth(feature, value) {
4091
+ return value ? {
4092
+ atRule: {
4093
+ name: 'media',
4094
+ params: "(".concat(feature, ": ").concat(value, ")")
4095
+ }
4096
+ } : null;
4097
+ }
4098
+ var PSEUDO = {
4099
+ hover: '&:hover',
4100
+ focus: '&:focus',
4101
+ 'focus-within': '&:focus-within',
4102
+ 'focus-visible': '&:focus-visible',
4103
+ active: '&:active',
4104
+ visited: '&:visited',
4105
+ target: '&:target',
4106
+ disabled: '&:disabled',
4107
+ enabled: '&:enabled',
4108
+ checked: '&:checked',
4109
+ indeterminate: '&:indeterminate',
4110
+ "default": '&:default',
4111
+ required: '&:required',
4112
+ valid: '&:valid',
4113
+ invalid: '&:invalid',
4114
+ 'read-only': '&:read-only',
4115
+ 'placeholder-shown': '&:placeholder-shown',
4116
+ autofill: '&:autofill',
4117
+ empty: '&:empty',
4118
+ first: '&:first-child',
4119
+ last: '&:last-child',
4120
+ only: '&:only-child',
4121
+ odd: '&:nth-child(odd)',
4122
+ even: '&:nth-child(even)',
4123
+ 'first-of-type': '&:first-of-type',
4124
+ 'last-of-type': '&:last-of-type'
4125
+ };
4126
+ var PSEUDO_ELEMENT = {
4127
+ before: '&::before',
4128
+ after: '&::after',
4129
+ placeholder: '&::placeholder',
4130
+ selection: '&::selection',
4131
+ marker: '&::marker',
4132
+ file: '&::file-selector-button',
4133
+ backdrop: '&::backdrop',
4134
+ 'first-line': '&::first-line',
4135
+ 'first-letter': '&::first-letter'
4136
+ };
4137
+ var MEDIA = {
4138
+ dark: '(prefers-color-scheme: dark)',
4139
+ 'motion-reduce': '(prefers-reduced-motion: reduce)',
4140
+ 'motion-safe': '(prefers-reduced-motion: no-preference)',
4141
+ 'contrast-more': '(prefers-contrast: more)',
4142
+ 'contrast-less': '(prefers-contrast: less)',
4143
+ portrait: '(orientation: portrait)',
4144
+ landscape: '(orientation: landscape)',
4145
+ print: 'print'
4146
+ };
4147
+ function named(v) {
4148
+ return v ? v.value : null;
4149
+ }
4150
+
4151
+ // `group-hover` → `.group:hover &`; `group-[.foo]` → `.group.foo &`. A named value
4152
+ // is a pseudo-class, an arbitrary one is a raw selector fragment. A `/name`
4153
+ // modifier scopes to a named group/peer (`group-hover/item` → `.group\/item:hover`).
4154
+ function relational(v, m, base, tail) {
4155
+ var value = named(v);
4156
+ if (!value) return null;
4157
+ var cond = v.kind === 'arbitrary' ? value : ":".concat(value);
4158
+ var scope = m ? "".concat(base, "\\/").concat(m.value) : base;
4159
+ return {
4160
+ selector: "".concat(scope).concat(cond).concat(tail)
4161
+ };
4162
+ }
4163
+
4164
+ // `not-hover` → `&:not(:hover)`, `not-first` → `&:not(:first-child)`: resolve the
4165
+ // inner variant's pseudo, so the selector is valid (not the literal name). Only
4166
+ // simple pseudo variants compose; `not-[…]` takes an arbitrary selector.
4167
+ function notVariant(reg, v) {
4168
+ var _reg$getVariant;
4169
+ var value = named(v);
4170
+ if (!value) return null;
4171
+ if (v.kind === 'arbitrary') return {
4172
+ selector: "&:not(".concat(value, ")")
4173
+ };
4174
+ var frag = (_reg$getVariant = reg.getVariant(value)) === null || _reg$getVariant === void 0 || (_reg$getVariant = _reg$getVariant.selector) === null || _reg$getVariant === void 0 ? void 0 : _reg$getVariant.replace(/^&/, '').trim();
4175
+ return frag && frag.startsWith(':') ? {
4176
+ selector: "&:not(".concat(frag, ")")
4177
+ } : null;
4178
+ }
4179
+
4180
+ // The batteries-included registry: the default token theme plus the utility
4181
+ // families and variants. Projects extend it (`@utility`, `@theme`, JS config) or
4182
+ // build a bare `new Registry(theme)` and register their own.
4183
+ function createRegistry() {
4184
+ var reg = new Registry(defaultTheme());
4185
+ registerUtilities(reg);
4186
+ registerVariants(reg);
4187
+ return reg;
4188
+ }
4189
+
4190
+ // Reads `@utility` and `@custom-variant` blocks from CSS and registers them into
4191
+ // the registry — the CSS-first way to add utilities and variants, alongside
4192
+ // `@theme` for tokens. Call after loadTheme so functional utilities can resolve
4193
+ // against the theme.
4194
+ function loadDirectives(css, reg) {
4195
+ var sheet = parseCss(css);
4196
+ var _iterator = _createForOfIteratorHelper(sheet.children),
4197
+ _step;
4198
+ try {
4199
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
4200
+ var node = _step.value;
4201
+ if (node.type !== 'atrule') continue;
4202
+ if (node.name === 'utility') registerUtility(node, reg);else if (node.name === 'custom-variant') registerVariant(node, reg);
4203
+ }
4204
+ } catch (err) {
4205
+ _iterator.e(err);
4206
+ } finally {
4207
+ _iterator.f();
4208
+ }
4209
+ return reg;
4210
+ }
4211
+ function registerUtility(atRule, reg) {
4212
+ var _atRule$preludeText;
4213
+ var name = ((_atRule$preludeText = atRule.preludeText) !== null && _atRule$preludeText !== void 0 ? _atRule$preludeText : '').trim();
4214
+ if (!name || !atRule.block) return;
4215
+
4216
+ // Flat declarations plus any nested rules (`&:hover`, `&::-webkit-scrollbar`);
4217
+ // the nested `&` is later woven with the utility's own selector by the compiler.
4218
+ var products = toProducts(atRule.block.children);
4219
+ if (products.length === 0) return;
4220
+
4221
+ // A trailing `-*` marks a functional utility: `tab-*` handles `tab-2`, `tab-[3]`.
4222
+ if (name.endsWith('-*')) {
4223
+ var root = name.slice(0, -2);
4224
+ if (root) reg.dynamicRule(root, function (ctx) {
4225
+ return resolveProducts(products, ctx);
4226
+ });
4227
+ return;
4228
+ }
4229
+ reg.rule(name, products);
4230
+ }
4231
+ function toProducts(children) {
4232
+ var out = [];
4233
+ var _iterator2 = _createForOfIteratorHelper(children),
4234
+ _step2;
4235
+ try {
4236
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4237
+ var c = _step2.value;
4238
+ if (c.type === 'declaration') {
4239
+ var _d$rawValue;
4240
+ var d = c;
4241
+ out.push(decl(d.property, ((_d$rawValue = d.rawValue) !== null && _d$rawValue !== void 0 ? _d$rawValue : '').trim(), d.important === true));
4242
+ } else if (c.type === 'rule') {
4243
+ var _r$declarations, _r$children, _r$rawSelector;
4244
+ var r = c;
4245
+ // The parser splits a rule's own declarations from its nested rules; a
4246
+ // utility body wants both, declarations first.
4247
+ var kids = [].concat(_toConsumableArray((_r$declarations = r.declarations) !== null && _r$declarations !== void 0 ? _r$declarations : []), _toConsumableArray((_r$children = r.children) !== null && _r$children !== void 0 ? _r$children : []));
4248
+ out.push(rule(((_r$rawSelector = r.rawSelector) !== null && _r$rawSelector !== void 0 ? _r$rawSelector : '').trim(), toProducts(kids)));
4249
+ }
4250
+ }
4251
+ } catch (err) {
4252
+ _iterator2.e(err);
4253
+ } finally {
4254
+ _iterator2.f();
4255
+ }
4256
+ return out;
4257
+ }
4258
+
4259
+ // Applies a functional utility's templates to one atom, walking nested rules too.
4260
+ // `--value()` is required — if it can't resolve, the whole utility is dropped
4261
+ // (returns null). `--modifier()` is optional — a declaration using it is skipped
4262
+ // when there's no matching modifier, so `text-lg` and `text-lg/7` share one def.
4263
+ function resolveProducts(templates, ctx) {
4264
+ var out = [];
4265
+ var _iterator3 = _createForOfIteratorHelper(templates),
4266
+ _step3;
4267
+ try {
4268
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4269
+ var t = _step3.value;
4270
+ if (t.kind === 'declaration') {
4271
+ var withValue = replaceFn(t.value, '--value', function (args) {
4272
+ return resolveValue(args, ctx);
4273
+ });
4274
+ if (withValue === null) return null;
4275
+ var withModifier = replaceFn(withValue, '--modifier', function (args) {
4276
+ return resolveModifier(args, ctx);
4277
+ });
4278
+ if (withModifier === null) continue;
4279
+ out.push(_objectSpread2(_objectSpread2({}, t), {}, {
4280
+ value: withModifier
4281
+ }));
4282
+ } else {
4283
+ var inner = resolveProducts(t.nodes, ctx);
4284
+ if (inner === null) return null;
4285
+ out.push(rule(t.selector, inner));
4286
+ }
4287
+ }
4288
+ } catch (err) {
4289
+ _iterator3.e(err);
4290
+ } finally {
4291
+ _iterator3.f();
4292
+ }
4293
+ return out.length ? out : null;
4294
+ }
4295
+ function resolveValue(args, ctx) {
4296
+ var value = ctx.value;
4297
+ if (!value) return null;
4298
+ for (var _i = 0, _splitArgs = splitArgs(args); _i < _splitArgs.length; _i++) {
4299
+ var arg = _splitArgs[_i];
4300
+ var themed = fromTheme(arg, value.kind === 'named' ? value.value : null, ctx);
4301
+ if (themed !== null) return themed;
4302
+ if (value.kind === 'named') {
4303
+ var lit = fromNamed(arg, value.value);
4304
+ if (lit !== null) return lit;
4305
+ } else {
4306
+ var arb = fromArbitrary(arg, value.value, value.dataType);
4307
+ if (arb !== null) return arb;
4308
+ }
4309
+ }
4310
+ return null;
4311
+ }
4312
+ function resolveModifier(args, ctx) {
4313
+ var modifier = ctx.modifier;
4314
+ if (!modifier) return null;
4315
+ for (var _i2 = 0, _splitArgs2 = splitArgs(args); _i2 < _splitArgs2.length; _i2++) {
4316
+ var arg = _splitArgs2[_i2];
4317
+ var themed = fromTheme(arg, modifier.kind === 'named' ? modifier.value : null, ctx);
4318
+ if (themed !== null) return themed;
4319
+ if (modifier.kind === 'named') {
4320
+ var lit = fromNamed(arg, modifier.value);
4321
+ if (lit !== null) return lit;
4322
+ } else {
4323
+ var arb = fromArbitrary(arg, modifier.value, null);
4324
+ if (arb !== null) return arb;
4325
+ }
4326
+ }
4327
+ return null;
4328
+ }
4329
+
4330
+ // `--foo` / `--foo-*` names a theme namespace; the atom's named value keys into
4331
+ // it (`--value(--tab-size)` + `tab-2` → `var(--tab-size-2)`).
4332
+ function fromTheme(arg, key, ctx) {
4333
+ if (key === null || !arg.startsWith('--')) return null;
4334
+ var ns = arg.replace(/-?\*$/, '').slice(2);
4335
+ return ns ? ctx.theme.resolve(ns, key) : null;
4336
+ }
4337
+
4338
+ // A bare value against a data-type keyword (`integer`, `number`, `percentage`) or a
4339
+ // quoted literal (`'inline'`).
4340
+ function fromNamed(arg, value) {
4341
+ if (isQuoted(arg)) return arg.slice(1, -1) === value ? value : null;
4342
+ var rx = NUMERIC[arg];
4343
+ return rx ? rx.test(value) ? value : null : null;
4344
+ }
4345
+
4346
+ // An arbitrary value against `[*]` (anything) or a typed bracket (`[integer]`,
4347
+ // `[length]`), gated on the value's own `type:` hint when it carries one.
4348
+ function fromArbitrary(arg, value, dataType) {
4349
+ if (arg[0] !== '[' || arg[arg.length - 1] !== ']') return null;
4350
+ var want = arg.slice(1, -1);
4351
+ if (want === '*') return value;
4352
+ if (dataType !== null) return dataType === want ? value : null;
4353
+ // Untyped arbitrary: validate against the simple numeric types we can check.
4354
+ var rx = NUMERIC[want];
4355
+ return rx ? rx.test(value) ? value : null : value;
4356
+ }
4357
+ var NUMERIC = {
4358
+ integer: /^-?\d+$/,
4359
+ number: /^-?\d*\.?\d+$/,
4360
+ percentage: /^-?\d*\.?\d+%$/
4361
+ };
4362
+ function isQuoted(s) {
4363
+ return s.length >= 2 && (s[0] === '"' || s[0] === "'") && s[s.length - 1] === s[0];
4364
+ }
4365
+ function splitArgs(args) {
4366
+ return splitAtTopLevel(args, ',').map(function (a) {
4367
+ return a.trim();
4368
+ }).filter(function (a) {
4369
+ return a !== '';
4370
+ });
4371
+ }
4372
+
4373
+ // Replaces every `name(...)` call in `input` (parens balanced, even when nested in
4374
+ // `calc(...)`) with `resolve`'s result. Returns null if any call fails to resolve.
4375
+ function replaceFn(input, name, resolve) {
4376
+ var token = name + '(';
4377
+ var out = '';
4378
+ var i = 0;
4379
+ for (;;) {
4380
+ var start = input.indexOf(token, i);
4381
+ if (start === -1) return out + input.slice(i);
4382
+ out += input.slice(i, start);
4383
+ var depth = 0;
4384
+ var j = start + token.length - 1;
4385
+ for (; j < input.length; j++) {
4386
+ if (input[j] === '(') depth++;else if (input[j] === ')' && --depth === 0) break;
4387
+ }
4388
+ if (j >= input.length) return null; // unbalanced
4389
+ var resolved = resolve(input.slice(start + token.length, j));
4390
+ if (resolved === null) return null;
4391
+ out += resolved;
4392
+ i = j + 1;
4393
+ }
4394
+ }
4395
+ function registerVariant(atRule, reg) {
4396
+ var _atRule$preludeText2;
4397
+ var prelude = ((_atRule$preludeText2 = atRule.preludeText) !== null && _atRule$preludeText2 !== void 0 ? _atRule$preludeText2 : '').trim();
4398
+ if (!prelude) return;
4399
+
4400
+ // Block form: `@custom-variant name { &:hover { @slot } }` — the prelude is just
4401
+ // the name and the block describes the wrapping, marked by `@slot`.
4402
+ if (atRule.block) {
4403
+ var wrap = blockToWrap(atRule.block.children);
4404
+ if (prelude && wrap) reg.variant(prelude, wrap);
4405
+ return;
4406
+ }
4407
+
4408
+ // Shorthand: `@custom-variant name (condition)`.
4409
+ var paren = prelude.indexOf('(');
4410
+ if (paren === -1 || !prelude.endsWith(')')) return;
4411
+ var name = prelude.slice(0, paren).trim();
4412
+ var condition = prelude.slice(paren + 1, -1).trim();
4413
+ if (!name || !condition) return;
4414
+ reg.variant(name, wrapFor(condition));
4415
+ }
4416
+
4417
+ // Walk the single path down to `@slot`, collecting the selector (nested rules,
4418
+ // combined by `&` substitution) and/or the wrapping at-rule (`@media`, `@supports`).
4419
+ // Supports one selector level, one at-rule level, or both nested.
4420
+ function blockToWrap(children) {
4421
+ var selector;
4422
+ var at;
4423
+ var node = firstBlockChild(children);
4424
+ while (node) {
4425
+ if (node.type === 'rule') {
4426
+ var _rawSelector, _children;
4427
+ var sel = ((_rawSelector = node.rawSelector) !== null && _rawSelector !== void 0 ? _rawSelector : '').trim();
4428
+ selector = selector ? sel.replace(/&/g, selector) : sel;
4429
+ node = firstBlockChild((_children = node.children) !== null && _children !== void 0 ? _children : []);
4430
+ } else if (node.type === 'atrule') {
4431
+ var _ar$preludeText;
4432
+ var ar = node;
4433
+ if (ar.name === 'slot') break;
4434
+ at = {
4435
+ name: ar.name,
4436
+ params: ((_ar$preludeText = ar.preludeText) !== null && _ar$preludeText !== void 0 ? _ar$preludeText : '').trim()
4437
+ };
4438
+ node = ar.block ? firstBlockChild(ar.block.children) : undefined;
4439
+ } else {
4440
+ node = undefined;
4441
+ }
4442
+ }
4443
+ var wrap = {};
4444
+ if (selector) wrap.selector = selector.includes('&') ? selector : "&".concat(selector);
4445
+ if (at) wrap.atRule = at;
4446
+ return wrap.selector || wrap.atRule ? wrap : null;
4447
+ }
4448
+ function firstBlockChild(children) {
4449
+ return children.find(function (c) {
4450
+ return c.type === 'rule' || c.type === 'atrule';
4451
+ });
4452
+ }
4453
+ function wrapFor(condition) {
4454
+ if (condition[0] === '@') {
4455
+ var cut = condition.search(/[\s(]/);
4456
+ var at = cut === -1 ? condition.slice(1) : condition.slice(1, cut);
4457
+ var params = cut === -1 ? '' : condition.slice(cut).trim();
4458
+ return {
4459
+ atRule: {
4460
+ name: at,
4461
+ params: params
4462
+ }
4463
+ };
4464
+ }
4465
+ return {
4466
+ selector: condition.includes('&') ? condition : "&".concat(condition)
4467
+ };
4468
+ }
4469
+
4470
+ // Read `@theme { --color-red-500: …; --spacing: …; }` blocks from CSS into a
4471
+ // Theme. This is the CSS-first way to define tokens; the registry is then
4472
+ // built from the resulting theme.
4473
+ function loadTheme(css) {
4474
+ var theme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Theme();
4475
+ var sheet = parseCss(css);
4476
+ var _iterator = _createForOfIteratorHelper(sheet.children),
4477
+ _step;
4478
+ try {
4479
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
4480
+ var node = _step.value;
4481
+ if (node.type === 'atrule' && node.name === 'theme' && node.block) {
4482
+ collect(node, theme);
4483
+ }
4484
+ }
4485
+ } catch (err) {
4486
+ _iterator.e(err);
4487
+ } finally {
4488
+ _iterator.f();
4489
+ }
4490
+ return theme;
4491
+ }
4492
+ function collect(atRule, theme) {
4493
+ var _iterator2 = _createForOfIteratorHelper(atRule.block.children),
4494
+ _step2;
4495
+ try {
4496
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4497
+ var child = _step2.value;
4498
+ if (child.type === 'declaration' && isCustomProperty(child)) {
4499
+ var _child$rawValue;
4500
+ theme.add(child.property, ((_child$rawValue = child.rawValue) !== null && _child$rawValue !== void 0 ? _child$rawValue : '').trim());
4501
+ }
4502
+ }
4503
+ } catch (err) {
4504
+ _iterator2.e(err);
4505
+ } finally {
4506
+ _iterator2.f();
4507
+ }
4508
+ }
4509
+ function isCustomProperty(d) {
4510
+ return d.customProperty === true || d.property.startsWith('--');
4488
4511
  }
4489
4512
 
4490
- function registerUtilities(reg) {
4491
- registerLayout(reg);
4492
- registerFlexGrid(reg);
4493
- registerSpacing(reg);
4494
- registerSizing(reg);
4495
- registerTypography(reg);
4496
- registerBackgrounds(reg);
4497
- registerBorders(reg);
4498
- registerEffects(reg);
4499
- registerTransforms(reg);
4500
- registerTransitions(reg);
4501
- registerFilters(reg);
4502
- registerGradients(reg);
4513
+ // Emit the theme as `:root { --token: value; … }` so the tokens ship as live
4514
+ // custom properties. Pass `used` to emit only the tokens actually referenced
4515
+ // (plus any they transitively reference) — see {@link collectVarRefs}.
4516
+ function emitTheme(theme) {
4517
+ var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':root';
4518
+ var used = arguments.length > 2 ? arguments[2] : undefined;
4519
+ var entries = used ? usedEntries(theme, used) : theme.entries();
4520
+ return rule(selector, entries.map(function (_ref) {
4521
+ var _ref2 = _slicedToArray(_ref, 2),
4522
+ name = _ref2[0],
4523
+ value = _ref2[1];
4524
+ return decl(name, value);
4525
+ }));
4503
4526
  }
4527
+ var VAR_REF = /var\(\s*(--[\w-]+)/g;
4504
4528
 
4505
- function registerVariants(reg) {
4506
- for (var _i = 0, _Object$entries = Object.entries(PSEUDO); _i < _Object$entries.length; _i++) {
4507
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
4508
- name = _Object$entries$_i[0],
4509
- sel = _Object$entries$_i[1];
4510
- reg.variant(name, {
4511
- selector: sel
4512
- });
4513
- }
4514
- for (var _i2 = 0, _Object$entries2 = Object.entries(PSEUDO_ELEMENT); _i2 < _Object$entries2.length; _i2++) {
4515
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
4516
- _name = _Object$entries2$_i[0],
4517
- _sel = _Object$entries2$_i[1];
4518
- reg.variant(_name, {
4519
- selector: _sel
4520
- });
4529
+ // Every `--token` referenced through `var(--token)` across a compiled tree.
4530
+ function collectVarRefs(nodes) {
4531
+ var into = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();
4532
+ var _iterator3 = _createForOfIteratorHelper(nodes),
4533
+ _step3;
4534
+ try {
4535
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4536
+ var node = _step3.value;
4537
+ if (node.kind === 'declaration') {
4538
+ var _iterator4 = _createForOfIteratorHelper(node.value.matchAll(VAR_REF)),
4539
+ _step4;
4540
+ try {
4541
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
4542
+ var m = _step4.value;
4543
+ into.add(m[1]);
4544
+ }
4545
+ } catch (err) {
4546
+ _iterator4.e(err);
4547
+ } finally {
4548
+ _iterator4.f();
4549
+ }
4550
+ } else if (node.kind === 'raw') {
4551
+ var _iterator5 = _createForOfIteratorHelper(node.text.matchAll(VAR_REF)),
4552
+ _step5;
4553
+ try {
4554
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
4555
+ var _m = _step5.value;
4556
+ into.add(_m[1]);
4557
+ }
4558
+ } catch (err) {
4559
+ _iterator5.e(err);
4560
+ } finally {
4561
+ _iterator5.f();
4562
+ }
4563
+ } else {
4564
+ collectVarRefs(node.nodes, into);
4565
+ }
4566
+ }
4567
+ } catch (err) {
4568
+ _iterator3.e(err);
4569
+ } finally {
4570
+ _iterator3.f();
4521
4571
  }
4522
- for (var _i3 = 0, _Object$entries3 = Object.entries(MEDIA); _i3 < _Object$entries3.length; _i3++) {
4523
- var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
4524
- _name2 = _Object$entries3$_i[0],
4525
- params = _Object$entries3$_i[1];
4526
- reg.variant(_name2, {
4527
- atRule: {
4528
- name: 'media',
4529
- params: params
4572
+ return into;
4573
+ }
4574
+
4575
+ // The theme entries to keep for `used`: the referenced tokens plus the transitive
4576
+ // closure of any tokens their own values reference (e.g. `--color-primary:
4577
+ // var(--color-blue-500)`). Insertion order is preserved.
4578
+ function usedEntries(theme, used) {
4579
+ var keep = new Set();
4580
+ var stack = _toConsumableArray(used);
4581
+ while (stack.length) {
4582
+ var name = stack.pop();
4583
+ if (keep.has(name)) continue;
4584
+ var value = theme.get(name);
4585
+ if (value === undefined) continue; // referenced but not a theme token
4586
+ keep.add(name);
4587
+ var _iterator6 = _createForOfIteratorHelper(value.matchAll(VAR_REF)),
4588
+ _step6;
4589
+ try {
4590
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4591
+ var m = _step6.value;
4592
+ stack.push(m[1]);
4530
4593
  }
4531
- });
4594
+ } catch (err) {
4595
+ _iterator6.e(err);
4596
+ } finally {
4597
+ _iterator6.f();
4598
+ }
4532
4599
  }
4533
- reg.variant('rtl', {
4534
- selector: '&:where([dir="rtl"], [dir="rtl"] *)'
4535
- });
4536
- reg.variant('ltr', {
4537
- selector: '&:where([dir="ltr"], [dir="ltr"] *)'
4538
- });
4539
- reg.variant('*', {
4540
- selector: '& > *'
4541
- }); // direct children
4542
- reg.variant('**', {
4543
- selector: '& *'
4544
- }); // all descendants
4545
- reg.variant('open', {
4546
- selector: '&:is([open], :open)'
4547
- });
4548
- reg.variant('inert', {
4549
- selector: '&:is([inert], [inert] *)'
4600
+ return theme.entries().filter(function (_ref3) {
4601
+ var _ref4 = _slicedToArray(_ref3, 1),
4602
+ name = _ref4[0];
4603
+ return keep.has(name);
4550
4604
  });
4551
- registerBreakpointVariants(reg);
4605
+ }
4552
4606
 
4553
- // `max-md`, `min-lg` resolve the named breakpoint from the theme; `max-[600px]`
4554
- // takes the width verbatim. `max-*` overrides the `max-w`/`max-h` utilities here
4555
- // because it's a variant, not a utility.
4556
- var width = function width(v) {
4557
- var _reg$theme$get;
4558
- var value = named(v);
4559
- if (!value) return null;
4560
- return v.kind === 'arbitrary' ? value : (_reg$theme$get = reg.theme.get("--breakpoint-".concat(value))) !== null && _reg$theme$get !== void 0 ? _reg$theme$get : null;
4607
+ // ─── Parser tree → engine AST ────────────────────────────────────────────────
4608
+
4609
+ var offsetOf = function offsetOf(node) {
4610
+ var _node$loc$start$offse, _node$loc;
4611
+ return (_node$loc$start$offse = (_node$loc = node.loc) === null || _node$loc === void 0 ? void 0 : _node$loc.start.offset) !== null && _node$loc$start$offse !== void 0 ? _node$loc$start$offse : 0;
4612
+ };
4613
+ function locOf(node, source) {
4614
+ if (!source || !node.loc) return undefined;
4615
+ return {
4616
+ source: source,
4617
+ line: node.loc.start.line,
4618
+ column: Math.max(0, node.loc.start.column - 1)
4561
4619
  };
4562
- reg.dynamicVariant('min', function (v) {
4563
- return mediaWidth('min-width', width(v));
4564
- });
4565
- reg.dynamicVariant('max', function (v) {
4566
- return mediaWidth('max-width', width(v));
4567
- });
4568
- reg.dynamicVariant('group', function (v, m) {
4569
- return relational(v, m, '.group', ' &');
4570
- });
4571
- reg.dynamicVariant('peer', function (v, m) {
4572
- return relational(v, m, '.peer', ' ~ &');
4573
- });
4574
- reg.dynamicVariant('data', function (v) {
4575
- return named(v) ? {
4576
- selector: "&[data-".concat(named(v), "]")
4577
- } : null;
4578
- });
4579
- reg.dynamicVariant('aria', function (v) {
4580
- return named(v) ? {
4581
- selector: "&[aria-".concat(named(v), "]")
4582
- } : null;
4620
+ }
4621
+
4622
+ /** Parses author CSS into the engine's AST, in source order. */
4623
+ function parseStyle(css, from) {
4624
+ var sheet = parseCss(css, {
4625
+ includeSourceMaps: true,
4626
+ includeComments: false
4583
4627
  });
4584
- reg.dynamicVariant('has', function (v) {
4585
- return named(v) ? {
4586
- selector: "&:has(".concat(named(v), ")")
4587
- } : null;
4628
+ return convertAll(sheet.children, from);
4629
+ }
4630
+ function convertAll(nodes, from) {
4631
+ var out = [];
4632
+ var _iterator = _createForOfIteratorHelper(nodes),
4633
+ _step;
4634
+ try {
4635
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
4636
+ var node = _step.value;
4637
+ var converted = convert(node, from);
4638
+ if (converted) out.push(converted);
4639
+ }
4640
+ } catch (err) {
4641
+ _iterator.e(err);
4642
+ } finally {
4643
+ _iterator.f();
4644
+ }
4645
+ return out;
4646
+ }
4647
+ function convert(node, from) {
4648
+ switch (node.type) {
4649
+ case 'declaration':
4650
+ {
4651
+ var _d$rawValue;
4652
+ var d = node;
4653
+ return decl(d.property, (_d$rawValue = d.rawValue) !== null && _d$rawValue !== void 0 ? _d$rawValue : '', d.important, locOf(d, from));
4654
+ }
4655
+ case 'rule':
4656
+ {
4657
+ var _r$declarations, _r$children, _r$rawSelector;
4658
+ var r = node;
4659
+ // The parser keeps declarations and nested rules apart; the source offsets put them
4660
+ // back in the order they were written, which is the order they cascade in.
4661
+ var children = [].concat(_toConsumableArray((_r$declarations = r.declarations) !== null && _r$declarations !== void 0 ? _r$declarations : []), _toConsumableArray((_r$children = r.children) !== null && _r$children !== void 0 ? _r$children : []));
4662
+ children.sort(function (a, b) {
4663
+ return offsetOf(a) - offsetOf(b);
4664
+ });
4665
+ return rule(((_r$rawSelector = r.rawSelector) !== null && _r$rawSelector !== void 0 ? _r$rawSelector : '').trim(), convertAll(children, from), locOf(r, from));
4666
+ }
4667
+ case 'keyframe':
4668
+ {
4669
+ var k = node;
4670
+ return rule(k.selector, convertAll(k.declarations, from), locOf(k, from));
4671
+ }
4672
+ case 'atrule':
4673
+ {
4674
+ var _a$preludeText;
4675
+ var a = node;
4676
+ var params = ((_a$preludeText = a.preludeText) !== null && _a$preludeText !== void 0 ? _a$preludeText : '').trim();
4677
+ // A statement (`@import`, `@apply` before expansion has a block of its own only when
4678
+ // nested): no block means no braces in the output either.
4679
+ if (!a.block) return a.name === 'apply' ? atRule('apply', params, [], locOf(a, from)) : raw("@".concat(a.name).concat(params ? ' ' + params : '', ";"), locOf(a, from));
4680
+ return atRule(a.name, params, convertAll(a.block.children, from), locOf(a, from));
4681
+ }
4682
+ default:
4683
+ return null;
4684
+ }
4685
+ }
4686
+
4687
+ // ─── @apply ──────────────────────────────────────────────────────────────────
4688
+
4689
+ /**
4690
+ * Replaces each `@apply a b c` with what those utilities produce: flat declarations in place,
4691
+ * and a nested rule (`&` standing for the applying selector) for a utility that needs a
4692
+ * selector of its own (`hover:`, `group-hover:`, `space-x-*`, `md:`). Unknown classes are
4693
+ * skipped. `applied` collects the utilities used.
4694
+ */
4695
+ function applyUtilities(nodes, reg) {
4696
+ var applied = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
4697
+ var out = [];
4698
+ var _iterator2 = _createForOfIteratorHelper(nodes),
4699
+ _step2;
4700
+ try {
4701
+ var _loop = function _loop() {
4702
+ var node = _step2.value;
4703
+ if (node.kind === 'at-rule' && node.name === 'apply') {
4704
+ // What it expands to was written on the @apply line, as far as a source map can tell.
4705
+ out.push.apply(out, _toConsumableArray(expandOne(node.params, reg, applied).map(function (n) {
4706
+ return withLoc(n, node.loc);
4707
+ })));
4708
+ } else if (node.kind === 'rule' || node.kind === 'at-rule') {
4709
+ out.push(_objectSpread2(_objectSpread2({}, node), {}, {
4710
+ nodes: applyUtilities(node.nodes, reg, applied)
4711
+ }));
4712
+ } else {
4713
+ out.push(node);
4714
+ }
4715
+ };
4716
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4717
+ _loop();
4718
+ }
4719
+ } catch (err) {
4720
+ _iterator2.e(err);
4721
+ } finally {
4722
+ _iterator2.f();
4723
+ }
4724
+ return out;
4725
+ }
4726
+ function expandOne(params, reg, applied) {
4727
+ var list = params.trim();
4728
+ // A trailing `!important` marks every inlined declaration (Tailwind semantics).
4729
+ var important = false;
4730
+ var bang = list.match(/!important\s*$/);
4731
+ if (bang) {
4732
+ important = true;
4733
+ list = list.slice(0, bang.index).trim();
4734
+ }
4735
+ var decls = [];
4736
+ var nested = [];
4737
+ var _iterator3 = _createForOfIteratorHelper(list.split(/\s+/)),
4738
+ _step3;
4739
+ try {
4740
+ var _loop2 = function _loop2() {
4741
+ var token = _step3.value;
4742
+ if (!token) return 0; // continue
4743
+ var atom = parseAtom(token, reg);
4744
+ if (!atom) return 0; // continue
4745
+ var compiled = compileAtom(atom, reg);
4746
+ if (!compiled || compiled.length === 0) return 0; // continue
4747
+ applied.add(token);
4748
+ if (important) markImportant(compiled);
4749
+ var own = '.' + escapeClass(atom.raw);
4750
+ // A plain utility, one rule on its own class with only declarations, inlines.
4751
+ var only = compiled[0];
4752
+ if (compiled.length === 1 && only.kind === 'rule' && only.selector === own && only.nodes.every(function (n) {
4753
+ return n.kind === 'declaration';
4754
+ })) {
4755
+ decls.push.apply(decls, _toConsumableArray(only.nodes.map(function (n) {
4756
+ return _objectSpread2({}, n);
4757
+ })));
4758
+ return 0; // continue
4759
+ }
4760
+ // Anything else keeps its structure, with the utility's class replaced by `&`.
4761
+ nested.push.apply(nested, _toConsumableArray(compiled.map(function (n) {
4762
+ return toNesting(n, own);
4763
+ })));
4764
+ },
4765
+ _ret;
4766
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4767
+ _ret = _loop2();
4768
+ if (_ret === 0) continue;
4769
+ }
4770
+ // Flat declarations first, then the nested rules: the order the author's line implies.
4771
+ } catch (err) {
4772
+ _iterator3.e(err);
4773
+ } finally {
4774
+ _iterator3.f();
4775
+ }
4776
+ return [].concat(decls, nested);
4777
+ }
4778
+ function withLoc(node, loc) {
4779
+ var _node$loc2;
4780
+ if (!loc) return node;
4781
+ if (node.kind === 'rule' || node.kind === 'at-rule') return _objectSpread2(_objectSpread2({}, node), {}, {
4782
+ loc: (_node$loc2 = node.loc) !== null && _node$loc2 !== void 0 ? _node$loc2 : loc,
4783
+ nodes: node.nodes.map(function (n) {
4784
+ return withLoc(n, loc);
4785
+ })
4786
+ });
4787
+ return node.loc ? node : _objectSpread2(_objectSpread2({}, node), {}, {
4788
+ loc: loc
4588
4789
  });
4589
- reg.dynamicVariant('not', function (v) {
4590
- return notVariant(reg, v);
4790
+ }
4791
+ function toNesting(node, own) {
4792
+ if (node.kind === 'rule') return _objectSpread2(_objectSpread2({}, node), {}, {
4793
+ selector: node.selector.split(own).join('&'),
4794
+ nodes: node.nodes.map(function (n) {
4795
+ return toNesting(n, own);
4796
+ })
4591
4797
  });
4592
- reg.dynamicVariant('supports', function (v) {
4593
- return named(v) ? {
4594
- atRule: {
4595
- name: 'supports',
4596
- params: "(".concat(named(v), ")")
4597
- }
4598
- } : null;
4798
+ if (node.kind === 'at-rule') return _objectSpread2(_objectSpread2({}, node), {}, {
4799
+ nodes: node.nodes.map(function (n) {
4800
+ return toNesting(n, own);
4801
+ })
4599
4802
  });
4803
+ return node;
4804
+ }
4805
+ function markImportant(nodes) {
4806
+ var _iterator4 = _createForOfIteratorHelper(nodes),
4807
+ _step4;
4808
+ try {
4809
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
4810
+ var n = _step4.value;
4811
+ if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant(n.nodes);
4812
+ }
4813
+ } catch (err) {
4814
+ _iterator4.e(err);
4815
+ } finally {
4816
+ _iterator4.f();
4817
+ }
4600
4818
  }
4601
4819
 
4602
- // The named breakpoints (`sm:`/`md:`/…) are static variants, so their media params
4603
- // bake the theme value at registration. A `@theme { --breakpoint-md: … }` override
4604
- // loaded later wouldn't reach them — so compile() re-runs this after loadTheme to
4605
- // pick up overrides. (The dynamic `min-*`/`max-*` already resolve at apply time.)
4606
- function registerBreakpointVariants(reg) {
4607
- for (var _i4 = 0, _arr = ['sm', 'md', 'lg', 'xl', '2xl']; _i4 < _arr.length; _i4++) {
4608
- var bp = _arr[_i4];
4609
- var min = reg.theme.get("--breakpoint-".concat(bp));
4610
- if (min) reg.variant(bp, {
4611
- atRule: {
4612
- name: 'media',
4613
- params: "(min-width: ".concat(min, ")")
4820
+ // ─── Nesting → plain selectors ───────────────────────────────────────────────
4821
+
4822
+ // At-rules whose body is more stylesheet: nesting is resolved through them. Everything else
4823
+ // (`@keyframes`, `@font-face`, `@property`, …) is left exactly as written.
4824
+ var GROUPING = new Set(['media', 'supports', 'container', 'layer', 'document', 'scope', 'starting-style']);
4825
+
4826
+ /** Splits a selector list on its top-level commas (not those inside `:is(…)`, `[…]` or quotes). */
4827
+ function splitSelectorList(selector) {
4828
+ var parts = [];
4829
+ var depth = 0;
4830
+ var quote = '';
4831
+ var start = 0;
4832
+ for (var i = 0; i < selector.length; i++) {
4833
+ var c = selector[i];
4834
+ if (quote) {
4835
+ if (c === '\\') i++;else if (c === quote) quote = '';
4836
+ } else if (c === '"' || c === "'") quote = c;else if (c === '\\') i++;else if (c === '(' || c === '[') depth++;else if (c === ')' || c === ']') depth--;else if (c === ',' && depth === 0) {
4837
+ parts.push(selector.slice(start, i).trim());
4838
+ start = i + 1;
4839
+ }
4840
+ }
4841
+ parts.push(selector.slice(start).trim());
4842
+ return parts.filter(Boolean);
4843
+ }
4844
+
4845
+ /** The selector a nested rule stands for, given its parent's: `&` replaced, or a descendant. */
4846
+ function resolveNested(child, parent) {
4847
+ var parents = splitSelectorList(parent);
4848
+ var out = [];
4849
+ var _iterator5 = _createForOfIteratorHelper(splitSelectorList(child)),
4850
+ _step5;
4851
+ try {
4852
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
4853
+ var c = _step5.value;
4854
+ var _iterator6 = _createForOfIteratorHelper(parents),
4855
+ _step6;
4856
+ try {
4857
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4858
+ var p = _step6.value;
4859
+ out.push(c.includes('&') ? c.split('&').join(p) : "".concat(p, " ").concat(c));
4860
+ }
4861
+ } catch (err) {
4862
+ _iterator6.e(err);
4863
+ } finally {
4864
+ _iterator6.f();
4614
4865
  }
4615
- });
4866
+ }
4867
+ } catch (err) {
4868
+ _iterator5.e(err);
4869
+ } finally {
4870
+ _iterator5.f();
4616
4871
  }
4872
+ return out.join(', ');
4617
4873
  }
4618
- function mediaWidth(feature, value) {
4619
- return value ? {
4620
- atRule: {
4621
- name: 'media',
4622
- params: "(".concat(feature, ": ").concat(value, ")")
4874
+
4875
+ /**
4876
+ * Resolves CSS nesting into plain rules, keeping the cascade: a rule's declarations stay
4877
+ * together until a nested rule interrupts them, and the ones after it follow it. Grouping
4878
+ * at-rules nested in a rule wrap a rule on the parent's selector.
4879
+ */
4880
+ function flattenNesting(nodes) {
4881
+ var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
4882
+ var out = [];
4883
+ var _iterator7 = _createForOfIteratorHelper(nodes),
4884
+ _step7;
4885
+ try {
4886
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
4887
+ var node = _step7.value;
4888
+ if (node.kind === 'rule') {
4889
+ var selector = parent === null ? node.selector : resolveNested(node.selector, parent);
4890
+ out.push.apply(out, _toConsumableArray(flattenRule(selector, node.nodes, node.loc)));
4891
+ } else if (node.kind === 'at-rule' && GROUPING.has(node.name)) {
4892
+ out.push(_objectSpread2(_objectSpread2({}, node), {}, {
4893
+ nodes: parent === null ? flattenNesting(node.nodes) : flattenRule(parent, node.nodes, node.loc)
4894
+ }));
4895
+ } else {
4896
+ out.push(node);
4897
+ }
4623
4898
  }
4624
- } : null;
4899
+ } catch (err) {
4900
+ _iterator7.e(err);
4901
+ } finally {
4902
+ _iterator7.f();
4903
+ }
4904
+ return out;
4625
4905
  }
4626
- var PSEUDO = {
4627
- hover: '&:hover',
4628
- focus: '&:focus',
4629
- 'focus-within': '&:focus-within',
4630
- 'focus-visible': '&:focus-visible',
4631
- active: '&:active',
4632
- visited: '&:visited',
4633
- target: '&:target',
4634
- disabled: '&:disabled',
4635
- enabled: '&:enabled',
4636
- checked: '&:checked',
4637
- indeterminate: '&:indeterminate',
4638
- "default": '&:default',
4639
- required: '&:required',
4640
- valid: '&:valid',
4641
- invalid: '&:invalid',
4642
- 'read-only': '&:read-only',
4643
- 'placeholder-shown': '&:placeholder-shown',
4644
- autofill: '&:autofill',
4645
- empty: '&:empty',
4646
- first: '&:first-child',
4647
- last: '&:last-child',
4648
- only: '&:only-child',
4649
- odd: '&:nth-child(odd)',
4650
- even: '&:nth-child(even)',
4651
- 'first-of-type': '&:first-of-type',
4652
- 'last-of-type': '&:last-of-type'
4653
- };
4654
- var PSEUDO_ELEMENT = {
4655
- before: '&::before',
4656
- after: '&::after',
4657
- placeholder: '&::placeholder',
4658
- selection: '&::selection',
4659
- marker: '&::marker',
4660
- file: '&::file-selector-button',
4661
- backdrop: '&::backdrop',
4662
- 'first-line': '&::first-line',
4663
- 'first-letter': '&::first-letter'
4664
- };
4665
- var MEDIA = {
4666
- dark: '(prefers-color-scheme: dark)',
4667
- 'motion-reduce': '(prefers-reduced-motion: reduce)',
4668
- 'motion-safe': '(prefers-reduced-motion: no-preference)',
4669
- 'contrast-more': '(prefers-contrast: more)',
4670
- 'contrast-less': '(prefers-contrast: less)',
4671
- portrait: '(orientation: portrait)',
4672
- landscape: '(orientation: landscape)',
4673
- print: 'print'
4674
- };
4675
- function named(v) {
4676
- return v ? v.value : null;
4906
+ function flattenRule(selector, children, loc) {
4907
+ var out = [];
4908
+ var pending = [];
4909
+ var flush = function flush() {
4910
+ if (pending.length) out.push(rule(selector, pending, loc));
4911
+ pending = [];
4912
+ };
4913
+ var _iterator8 = _createForOfIteratorHelper(children),
4914
+ _step8;
4915
+ try {
4916
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
4917
+ var child = _step8.value;
4918
+ if (child.kind === 'declaration' || child.kind === 'raw') {
4919
+ pending.push(child);
4920
+ } else if (child.kind === 'rule') {
4921
+ flush();
4922
+ out.push.apply(out, _toConsumableArray(flattenRule(resolveNested(child.selector, selector), child.nodes, child.loc)));
4923
+ } else if (GROUPING.has(child.name)) {
4924
+ flush();
4925
+ out.push(_objectSpread2(_objectSpread2({}, child), {}, {
4926
+ nodes: flattenRule(selector, child.nodes, child.loc)
4927
+ }));
4928
+ } else {
4929
+ flush();
4930
+ out.push(child);
4931
+ }
4932
+ }
4933
+ } catch (err) {
4934
+ _iterator8.e(err);
4935
+ } finally {
4936
+ _iterator8.f();
4937
+ }
4938
+ flush();
4939
+ return out;
4677
4940
  }
4678
4941
 
4679
- // `group-hover` → `.group:hover &`; `group-[.foo]` → `.group.foo &`. A named value
4680
- // is a pseudo-class, an arbitrary one is a raw selector fragment. A `/name`
4681
- // modifier scopes to a named group/peer (`group-hover/item` → `.group\/item:hover`).
4682
- function relational(v, m, base, tail) {
4683
- var value = named(v);
4684
- if (!value) return null;
4685
- var cond = v.kind === 'arbitrary' ? value : ":".concat(value);
4686
- var scope = m ? "".concat(base, "\\/").concat(m.value) : base;
4942
+ // ─── The shared context ──────────────────────────────────────────────────────
4943
+
4944
+ /**
4945
+ * What every stylesheet of one project shares: the registry (theme, utilities, variants,
4946
+ * custom definitions) and the theme tokens the processed CSS refers to, so the global sheet
4947
+ * keeps them however they are reached. One per build, made by whoever orchestrates it.
4948
+ */
4949
+
4950
+ function createCssContext() {
4951
+ var _options$registry;
4952
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4953
+ var registry = (_options$registry = options.registry) !== null && _options$registry !== void 0 ? _options$registry : createRegistry();
4954
+ if (options.theme) {
4955
+ loadTheme(options.theme, registry.theme);
4956
+ registerBreakpointVariants(registry);
4957
+ loadDirectives(options.theme, registry);
4958
+ }
4687
4959
  return {
4688
- selector: "".concat(scope).concat(cond).concat(tail)
4960
+ registry: registry,
4961
+ usedTokens: new Set()
4689
4962
  };
4690
4963
  }
4691
4964
 
4692
- // `not-hover` → `&:not(:hover)`, `not-first` → `&:not(:first-child)`: resolve the
4693
- // inner variant's pseudo, so the selector is valid (not the literal name). Only
4694
- // simple pseudo variants compose; `not-[…]` takes an arbitrary selector.
4695
- function notVariant(reg, v) {
4696
- var _reg$getVariant;
4697
- var value = named(v);
4698
- if (!value) return null;
4699
- if (v.kind === 'arbitrary') return {
4700
- selector: "&:not(".concat(value, ")")
4965
+ // Directives that define the context; component CSS does not get to change it.
4966
+ var CONTEXT_DIRECTIVES = new Set(['theme', 'utility', 'custom-variant', 'source', 'fluixi']);
4967
+ /**
4968
+ * Processes one stylesheet in a shared context, exactly as the project's own CSS would be:
4969
+ * `@apply` expanded with the context's utilities, theme values resolved, nesting flattened.
4970
+ * It never emits the utility layer or the theme tokens; the tokens it refers to are recorded
4971
+ * in `ctx.usedTokens` for the global sheet to keep.
4972
+ */
4973
+ function processCss(input, ctx) {
4974
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
4975
+ var parsed = typeof input === 'string' ? parseStyle(input, options.from) : input;
4976
+ var ignored = [];
4977
+ var references = [];
4978
+ var kept = parsed.filter(function (n) {
4979
+ var reference = n.kind === 'raw' ? n.text.match(/^@reference\s+(["'])(.+)\1\s*;$/) : null;
4980
+ if (reference) {
4981
+ references.push(reference[2]);
4982
+ return false;
4983
+ }
4984
+ if (n.kind === 'at-rule' && CONTEXT_DIRECTIVES.has(n.name)) {
4985
+ ignored.push(n.name);
4986
+ return false;
4987
+ }
4988
+ return true;
4989
+ });
4990
+ var applied = new Set();
4991
+ var ast = applyUtilities(kept, ctx.registry, applied);
4992
+ if (options.flatten !== false) ast = flattenNesting(ast);
4993
+ collectVarRefs(ast, ctx.usedTokens);
4994
+ return {
4995
+ ast: ast,
4996
+ css: stringify(ast, {
4997
+ minify: options.minify
4998
+ }),
4999
+ applied: _toConsumableArray(applied),
5000
+ ignored: ignored,
5001
+ references: references
4701
5002
  };
4702
- var frag = (_reg$getVariant = reg.getVariant(value)) === null || _reg$getVariant === void 0 || (_reg$getVariant = _reg$getVariant.selector) === null || _reg$getVariant === void 0 ? void 0 : _reg$getVariant.replace(/^&/, '').trim();
4703
- return frag && frag.startsWith(':') ? {
4704
- selector: "&:not(".concat(frag, ")")
4705
- } : null;
4706
5003
  }
4707
5004
 
4708
- // The batteries-included registry: the default token theme plus the utility
4709
- // families and variants. Projects extend it (`@utility`, `@theme`, JS config) or
4710
- // build a bare `new Registry(theme)` and register their own.
4711
- function createRegistry() {
4712
- var reg = new Registry(defaultTheme());
4713
- registerUtilities(reg);
4714
- registerVariants(reg);
4715
- return reg;
5005
+ // `@apply a b c;` in author CSS that `transform` passes through: the slice is parsed, the
5006
+ // `@apply` at-rules are expanded on the AST (`style.ts`), and the result is printed again.
5007
+ // A slice without `@apply` is returned as written.
5008
+ function expandApply(css, reg) {
5009
+ if (!css.includes('@apply')) return css;
5010
+ return stringify(applyUtilities(parseStyle(css), reg)).trimEnd();
5011
+ }
5012
+
5013
+ // Renders a `transform()` result as a compact, colourised build line for the
5014
+ // Vite/PostCSS plugins to print. Pure (returns a string) so css-core stays
5015
+ // side-effect free — the plugins own the actual `console.log`.
5016
+
5017
+ var ANSI = {
5018
+ reset: '\x1b[0m',
5019
+ dim: '\x1b[2m',
5020
+ bold: '\x1b[1m',
5021
+ cyan: '\x1b[36m',
5022
+ green: '\x1b[32m',
5023
+ yellow: '\x1b[33m',
5024
+ red: '\x1b[31m'
5025
+ };
5026
+ function paint(code, s, color) {
5027
+ return color ? code + s + ANSI.reset : s;
5028
+ }
5029
+ function humanBytes(n) {
5030
+ return n < 1024 ? "".concat(n, " B") : "".concat((n / 1024).toFixed(1), " kB");
5031
+ }
5032
+ function humanMs(ms) {
5033
+ return ms < 1 ? "".concat(ms * 1000 | 0, " \xB5s") : ms < 1000 ? "".concat(ms.toFixed(1), " ms") : "".concat((ms / 1000).toFixed(2), " s");
5034
+ }
5035
+
5036
+ // Green under 10 ms, yellow under 50 ms, red beyond — a quick "is it fast?" cue.
5037
+ function timeColor(ms) {
5038
+ return ms < 10 ? ANSI.green : ms < 50 ? ANSI.yellow : ANSI.red;
5039
+ }
5040
+ function formatBuildLog(label, stats) {
5041
+ var _options$color;
5042
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5043
+ var color = (_options$color = options.color) !== null && _options$color !== void 0 ? _options$color : true;
5044
+ var head = paint(ANSI.cyan + ANSI.bold, '◆ fluixi', color);
5045
+ var name = paint(ANSI.bold, label, color);
5046
+ var time = paint(timeColor(stats.ms), humanMs(stats.ms), color);
5047
+ var parts = ["".concat(stats.utilities, " ").concat(stats.utilities === 1 ? 'utility' : 'utilities'), "".concat(stats.scanned, " scanned"), humanBytes(stats.bytes)];
5048
+ if (stats.sources) parts.push("".concat(stats.sources, " ").concat(stats.sources === 1 ? 'source' : 'sources'));
5049
+ var detail = paint(ANSI.dim, parts.join(' · '), color);
5050
+ return "".concat(head, " ").concat(name, " ").concat(time, "\n ").concat(detail);
4716
5051
  }
4717
5052
 
4718
5053
  // Pulls atom class strings out of arbitrary source (HTML, JSX, template
@@ -4910,6 +5245,9 @@ function scanSourceFiles(files) {
4910
5245
  return _toConsumableArray(found);
4911
5246
  }
4912
5247
 
5248
+ /** The cascade layer the bridge is emitted in: fluixi-ui's tokens layer, below its skins. */
5249
+ var UI_TOKENS_LAYER = 'flx.tokens';
5250
+
4913
5251
  // Bridges a fluixi-css theme to the `--flx-ui-*` custom properties the Fluixi UI
4914
5252
  // components read (`@fluixi-ui/tokens`). Each bridge emits `--flx-ui-x: var(--src)`
4915
5253
  // so a fluixi-css theme *drives* the UI — change the theme, the components follow —
@@ -5225,12 +5563,18 @@ function transform(input) {
5225
5563
  var used = collectVarRefs(rules);
5226
5564
  if (uiBlocks) collectVarRefs(uiBlocks, used);
5227
5565
  collectVarRefs(authorNodes, used); // keep tokens the author CSS references by hand / via @apply
5228
- var tokens = emitTheme(reg.theme, ':root', used);
5566
+ var tokens = emitTheme(reg.theme, ':root', options.keepAllTokens ? undefined : used);
5229
5567
  if (tokens.nodes.length) generated.push(tokens);
5230
5568
  }
5231
- if (uiBlocks) generated.push.apply(generated, _toConsumableArray(uiBlocks.filter(function (b) {
5232
- return b.nodes.length;
5233
- })));
5569
+ // In the tokens layer, where fluixi-ui's own defaults live: later in the cascade than those, so
5570
+ // the theme still drives them, and below `flx.skin`, so a skin's tokens win. Unlayered, the
5571
+ // bridge beat every layer and a skin's radii, sizes and shadows never applied.
5572
+ if (uiBlocks) {
5573
+ var blocks = uiBlocks.filter(function (b) {
5574
+ return b.nodes.length;
5575
+ });
5576
+ if (blocks.length) generated.push(atRule('layer', UI_TOKENS_LAYER, blocks));
5577
+ }
5234
5578
  generated.push.apply(generated, rules);
5235
5579
  var nodes = markerAt >= 0 ? [].concat(_toConsumableArray(authorNodes.slice(0, markerAt)), generated, _toConsumableArray(authorNodes.slice(markerAt))) : [].concat(authorNodes, generated);
5236
5580
  var resetFrom = (_options$resetFrom = options.resetFrom) !== null && _options$resetFrom !== void 0 ? _options$resetFrom : 'fluixi:reset.css';
@@ -5398,9 +5742,15 @@ function compile(input) {
5398
5742
  var tokens = emitTheme(reg.theme, ':root', used);
5399
5743
  if (tokens.nodes.length) nodes.push(tokens);
5400
5744
  }
5401
- if (uiBlocks) nodes.push.apply(nodes, _toConsumableArray(uiBlocks.filter(function (b) {
5402
- return b.nodes.length;
5403
- })));
5745
+ // In the tokens layer, where fluixi-ui's own defaults live: later in the cascade than those, so
5746
+ // the theme still drives them, and below `flx.skin`, so a skin's tokens win. Unlayered, the
5747
+ // bridge beat every layer and a skin's radii, sizes and shadows never applied.
5748
+ if (uiBlocks) {
5749
+ var blocks = uiBlocks.filter(function (b) {
5750
+ return b.nodes.length;
5751
+ });
5752
+ if (blocks.length) nodes.push(atRule('layer', UI_TOKENS_LAYER, blocks));
5753
+ }
5404
5754
  nodes.push.apply(nodes, rules);
5405
5755
  return {
5406
5756
  css: stringify(nodes, {
@@ -5415,12 +5765,15 @@ function compile(input) {
5415
5765
  exports.Registry = Registry;
5416
5766
  exports.SPECIAL_COLORS = SPECIAL_COLORS;
5417
5767
  exports.Theme = Theme;
5768
+ exports.UI_TOKENS_LAYER = UI_TOKENS_LAYER;
5769
+ exports.applyUtilities = applyUtilities;
5418
5770
  exports.atRule = atRule;
5419
5771
  exports.collectVarRefs = collectVarRefs;
5420
5772
  exports.colorValue = colorValue;
5421
5773
  exports.compile = compile;
5422
5774
  exports.compileAtom = compileAtom;
5423
5775
  exports.compileClasses = compileClasses;
5776
+ exports.createCssContext = createCssContext;
5424
5777
  exports.createRegistry = createRegistry;
5425
5778
  exports.decl = decl;
5426
5779
  exports.decodeUnderscores = decodeUnderscores;
@@ -5429,24 +5782,29 @@ exports.emitTheme = emitTheme;
5429
5782
  exports.emitUiTheme = emitUiTheme;
5430
5783
  exports.escapeClass = escapeClass;
5431
5784
  exports.expandApply = expandApply;
5785
+ exports.flattenNesting = flattenNesting;
5432
5786
  exports.formatBuildLog = formatBuildLog;
5433
5787
  exports.keywords = keywords;
5434
5788
  exports.loadDirectives = loadDirectives;
5435
5789
  exports.loadTheme = loadTheme;
5436
5790
  exports.parseAtom = parseAtom;
5437
5791
  exports.parseSources = parseSources;
5792
+ exports.parseStyle = parseStyle;
5438
5793
  exports.parseVariant = parseVariant;
5794
+ exports.processCss = processCss;
5439
5795
  exports.props = props;
5440
5796
  exports.raw = raw;
5441
5797
  exports.registerBreakpointVariants = registerBreakpointVariants;
5442
5798
  exports.registerUtilities = registerUtilities;
5443
5799
  exports.registerVariants = registerVariants;
5800
+ exports.resolveNested = resolveNested;
5444
5801
  exports.resolveSourceFiles = resolveSourceFiles;
5445
5802
  exports.rule = rule;
5446
5803
  exports.scanAtoms = scanAtoms;
5447
5804
  exports.scanSourceFiles = scanSourceFiles;
5448
5805
  exports.sizeValue = sizeValue;
5449
5806
  exports.splitAtTopLevel = splitAtTopLevel;
5807
+ exports.splitSelectorList = splitSelectorList;
5450
5808
  exports.statics = statics;
5451
5809
  exports.stringify = stringify;
5452
5810
  exports.stringifyWithMap = stringifyWithMap;