Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 | 5x 16x 76x 14x 16x 11x 9x 8x 8x 7x 16x 16x 64x 64x 59x 59x 59x 59x 59x 59x 64x 40x 43x 40x 69x 69x 69x 69x 69x 69x 89x 69x 69x 69x 69x 69x 8x 8x 15x 8x 8x 11x 4x 11x 2x 2x 32x 32x 31x 23x 19x 19x 19x 11x 11x 19x 32x 32x 5x 52x 30x 30x 30x 30x 30x 30x 30x 30x 30x 48x 50x 32x 18x 7x 7x 1x 6x 64x 64x 59x 63x 35x 35x 35x 35x 35x 64x 11x 11x 11x 11x 11x 1x 1x 1x 1x 32x 32x 32x 18x 18x 11x 5x 3x 1x 7x 7x 5x 5x 5x 5x 5x 7x 20x 20x 20x 7x 7x 5x 5x 20x 11x 11x 3x 15x 15x 15x 15x 15x 3x 12x 4x 15x 2x 15x 15x 1x 20x 20x 20x 20x 22x 7x 20x 21x 20x 5x 5x 5x 20x 5x 5x 2x 3x 2x 1x 20x 7x 2x 2x 20x 20x 20x 20x 20x 20x 20x 20x 15x 64x 19x 19x 9x 9x 9x 9x 1x 1x 9x 8x 8x 8x 8x 8x 8x 32x 9x 9x 1x 1x 1x 9x 9x 32x 9x 8x 8x 2x 2x 2x 2x 9x 9x 6x 6x 5x 5x 2x 1x 1x 5x 32x 9x 6x 6x 2x 2x 9x 9x 32x 32x 32x 32x 32x 32x 32x 32x 32x 9x 4x 6x 6x 2x 2x 2x 2x 32x 32x 10x 10x 6x 6x 32x 34x 5x 32x 29x 29x 32x 29x 32x 64x 64x 59x 2x 2x 2x 2x 2x 64x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 31x 23x 23x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x 32x 17x 9x 32x 32x 32x 47x 47x 47x 47x 32x 33x 33x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 20x 32x 32x 32x 32x 32x 32x 6x 6x 10x 6x | /**
* Static regression-risk diff between a component's legacy CSS (`<name>.css`)
* and the effective new CSS (`themes/base.css` + tracked theme assignments).
*
* The entry point is {@link diff}. It returns a flag array in a stable
* (but not topologically sorted) order so tests can snapshot. Every
* heuristic pairing sets `needsReview: true` and drops to `info` severity;
* only deterministic rules produce `breaking` / `warning`.
*/
import { selectorKey, maxSpecificity, compareSpecificity, splitSelectorList } from './extract.js';
import { canonicalizeRule5Selector } from '../checks/helpers/selectorRole.js';
import { classifyPair } from './propertyPairs.js';
import {
hooksAssignedByAnyTheme,
hooksAssignedByAllThemes,
hooksReadByLegacy,
hooksReadByBase,
} from './models.js';
import type {
DeclModel,
DiffContext,
EffectiveNewModel,
Flag,
FlagSide,
FlagSummary,
LegacyModel,
MotionSignals,
Severity,
} from './types.js';
const STATE_SUFFIXES = ['-focus-visible', '-focus', '-hover', '-active', '-disabled'] as const;
/** Entry in the per-selector index. */
interface IndexedSelector {
selector: string;
decls: DeclModel[];
}
/** Entry in the theme-selector index (for `selector-moved-to-theme`). */
interface ThemeSelectorEntry {
key: string;
selector: string;
tokens: Set<string>;
themes: string[];
}
/** Return `{core, state}` for a component hook so rename matching can compare state-free forms. */
function splitStateSuffix(hook: string): { core: string; state: string } {
for (const s of STATE_SUFFIXES) {
if (hook.endsWith(s)) return { core: hook.slice(0, -s.length), state: s };
}
return { core: hook, state: '' };
}
/**
* Rewrite legacy `-text-color` / `-bg-color` / `-background-color` /
* `-border-color` suffixes into the canonical `color-{foreground|background|border}` form.
*/
function canonicalizeHookCore(core: string): string {
if (core.endsWith('-text-color')) return core.slice(0, -'-text-color'.length) + '-color-foreground';
if (core.endsWith('-bg-color')) return core.slice(0, -'-bg-color'.length) + '-color-background';
if (core.endsWith('-background-color'))
return core.slice(0, -'-background-color'.length) + '-color-background';
if (core.endsWith('-border-color')) return core.slice(0, -'-border-color'.length) + '-color-border';
return core;
}
/** Canonical rename candidate for a legacy hook. Equal to input when no rename applies. */
export function canonicalHookForm(hook: string): string {
const { core, state } = splitStateSuffix(hook);
return canonicalizeHookCore(core) + state;
}
/** Index `declsBySelector` by normalized selector key. */
function indexBySelectorKey(declsBySelector: Map<string, DeclModel[]>): Map<string, IndexedSelector> {
const byKey = new Map<string, IndexedSelector>();
for (const [selector, decls] of declsBySelector.entries()) {
const key = selectorKey(selector);
let entry = byKey.get(key);
Eif (!entry) {
entry = { selector, decls: [] };
byKey.set(key, entry);
}
entry.decls.push(...decls);
}
return byKey;
}
/** Group a decl list by property name. Latest declaration wins (in-rule cascade). */
function bundleByProp(decls: DeclModel[]): Map<string, DeclModel> {
const byProp = new Map<string, DeclModel>();
for (const decl of decls) byProp.set(decl.prop, decl);
return byProp;
}
/** Extract class-like tokens from a selector for Jaccard similarity. */
function selectorTokenSet(selector: string): Set<string> {
const tokens = new Set<string>();
const classRe = /\.([a-zA-Z_][\w-]*)/g;
const idRe = /#([a-zA-Z_][\w-]*)/g;
const attrRe = /\[[^\]]+\]/g;
const pseudoRe = /::?([a-zA-Z-]+)/g;
const tagRe = /(?:^|[\s>+~(,])([a-zA-Z][\w-]*)(?![-\w])/g;
let m: RegExpExecArray | null;
while ((m = classRe.exec(selector))) tokens.add('.' + m[1]);
while ((m = idRe.exec(selector))) tokens.add('#' + m[1]);
while ((m = attrRe.exec(selector))) tokens.add(m[0]);
while ((m = pseudoRe.exec(selector))) tokens.add(':' + m[1]);
while ((m = tagRe.exec(selector))) tokens.add(m[1]);
return tokens;
}
function jaccard(a: Set<string>, b: Set<string>): number {
Iif (a.size === 0 && b.size === 0) return 1;
let shared = 0;
for (const t of a) if (b.has(t)) shared += 1;
const union = a.size + b.size - shared;
return union === 0 ? 0 : shared / union;
}
function shareAnyClassToken(a: Set<string>, b: Set<string>): boolean {
for (const t of a) if (t.startsWith('.') && b.has(t)) return true;
return false;
}
function isStrictSubset(sub: Set<string>, sup: Set<string>): boolean {
if (sub.size === 0 || sub.size >= sup.size) return false;
for (const t of sub) Iif (!sup.has(t)) return false;
return true;
}
/** Build the theme-selector index used for `selector-moved-to-theme` detection. */
function collectThemeSelectors(effective: EffectiveNewModel): {
byKey: Map<string, ThemeSelectorEntry>;
entries: ThemeSelectorEntry[];
} {
const byKey = new Map<string, ThemeSelectorEntry>();
for (const [themeName, themeBlock] of Object.entries(effective.themes ?? {})) {
if (!themeBlock?.assignmentsBySelector) continue;
for (const selector of Object.keys(themeBlock.assignmentsBySelector)) {
const key = selectorKey(selector);
let entry = byKey.get(key);
if (!entry) {
entry = {
key,
selector,
tokens: selectorTokenSet(selector),
themes: [],
};
byKey.set(key, entry);
}
entry.themes.push(themeName);
}
}
const entries = [...byKey.values()].map((v) => ({ ...v }));
return { byKey, entries };
}
/**
* Does a terminal fallback qualify as "customer-visible"? Literal values,
* `transparent`, `currentColor`, and `--slds-g-*` tier fallbacks do; shared
* (`--slds-s-*`) and component (`--slds-c-*`) tier tokens do not.
*/
const CUSTOMER_VISIBLE_TERMINAL = (t: string | null | undefined): boolean => {
if (t === null || t === undefined) return false;
const v = String(t).trim();
Iif (v === '') return false;
Iif (v === 'revert' || v === 'transparent' || v === 'currentcolor' || v === 'currentColor') return true;
Iif (v.startsWith('var(--slds-g-')) return true;
Iif (v.startsWith('var(--slds-s-')) return false;
Iif (v.startsWith('var(--slds-c-')) return false;
Iif (v.startsWith('var(')) return true;
return true;
};
function hasSharedTierIntermediary(varChain: string[]): boolean {
return varChain.some((t) => t.startsWith('--slds-s-'));
}
function makeFlag(id: string, severity: Severity, payload: Omit<Flag, 'id' | 'severity'>): Flag {
return { id, severity, ...payload };
}
/**
* Pull `{ source, line }` off a {@link DeclModel} so a {@link FlagSide}
* can cite where the offending declaration was authored.
*/
function declLocation(decl: DeclModel): { source: string | null; line: number | null } {
return { source: decl.source, line: decl.line };
}
/**
* (1) hook-renamed + hook-removed-from-public-api (both `info`).
* Acknowledged API changes — surfaced for migration-guide cross-reference.
*/
function emitHookApiChanges(flags: Flag[], legacyHooks: Set<string>, newHooks: Set<string>): void {
for (const legacyHook of legacyHooks) {
if (newHooks.has(legacyHook)) continue;
const canonical = canonicalHookForm(legacyHook);
if (canonical !== legacyHook && newHooks.has(canonical)) {
flags.push(
makeFlag('hook-renamed', 'info', {
legacy: { hook: legacyHook },
next: { hook: canonical },
detail: `\`${legacyHook}\` → \`${canonical}\` — confirm migration-guide entry exists.`,
}),
);
} else {
flags.push(
makeFlag('hook-removed-from-public-api', 'info', {
legacy: { hook: legacyHook },
detail: `\`${legacyHook}\` is read by legacy CSS but never read by the effective new CSS.`,
}),
);
}
}
}
/**
* Collect `{ hook -> { selector -> firstDeclModel } }` from a selector-key
* index. The first decl reading a given hook on a given selector is enough
* to thread a `file:line` citation through `hook-selector-moved` flags.
*/
function collectHookSites(byKey: Map<string, IndexedSelector>): Map<string, Map<string, DeclModel>> {
const sites = new Map<string, Map<string, DeclModel>>();
for (const { selector, decls } of byKey.values()) {
for (const decl of decls) {
for (const hook of decl.hooksRead) {
let bucket = sites.get(hook);
Eif (!bucket) {
bucket = new Map();
sites.set(hook, bucket);
}
Eif (!bucket.has(selector)) bucket.set(selector, decl);
}
}
}
return sites;
}
/**
* (2) hook-selector-moved (`breaking`).
* Same hook name, read under a different normalized selector.
*
* Rule 5 paired-form migrations (e.g. `.slds-X_mod` → `.slds-X.slds-X_mod`,
* or `.slds-X__el` → `.slds-X .slds-X__el`) are not regressions: the new CSS
* still reads the same hook against the same effective hook target, just in
* the canonical root-anchored shape. Canonicalize selector keys via
* {@link canonicalizeRule5Selector} during the move-detection pass so those
* shape migrations don't produce false `breaking` flags.
*/
/**
* For a single hook present in both sides, push a `hook-selector-moved`
* flag for every legacy selector that has no direct or canonicalized
* match on the new side. Extracted from {@link emitHookSelectorMoves}
* to keep that function's cognitive complexity bounded.
*/
function emitHookSelectorMovesForHook(
flags: Flag[],
hook: string,
legacySelectors: Map<string, DeclModel>,
newSelectors: Map<string, DeclModel>,
): void {
const newCanonicalIndex = new Map<string, string>();
for (const newSel of newSelectors.keys()) {
newCanonicalIndex.set(canonicalizeRule5Selector(newSel), newSel);
}
for (const [legacySel, legacyDecl] of legacySelectors.entries()) {
if (newSelectors.has(legacySel)) continue;
Iif (newCanonicalIndex.has(canonicalizeRule5Selector(legacySel))) continue;
const moved = [...newSelectors.keys()][0];
const newDecl = newSelectors.get(moved);
flags.push(
makeFlag('hook-selector-moved', 'breaking', {
selector: legacySel,
legacy: { hook, selector: legacySel, ...declLocation(legacyDecl) },
next: { hook, selector: moved, ...(newDecl ? declLocation(newDecl) : {}) },
detail: `Hook \`${hook}\` is read under \`${legacySel}\` in legacy but under \`${moved}\` in the new CSS. Customer overrides scoped to the old selector will no longer apply.`,
}),
);
}
}
function emitHookSelectorMoves(
flags: Flag[],
legacyByKey: Map<string, IndexedSelector>,
newByKey: Map<string, IndexedSelector>,
): void {
const legacyHookSites = collectHookSites(legacyByKey);
const newHookSites = collectHookSites(newByKey);
for (const [hook, legacySelectors] of legacyHookSites.entries()) {
const newSelectors = newHookSites.get(hook);
if (!newSelectors) continue;
emitHookSelectorMovesForHook(flags, hook, legacySelectors, newSelectors);
}
}
interface PairingResult {
legacyProp: string;
nextProp: string;
classification: ReturnType<typeof classifyPair>;
rank: number;
}
/**
* Pairing rank: lower = stronger match. `incompatible` is the firm
* "definitely not the same property" signal so it pins a swap immediately;
* `equivalent` is the next-best deterministic match; everything else falls
* to the soft tier where we only commit if it's the only candidate.
*/
function rankFor(kind: ReturnType<typeof classifyPair>['kind']): number {
if (kind === 'incompatible') return 0;
if (kind === 'equivalent') return 1;
return 2;
}
/**
* Find the strongest candidate `nextProp` for `legacyProp` among
* `candidates`. Stops early on rank 0 (incompatible — the firmest match).
*/
function bestPairingFor(legacyProp: string, candidates: Iterable<string>): PairingResult | null {
let best: PairingResult | null = null;
for (const nextProp of candidates) {
const classification = classifyPair(legacyProp, nextProp);
const rank = rankFor(classification.kind);
Eif (best === null || rank < best.rank) {
best = { legacyProp, nextProp, classification, rank };
if (rank === 0) break;
}
}
return best;
}
/** Pair removed/added property sets using `classifyPair`. Greedy — each property pairs at most once. */
function pairPropSwaps(removedProps: string[], addedProps: string[]): PairingResult[] {
const remaining = new Set(addedProps);
const pairings: PairingResult[] = [];
for (const legacyProp of removedProps) {
const best = bestPairingFor(legacyProp, remaining);
// Only commit when classification is deterministic, or when there's a
// single-candidate swap (then record with needsReview).
if (best && (best.rank < 2 || remaining.size === 1)) {
pairings.push(best);
remaining.delete(best.nextProp);
}
}
return pairings;
}
function fallbackCoveredByThemes(legacyDecl: DeclModel, ctx: DiffContext): boolean {
for (const hook of legacyDecl.hooksRead) {
if (ctx.assignedByAll.has(hook)) return true;
}
return false;
}
function emitValueChanges(
flags: Flag[],
prop: string,
selector: string,
legacyDecl: DeclModel,
newDecl: DeclModel,
ctx: DiffContext,
): void {
const legacyTerminal = legacyDecl.terminalFallback;
const newTerminal = newDecl.terminalFallback;
const legacyHasShared = hasSharedTierIntermediary(legacyDecl.varChain);
const newHasShared = hasSharedTierIntermediary(newDecl.varChain);
// fallback-removed: legacy had a customer-visible terminal, new has none.
if (
CUSTOMER_VISIBLE_TERMINAL(legacyTerminal) &&
(newTerminal === null || newTerminal === undefined) &&
!fallbackCoveredByThemes(legacyDecl, ctx)
) {
flags.push(
makeFlag('fallback-removed', 'breaking', {
selector,
legacy: {
prop,
rawValue: legacyDecl.rawValue,
terminal: legacyTerminal,
hooks: legacyDecl.hooksRead,
...declLocation(legacyDecl),
},
next: { prop, rawValue: newDecl.rawValue, hooks: newDecl.hooksRead, ...declLocation(newDecl) },
detail: `Legacy chain ended in \`${legacyTerminal}\` — the effective-new chain has no terminal fallback.`,
}),
);
} else if (
CUSTOMER_VISIBLE_TERMINAL(legacyTerminal) &&
(newTerminal === null || newTerminal === undefined) &&
fallbackCoveredByThemes(legacyDecl, ctx)
) {
flags.push(
makeFlag('fallback-moved-to-theme', 'info', {
selector,
legacy: {
prop,
rawValue: legacyDecl.rawValue,
terminal: legacyTerminal,
...declLocation(legacyDecl),
},
next: { prop, rawValue: newDecl.rawValue, ...declLocation(newDecl) },
detail: `Inline fallback \`${legacyTerminal}\` is now provided by every tracked theme's assignment for \`${legacyDecl.hooksRead[0] ?? '(hook)'}\`.`,
}),
);
}
// cascade-shortened: legacy read an --slds-s-* intermediary, new doesn't.
if (legacyHasShared && !newHasShared) {
flags.push(
makeFlag('cascade-shortened', 'info', {
selector,
legacy: { prop, rawValue: legacyDecl.rawValue, ...declLocation(legacyDecl) },
next: { prop, rawValue: newDecl.rawValue, ...declLocation(newDecl) },
detail: `Legacy chain read an \`--slds-s-*\` intermediary that the new chain does not. Shared tier is consumption-only; informational only.`,
}),
);
}
// property-value-changed: same prop + selector, different terminal that isn't already covered by fallback-* flags.
const terminalsDiffer =
CUSTOMER_VISIBLE_TERMINAL(legacyTerminal) &&
CUSTOMER_VISIBLE_TERMINAL(newTerminal) &&
legacyTerminal !== newTerminal;
if (terminalsDiffer) {
flags.push(
makeFlag('property-value-changed', 'breaking', {
selector,
legacy: {
prop,
rawValue: legacyDecl.rawValue,
terminal: legacyTerminal,
...declLocation(legacyDecl),
},
next: { prop, rawValue: newDecl.rawValue, terminal: newTerminal, ...declLocation(newDecl) },
detail: `Terminal fallback changed from \`${legacyTerminal}\` to \`${newTerminal}\` for \`${prop}\`.`,
}),
);
}
}
function partitionProps(
legacyDecls: Map<string, DeclModel>,
newDecls: Map<string, DeclModel>,
): { removed: string[]; added: string[]; shared: string[] } {
const removed: string[] = [];
const added: string[] = [];
const shared: string[] = [];
for (const prop of legacyDecls.keys()) {
if (newDecls.has(prop)) shared.push(prop);
else removed.push(prop);
}
for (const prop of newDecls.keys()) {
if (!legacyDecls.has(prop)) added.push(prop);
}
return { removed, added, shared };
}
function buildPropertyReplacedPayload(
selector: string,
legacyProp: string,
nextProp: string,
legacyDecl: DeclModel | undefined,
nextDecl: DeclModel | undefined,
): { selector: string; legacy: FlagSide; next: FlagSide } {
const legacy: FlagSide = {
prop: legacyProp,
rawValue: legacyDecl?.rawValue,
hooks: legacyDecl?.hooksRead ?? [],
...(legacyDecl ? declLocation(legacyDecl) : {}),
};
const next: FlagSide = {
prop: nextProp,
rawValue: nextDecl?.rawValue,
hooks: nextDecl?.hooksRead ?? [],
...(nextDecl ? declLocation(nextDecl) : {}),
};
return { selector, legacy, next };
}
function emitPropertyReplaced(
flags: Flag[],
selector: string,
pairings: PairingResult[],
legacyDecls: Map<string, DeclModel>,
newDecls: Map<string, DeclModel>,
): void {
for (const { legacyProp, nextProp, classification } of pairings) {
const commonPayload = buildPropertyReplacedPayload(
selector,
legacyProp,
nextProp,
legacyDecls.get(legacyProp),
newDecls.get(nextProp),
);
if (classification.kind === 'incompatible') {
flags.push(
makeFlag('property-replaced', 'breaking', {
...commonPayload,
detail: `\`${legacyProp}\` removed, \`${nextProp}\` added on the same selector. ${classification.reason}`,
}),
);
} else if (classification.kind === 'equivalent') {
flags.push(
makeFlag('property-replaced', 'info', {
...commonPayload,
detail: `\`${legacyProp}\` → \`${nextProp}\`. ${classification.reason}`,
}),
);
} else {
flags.push(
makeFlag('property-replaced', 'info', {
...commonPayload,
needsReview: true,
detail: `\`${legacyProp}\` removed, \`${nextProp}\` added on the same selector. ${classification.reason}`,
}),
);
}
}
}
function emitPropertyRemovals(
flags: Flag[],
selector: string,
removedProps: string[],
pairedLegacy: Set<string>,
legacyDecls: Map<string, DeclModel>,
): void {
for (const prop of removedProps) {
if (pairedLegacy.has(prop)) continue;
const decl = legacyDecls.get(prop)!;
flags.push(
makeFlag('property-removed', 'breaking', {
selector,
legacy: { prop, rawValue: decl.rawValue, hooks: decl.hooksRead, ...declLocation(decl) },
detail: `\`${prop}\` was declared on \`${selector}\` in legacy but is not declared on the same selector in the new CSS.`,
}),
);
}
}
/**
* (3) Per-selector diffing — same normalized selector on both sides.
* Detects property-removed, property-replaced, fallback-*, cascade-shortened,
* and property-value-changed.
*/
function diffSelector(
flags: Flag[],
legacyEntry: IndexedSelector,
newEntry: IndexedSelector,
ctx: DiffContext,
): void {
const legacyDecls = bundleByProp(legacyEntry.decls);
const newDecls = bundleByProp(newEntry.decls);
const { removed, added, shared } = partitionProps(legacyDecls, newDecls);
const pairings = pairPropSwaps(removed, added);
emitPropertyReplaced(flags, legacyEntry.selector, pairings, legacyDecls, newDecls);
const pairedLegacy = new Set(pairings.map((p) => p.legacyProp));
emitPropertyRemovals(flags, legacyEntry.selector, removed, pairedLegacy, legacyDecls);
// Additive-only changes (`property-added`) are intentionally not flagged.
for (const prop of shared) {
emitValueChanges(flags, prop, legacyEntry.selector, legacyDecls.get(prop)!, newDecls.get(prop)!, ctx);
}
}
/**
* (4) Scope changes / selector-specificity-changed / selector-moved-to-theme / selector-removed.
*
* Additive-only changes (new selectors not in legacy) aren't flagged.
* Pass 1: strict subset pairing (legacy ⊂ new base) → `selector-scope-narrowed` (info).
* Pass 2: Jaccard pairing → `selector-specificity-changed` (info) when specs differ.
* Pass 3: legacy rule moved into a theme file → `selector-moved-to-theme` (info).
* Pass 4: remaining legacy-only → `selector-removed` (info).
*
* Note on severity: `selector-specificity-changed` and `selector-removed`
* used to be `warning`s framed around customer overrides scoped to the
* legacy selector. Under the current architecture customers customize via
* component hooks on the component root (Tier 3), and Rule 5 explicitly
* reshapes modifier/element specificity as a breaking-but-intentional
* SLDS-CSS-Interface change. Both flags now act as migration-completeness
* informational signals, not customer-override regressions.
*/
interface LegacyPair {
key: string;
selector: string;
tokens: Set<string>;
sampleDecl: DeclModel | undefined;
}
type NewPair = LegacyPair;
function buildPairs(keys: string[], byKey: Map<string, IndexedSelector>): LegacyPair[] {
return keys.map((k) => {
const entry = byKey.get(k)!;
return {
key: k,
selector: entry.selector,
tokens: selectorTokenSet(entry.selector),
sampleDecl: entry.decls[0],
};
});
}
function pickBestSubsetMatch(leg: LegacyPair, newPairs: NewPair[], usedNew: Set<string>): NewPair | null {
let best: { nw: NewPair; delta: number } | null = null;
for (const nw of newPairs) {
Iif (usedNew.has(nw.key)) continue;
if (!isStrictSubset(leg.tokens, nw.tokens)) continue;
const delta = nw.tokens.size - leg.tokens.size;
Eif (best === null || delta < best.delta) best = { nw, delta };
}
return best?.nw ?? null;
}
function pickBestJaccardMatch(leg: LegacyPair, newPairs: NewPair[], usedNew: Set<string>): NewPair | null {
let best: { nw: NewPair; score: number } | null = null;
for (const nw of newPairs) {
Iif (usedNew.has(nw.key)) continue;
const score = jaccard(leg.tokens, nw.tokens);
if (score > 0.5 && (best === null || score > best.score)) best = { nw, score };
}
return best?.nw ?? null;
}
function emitScopeNarrowings(
flags: Flag[],
legacyPairs: LegacyPair[],
newPairs: NewPair[],
usedNew: Set<string>,
pairedLegacy: Set<string>,
): void {
for (const leg of legacyPairs) {
const nw = pickBestSubsetMatch(leg, newPairs, usedNew);
if (!nw) continue;
const legSpec = maxSpecificity(leg.selector);
const newSpec = maxSpecificity(nw.selector);
flags.push(
makeFlag('selector-scope-narrowed', 'info', {
selector: leg.selector,
legacy: {
selector: leg.selector,
specificity: legSpec,
...(leg.sampleDecl ? declLocation(leg.sampleDecl) : {}),
},
next: {
selector: nw.selector,
specificity: newSpec,
...(nw.sampleDecl ? declLocation(nw.sampleDecl) : {}),
},
detail: `\`${leg.selector}\` was scoped inside additional context → \`${nw.selector}\`. Selector scope changes are expected — no behavior regression implied.`,
}),
);
usedNew.add(nw.key);
pairedLegacy.add(leg.key);
}
}
function emitSpecificityChanges(
flags: Flag[],
legacyPairs: LegacyPair[],
newPairs: NewPair[],
usedNew: Set<string>,
pairedLegacy: Set<string>,
): void {
for (const leg of legacyPairs) {
if (pairedLegacy.has(leg.key)) continue;
const nw = pickBestJaccardMatch(leg, newPairs, usedNew);
if (!nw) continue;
const legSpec = maxSpecificity(leg.selector);
const newSpec = maxSpecificity(nw.selector);
Iif (compareSpecificity(legSpec, newSpec) === 0) continue;
flags.push(
makeFlag('selector-specificity-changed', 'info', {
selector: leg.selector,
legacy: {
selector: leg.selector,
specificity: legSpec,
...(leg.sampleDecl ? declLocation(leg.sampleDecl) : {}),
},
next: {
selector: nw.selector,
specificity: newSpec,
...(nw.sampleDecl ? declLocation(nw.sampleDecl) : {}),
},
detail: `Selector reshape: \`${leg.selector}\` (specificity ${legSpec.join(',')}) → \`${nw.selector}\` (specificity ${newSpec.join(',')}). Customer overrides sized against the old specificity may now lose the cascade war.`,
}),
);
usedNew.add(nw.key);
pairedLegacy.add(leg.key);
}
}
function findThemeRelocation(
leg: LegacyPair,
themeSelectors: ReturnType<typeof collectThemeSelectors>,
): { entry: ThemeSelectorEntry; direction: 'exact' | 'scoped' } | null {
const exact = themeSelectors.byKey.get(leg.key);
if (exact) return { entry: exact, direction: 'exact' };
let bestScoped: { entry: ThemeSelectorEntry; delta: number } | null = null;
for (const entry of themeSelectors.entries) {
if (!isStrictSubset(leg.tokens, entry.tokens)) continue;
const delta = entry.tokens.size - leg.tokens.size;
Eif (bestScoped === null || delta < bestScoped.delta) bestScoped = { entry, delta };
}
return bestScoped ? { entry: bestScoped.entry, direction: 'scoped' } : null;
}
function emitThemeRelocations(
flags: Flag[],
legacyPairs: LegacyPair[],
pairedLegacy: Set<string>,
themeSelectors: ReturnType<typeof collectThemeSelectors>,
): void {
for (const leg of legacyPairs) {
if (pairedLegacy.has(leg.key)) continue;
const hit = findThemeRelocation(leg, themeSelectors);
if (!hit) continue;
const themeList = hit.entry.themes.join(', ');
const shapeNote =
hit.direction === 'scoped' ? ` (scoped under additional context as \`${hit.entry.selector}\`)` : '';
flags.push(
makeFlag('selector-moved-to-theme', 'info', {
selector: leg.selector,
legacy: { selector: leg.selector },
next: { selector: hit.entry.selector, themes: hit.entry.themes },
detail: `\`${leg.selector}\` was moved out of the component CSS into theme file${hit.entry.themes.length === 1 ? '' : 's'} (${themeList})${shapeNote}. Per-theme hook assignment is the intended layering — no regression.`,
}),
);
pairedLegacy.add(leg.key);
}
}
function emitSelectorShapeChanges(
flags: Flag[],
onlyLegacyKeys: string[],
onlyNewKeys: string[],
legacyByKey: Map<string, IndexedSelector>,
newByKey: Map<string, IndexedSelector>,
themeSelectors: ReturnType<typeof collectThemeSelectors>,
): void {
const legacyPairs = buildPairs(onlyLegacyKeys, legacyByKey);
const newPairs = buildPairs(onlyNewKeys, newByKey);
const usedNew = new Set<string>();
const pairedLegacy = new Set<string>();
emitScopeNarrowings(flags, legacyPairs, newPairs, usedNew, pairedLegacy);
emitSpecificityChanges(flags, legacyPairs, newPairs, usedNew, pairedLegacy);
emitThemeRelocations(flags, legacyPairs, pairedLegacy, themeSelectors);
emitSelectorRemovals(flags, legacyPairs, pairedLegacy);
}
function emitSelectorRemovals(flags: Flag[], legacyPairs: LegacyPair[], pairedLegacy: Set<string>): void {
for (const leg of legacyPairs) {
if (pairedLegacy.has(leg.key)) continue;
flags.push(
makeFlag('selector-removed', 'info', {
selector: leg.selector,
legacy: {
selector: leg.selector,
...(leg.sampleDecl ? declLocation(leg.sampleDecl) : {}),
},
detail: `\`${leg.selector}\` appears in legacy but not in the effective new CSS.`,
}),
);
}
}
/**
* Push a single cross-selector `property-replaced` flag if the
* (legSel, legacyProp, newSel, nextDecl) combination represents a real
* incompatible swap and hasn't already been reported.
*/
function tryEmitCrossSelectorReplacement(
flags: Flag[],
existingPairs: Set<string>,
legSel: string,
legacyProp: string,
legacyDecl: DeclModel,
newSel: string,
nextDecl: DeclModel,
): void {
const classification = classifyPair(legacyProp, nextDecl.prop);
if (classification.kind !== 'incompatible') return;
const key = `${legSel}|${legacyProp}|${nextDecl.prop}`;
Iif (existingPairs.has(key)) return;
existingPairs.add(key);
flags.push(
makeFlag('property-replaced', 'breaking', {
selector: legSel,
legacy: {
prop: legacyProp,
rawValue: legacyDecl.rawValue,
hooks: legacyDecl.hooksRead,
selector: legSel,
...declLocation(legacyDecl),
},
next: {
prop: nextDecl.prop,
rawValue: nextDecl.rawValue,
hooks: nextDecl.hooksRead,
selector: newSel,
...declLocation(nextDecl),
},
detail: `\`${legacyProp}\` on \`${legSel}\` replaced by \`${nextDecl.prop}\` on \`${newSel}\`. ${classification.reason}`,
}),
);
}
/**
* For one (legacyProp, legacyDecl) on one legacy selector, walk every
* "related" new selector (one that shares a class token) and try to emit
* a cross-selector `property-replaced` flag for each new declaration.
*/
function emitCrossSelectorReplacementsForLegacyProp(
flags: Flag[],
existingPairs: Set<string>,
legSel: string,
legTokens: Set<string>,
legacyProp: string,
legacyDecl: DeclModel,
newByKey: Map<string, IndexedSelector>,
): void {
for (const { selector: newSel, decls: newDecls } of newByKey.values()) {
if (selectorKey(newSel) === selectorKey(legSel)) continue;
const newTokens = selectorTokenSet(newSel);
if (!shareAnyClassToken(legTokens, newTokens)) continue;
for (const nextDecl of newDecls) {
tryEmitCrossSelectorReplacement(flags, existingPairs, legSel, legacyProp, legacyDecl, newSel, nextDecl);
}
}
}
/**
* (5) Cross-selector `property-replaced` — breadcrumbs case. When a property
* is removed from a legacy selector and a "related" new selector has an
* incompatibly-paired property, emit a breaking flag. Related = shares at
* least one class token.
*/
function emitCrossSelectorPropertyReplaced(
flags: Flag[],
legacyByKey: Map<string, IndexedSelector>,
newByKey: Map<string, IndexedSelector>,
): void {
const existingPairs = new Set(
flags
.filter((f) => f.id === 'property-replaced')
.map((f) => `${f.selector}|${f.legacy?.prop}|${f.next?.prop}`),
);
for (const { selector: legSel, decls: legDecls } of legacyByKey.values()) {
const legTokens = selectorTokenSet(legSel);
const legProps = new Map<string, DeclModel>();
for (const d of legDecls) legProps.set(d.prop, d);
for (const [legacyProp, legacyDecl] of legProps.entries()) {
emitCrossSelectorReplacementsForLegacyProp(
flags,
existingPairs,
legSel,
legTokens,
legacyProp,
legacyDecl,
newByKey,
);
}
}
}
/** Collect `content` declarations from pseudo-element rules in a selector-key index. */
function collectContentDecls(byKey: Map<string, IndexedSelector>): Map<string, DeclModel> {
const out = new Map<string, DeclModel>();
for (const { selector, decls } of byKey.values()) {
if (!/::before|::after/.test(selector)) continue;
for (const decl of decls) {
Iif (decl.prop !== 'content') continue;
for (const member of splitSelectorList(selector)) {
Iif (!/::before|::after/.test(member)) continue;
out.set(member, decl);
}
}
}
return out;
}
/**
* (6) pseudo-element-content-hookified (`warning`).
*/
function emitContentHookified(
flags: Flag[],
legacyByKey: Map<string, IndexedSelector>,
newByKey: Map<string, IndexedSelector>,
): void {
const legacyByPseudo = collectContentDecls(legacyByKey);
const newByPseudo = collectContentDecls(newByKey);
for (const [selector, legacyDecl] of legacyByPseudo.entries()) {
const newDecl = newByPseudo.get(selector);
Iif (!newDecl) continue;
const legacyValue = legacyDecl.rawValue;
const newValue = newDecl.rawValue;
Iif (!legacyValue.startsWith('"') && !legacyValue.startsWith("'") && !legacyValue.startsWith('url'))
continue;
Iif (!newValue.startsWith('var(')) continue;
flags.push(
makeFlag('pseudo-element-content-hookified', 'warning', {
selector,
legacy: { prop: 'content', rawValue: legacyValue, ...declLocation(legacyDecl) },
next: { prop: 'content', rawValue: newValue, ...declLocation(newDecl) },
detail: `Pseudo-element \`content\` on \`${selector}\` changed from a literal to a \`var()\` expression. A consumer rendering without a theme will lose the content.`,
}),
);
}
}
/**
* Sum motion signals across `themes/base.css` and every per-theme file.
*
* Kinetics rules (`[kx-*]`) and `@media (prefers-reduced-motion)` blocks
* are valid in any theme-layer file, including `themes/<theme>.css` —
* cascade layers nest media queries cleanly. Counting only base.css
* misreports a relocated-but-still-present kinetics block as removed.
*/
function aggregateNewMotion(effective: EffectiveNewModel): MotionSignals {
const total: MotionSignals = { reducedMotionBlocks: 0, kxRules: 0 };
const baseMotion = effective.base?.motion;
Eif (baseMotion) {
total.reducedMotionBlocks += baseMotion.reducedMotionBlocks;
total.kxRules += baseMotion.kxRules;
}
for (const themeBlock of Object.values(effective.themes ?? {})) {
if (!themeBlock?.motion) continue;
total.reducedMotionBlocks += themeBlock.motion.reducedMotionBlocks;
total.kxRules += themeBlock.motion.kxRules;
}
return total;
}
/**
* (7) kinetics-or-motion-removed (`warning`).
*/
function emitMotionRemoval(
flags: Flag[],
legacyMotion: { reducedMotionBlocks: number; kxRules: number } | undefined,
newMotion: { reducedMotionBlocks: number; kxRules: number } | undefined,
): void {
const legacyHad = (legacyMotion?.reducedMotionBlocks ?? 0) > 0 || (legacyMotion?.kxRules ?? 0) > 0;
const newHas = (newMotion?.reducedMotionBlocks ?? 0) > 0 || (newMotion?.kxRules ?? 0) > 0;
if (legacyHad && !newHas) {
const parts: string[] = [];
Eif ((legacyMotion?.reducedMotionBlocks ?? 0) > 0) {
const n = legacyMotion!.reducedMotionBlocks;
parts.push(`${n} \`prefers-reduced-motion\` block${n === 1 ? '' : 's'}`);
}
Eif ((legacyMotion?.kxRules ?? 0) > 0) {
const n = legacyMotion!.kxRules;
parts.push(`${n} \`[kx-*]\` rule${n === 1 ? '' : 's'}`);
}
flags.push(
makeFlag('kinetics-or-motion-removed', 'warning', {
detail: `Legacy CSS contained ${parts.join(' + ')}; none are present in the effective new CSS.`,
}),
);
}
}
/**
* (8) hook-opened-but-unassigned-in-all-themes (`info`).
*/
function emitOrphanApiHooks(flags: Flag[], newHooks: Set<string>, assignedByAny: Set<string>): void {
for (const hook of newHooks) {
if (assignedByAny.has(hook)) continue;
flags.push(
makeFlag('hook-opened-but-unassigned-in-all-themes', 'info', {
legacy: null,
next: { hook },
detail: `\`${hook}\` is read by the effective new CSS but no tracked theme assigns it.`,
}),
);
}
}
/** Deduplicate flags by `(id, selector, legacy.prop?hook, next.prop?hook)`. */
function dedupe(flags: Flag[]): Flag[] {
const seen = new Set<string>();
const out: Flag[] = [];
for (const f of flags) {
const key = [
f.id,
f.selector ?? '',
f.legacy?.prop ?? f.legacy?.hook ?? '',
f.next?.prop ?? f.next?.hook ?? '',
].join('\u0000');
Iif (seen.has(key)) continue;
seen.add(key);
out.push(f);
}
return out;
}
/**
* Run every detection stage and return the flag list. Pure — same inputs
* always produce the same output order.
*/
export function diff(legacy: LegacyModel | null, effective: EffectiveNewModel | null): Flag[] {
const flags: Flag[] = [];
if (!legacy) {
flags.push(
makeFlag('audit-incomplete', 'info', {
detail: 'Legacy CSS file is missing — nothing to diff against.',
}),
);
return flags;
}
Iif (!effective?.base) {
flags.push(
makeFlag('audit-incomplete', 'info', {
detail: 'Effective new CSS (themes/base.css) is missing — nothing to diff against.',
}),
);
return flags;
}
const legacyByKey = indexBySelectorKey(legacy.declsBySelector);
const newByKey = indexBySelectorKey(effective.base.declsBySelector);
const themeSelectors = collectThemeSelectors(effective);
const assignedByAny = hooksAssignedByAnyTheme(effective);
const assignedByAll = hooksAssignedByAllThemes(effective);
const ctx: DiffContext = { assignedByAny, assignedByAll };
const legacyHooks = hooksReadByLegacy(legacy);
const newHooks = hooksReadByBase(effective);
emitHookApiChanges(flags, legacyHooks, newHooks);
emitHookSelectorMoves(flags, legacyByKey, newByKey);
const legacyKeys = new Set(legacyByKey.keys());
const newKeys = new Set(newByKey.keys());
const sharedKeys = [...legacyKeys].filter((k) => newKeys.has(k));
const onlyLegacy = [...legacyKeys].filter((k) => !newKeys.has(k));
const onlyNew = [...newKeys].filter((k) => !legacyKeys.has(k));
for (const k of sharedKeys) {
diffSelector(flags, legacyByKey.get(k)!, newByKey.get(k)!, ctx);
}
emitSelectorShapeChanges(flags, onlyLegacy, onlyNew, legacyByKey, newByKey, themeSelectors);
emitCrossSelectorPropertyReplaced(flags, legacyByKey, newByKey);
emitContentHookified(flags, legacyByKey, newByKey);
emitMotionRemoval(flags, legacy.motion, aggregateNewMotion(effective));
emitOrphanApiHooks(flags, newHooks, assignedByAny);
return dedupe(flags);
}
/** Summary counts by severity for use in compliance rows. */
export function summarize(flags: Flag[]): FlagSummary {
const summary: FlagSummary = { breaking: 0, warning: 0, info: 0 };
for (const f of flags) {
summary[f.severity] += 1;
}
return summary;
}
|