Skip to content

Commit c78a80f

Browse files
committed
Configurator: Reuse runtime lookups during pruning
Observe successful class-map lookups by running individual candidates through the existing merge engine. Expose this build-time adapter through the unstable tooling entry point and remove the configurator’s duplicate modifier and postfix decision tree. Intermediate base matches remain available to pruning without adding instrumentation to normal merging. Add an independent coverage matrix over pairs and triples of simple longhand utilities, with signed/static slash utilities, preserved descendant roots, theme collisions, and order-sensitive variants. Verify both encodings, prefixes, importance, pruning, and emitted TypeScript and JavaScript without deriving expected outcomes from production coverage helpers. Exercise the lookup adapter through unit and built ESM/CJS export checks, and document the ownership boundaries. Validation: all 583 repository tests pass with coverage, along with lint, type checks, library and Vite builds, and both package export checks.
1 parent 7c45b73 commit c78a80f

9 files changed

Lines changed: 154 additions & 40 deletions

File tree

‎agents/configurator.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,14 +88,16 @@ Validators become local bindings so minifiers can rename them. Default sharing h
8888

8989
Serialize `__proto__` object keys with computed syntax (`['__proto__']`); an ordinary or quoted object-literal key sets the prototype instead of preserving a theme family. Keep key serialization shared by inline objects, hoisted structures, and record maps. Regression tests execute TS and JS modules under every sharing mode and both encodings, with and without pruning, and compare their config and merge behavior with the materialized result.
9090

91-
Pruning runs after custom utilities, augmentations, and collision correction. Mirror the library's modifier/postfix parsing, preserve trie precedence, and keep every validator reached by a used candidate. Retain every successful lookup step, including the base matcher that enables a slash-modified class to resolve into a different final group. Keeping only the final group can promote a broader validator that bypasses postfix lookup. Count each supplied candidate once in the pruning report even when it retains several groups. If member attribution cannot explain a classifier hit, retain the whole group and report it in `unprunedClassGroups`. Validators may retain more than the scanned names; this is intentional conservative behavior.
91+
Pruning runs after custom utilities, augmentations, and collision correction. Use the library's unstable `createClassGroupLookup` to observe each candidate through the real merge engine; do not recreate its modifier/postfix decision tree in the configurator. The tooling wrapper records successful lookups without changing the runtime hot path. Preserve trie precedence and keep every validator reached by a used candidate. Retain every successful lookup step, including the base matcher that enables a slash-modified class to resolve into a different final group. Keeping only the final group can promote a broader validator that bypasses postfix lookup. Count each supplied candidate once in the pruning report even when it retains several groups. If member attribution cannot explain a classifier hit, retain the whole group and report it in `unprunedClassGroups`. Validators may retain more than the scanned names; this is intentional conservative behavior.
9292

9393
Use oxide over Tailwind's source configuration, not Vite's module graph: raw template/Markdown files and external `@source` packages may never enter that graph, and client/server graphs differ. `compile()` supplies roots, source entries, features, and dependency callbacks. Inline candidates are private upstream, so `scan.ts` parses active CSS statements from the entrypoint and CSS dependencies and ports Tailwind's brace expansion, including negations. Preserve comment/string boundaries: a regex over raw CSS can make a commented exclusion remove a class Tailwind still emits. Scanner regressions check emitted Tailwind CSS and pruned merge behavior for both entrypoint and imported directives. Recreate the scanner when the CSS graph changes; reuse it for source-only edits. The direct API and CLI propagate scan errors; the Vite wrapper may fall back to the full config.
9494

9595
## Debugging and validation
9696

9797
The test paths and bare inspector command below are relative to `packages/configurator/`. Prefer new cases in existing fixtures before adding a whole new theme; expensive generation should be shared. The [real-world fixture README](../packages/configurator/tests/fixtures/real-world/README.md) is permanent provenance and refresh guidance, not disposable research material.
9898

99+
`effect-combinations.test.ts` checks pairs and triples of known independent longhands with expected coverage derived from the fixture's property sets, not production declaration/coverage helpers. It combines those cases with preserved custom roots, signed/static slash collisions, theme collisions, variants, and importance across both encodings, prefixes, pruning, and emitted TS/JS. Keep an independent expectation layer like this alongside the larger conformance oracle, since that oracle shares production helpers and can agree with the same bug.
100+
99101
- The configurator's correctness gates are helper assertions in `packages/configurator/tests/fixture-utils.ts` (`assertTailwindConformance`, `assertExactClassificationParity`, `assertPruningEquivalence`, and the table helper `expectMerges`); tests that only call them are whitelisted for `vitest/expect-expect` in the package's eslint config — extend that list when adding a gate. The conflict oracle behind the sweeps lives in `tests/oracle.ts` (`mergeVerdict`: directional, var()-composition-aware; see its doc comment before changing verdict rules) and is importable under plain Node, which `scripts/explain.mts` relies on.
100102
- `generateFixture` is memoized per CSS/base/options within a worker and runs every emitted module through a round trip (written to `tests/.tmp-roundtrip-*`, imported through Vitest, `getConfig()` deep-equal to the materialized config). Cost scales with the number of distinct fixtures (0.1–1 s each), not with assertions — add cases to existing fixtures first; a new theme only for a new theme shape. Use `expectMerges` for curated tables (every mismatch reported at once, input and output side by side) and `mergeTable` + `toMatchInlineSnapshot` for exploratory batches.
101103
- `tests/vanilla-coverage.test.ts` is a ratchet against Tailwind itself (unclassified classes, consecutive pairs, cross-group exemplar pairs) with file snapshots of known divergences under `tests/__snapshots__/vanilla-coverage/`. Those lists name tailwind-merge default-config gaps as much as configurator ones; a new line after a change is something to look at, a removed line is a fix — update the snapshot deliberately, never blindly with `-u`. Divergences the library keeps on purpose (grid `col-start`/`col-end` before `col-span` per tailwind-merge#176, `sr-only` as a toggle) go into the file's `INTENTIONAL_DIVERGENCES` allowlist with a reason instead of the snapshots; a companion test fails when an allowlisted pair stops diverging, so stale entries get removed. The oracle itself stays a pure statement about compiled CSS — never encode library policy in `mergeVerdict`.

‎agents/tailwind-merge-internals.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ Links from the library's `docs/` to repository-wide files must traverse three pa
3232
- alphabetically sorts non-sensitive modifiers,
3333
- preserves placement around arbitrary/order-sensitive modifiers.
3434

35+
The unstable tooling entry point also exports `createClassGroupLookup` from `src/lib/class-group-lookup.ts`. It runs one candidate through `mergeClassList` with an observing class-map function and returns every successful lookup, including a slash class's intermediate base. The configurator uses this to preserve lookup dependencies during pruning. Keep this instrumentation outside the normal merge path; it is an adapter for build-time inspection, not a second implementation of modifier or lookup semantics. Both built ESM/CJS export checks exercise it.
36+
3537
## Performance constraints in hot-path code
3638

3739
The hot paths are `src/lib/merge-classlist.ts` and `src/lib/class-group-utils.ts`; `src/lib/parse-class-name.ts` runs per class on cache misses. When editing these files, preserve the existing V8-oriented patterns:

‎packages/configurator/src/prune.ts‎

Lines changed: 8 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
import { validators } from 'tailwind-merge'
2-
import { createClassGroupUtils, createParseClassName } from 'tailwind-merge/unstable-do-not-import'
2+
import { createClassGroupLookup } from 'tailwind-merge/unstable-do-not-import'
33

44
import { materializeConfig } from './materialize.ts'
55
import { type ConfigPlan, type PlanValue, filterConflictMap } from './plan.ts'
66

77
/**
88
* Shrinks a plan to the class names a project actually uses: groups and members survive only when needed by a used class's lookup, including intermediate base matchers for slash-modified classes — literals a used class names, nested prefix objects a used class descends into, and validators a used class's remaining tail satisfies.
99
*
10-
* The pruned plan merges exactly like the full plan for every class list made of used classes, by construction: it is a subset of the full plan with tailwind-merge's lookup precedence intact. Classification of a used class runs through tailwind-merge's own parser and class map (prefix, variants, important marker, postfix modifiers — mirroring `mergeClassList`'s lookup order), so a class matched via a literal keeps that literal and a class matched via a validator keeps that validator, in the same group and at the same trie position; removing other members can never promote a previously losing candidate, because lookup tries deeper literal paths first and validators in definition order, and that order is preserved among the survivors. Members are only ever removed, never re-encoded, and validators are kept whenever any used tail satisfies them — over-keeping is always safe, under-keeping never is. Retained validators can also classify names outside the used set, so the result is not a strict allowlist. Only supplied candidates carry the equivalence guarantee; consumers with externally supplied, separately styled class names should keep the full config.
10+
* The pruned plan merges exactly like the full plan for every class list made of used classes, by construction: it is a subset of the full plan with tailwind-merge's lookup precedence intact. Classification of a used class records the lookups of tailwind-merge's own merge engine (prefix, variants, important marker, and postfix modifiers), so a class matched via a literal keeps that literal and a class matched via a validator keeps that validator, in the same group and at the same trie position; removing other members can never promote a previously losing candidate, because lookup tries deeper literal paths first and validators in definition order, and that order is preserved among the survivors. Members are only ever removed, never re-encoded, and validators are kept whenever any used tail satisfies them — over-keeping is always safe, under-keeping never is. Retained validators can also classify names outside the used set, so the result is not a strict allowlist. Only supplied candidates carry the equivalence guarantee; consumers with externally supplied, separately styled class names should keep the full config.
1111
*
1212
* Used classes are raw tokens as a scanner finds them (`hover:bg-red-500/50`, `tw:p-4!`, `-mt-2`), deduplicated here; anything that does not classify is ignored. Conflict maps are filtered to the kept groups, `scales` stay untouched (the emitter drops shared consts nothing references anymore), and the result records what happened in `report.pruning`. The input plan is not mutated.
1313
*/
1414
export function prunePlan(plan: ConfigPlan, usedClasses: Iterable<string>): ConfigPlan {
1515
const config = materializeConfig(plan)
16-
const parseClassName = createParseClassName(config)
17-
const { getClassGroupId } = createClassGroupUtils(config)
18-
const postfixLookupClassGroupIds = new Set(config.postfixLookupClassGroups ?? [])
16+
const lookupClass = createClassGroupLookup(config)
1917

2018
/** Every successful lookup needed by a used class, including a base group that enables a subsequent postfix lookup. Names contain only the part the class map matched, with a leading minus removed. */
2119
const matchedNamesByGroup = new Map<string, Set<string>>()
@@ -29,45 +27,19 @@ export function prunePlan(plan: ConfigPlan, usedClasses: Iterable<string>): Conf
2927
}
3028
seen.add(className)
3129

32-
if (classify(className)) {
30+
const matches = lookupClass(className)
31+
if (matches.length > 0) {
3332
classifiedClassCount += 1
3433
}
35-
}
36-
37-
/**
38-
* Mirrors the lookup in tailwind-merge's `mergeClassList`, retaining every successful step. A slash-modified class can finish in a different group, but its base matcher must still survive: removing it could promote a broader validator that never requests the full lookup. Counts each supplied class once regardless of how many lookups it needs.
39-
*/
40-
function classify(className: string): boolean {
41-
const { isExternal, baseClassName, maybePostfixModifierPosition } =
42-
parseClassName(className)
43-
if (isExternal) {
44-
return false
45-
}
46-
47-
if (maybePostfixModifierPosition) {
48-
const withoutPostfix = baseClassName.substring(0, maybePostfixModifierPosition)
49-
const classGroupId = trackLookup(withoutPostfix)
50-
if (classGroupId && !postfixLookupClassGroupIds.has(classGroupId)) {
51-
return true
52-
}
53-
return Boolean(trackLookup(baseClassName) || classGroupId)
54-
}
55-
56-
return Boolean(trackLookup(baseClassName))
57-
}
58-
59-
/** Records the exact name at each successful classifier step so member pruning preserves its trie precedence. */
60-
function trackLookup(className: string): string | undefined {
61-
const classGroupId = getClassGroupId(className)
62-
if (classGroupId) {
34+
for (const match of matches) {
35+
const { classGroupId } = match
6336
let names = matchedNamesByGroup.get(classGroupId)
6437
if (!names) {
6538
names = new Set()
6639
matchedNamesByGroup.set(classGroupId, names)
6740
}
68-
names.add(lookupName(className))
41+
names.add(lookupName(match.className))
6942
}
70-
return classGroupId
7143
}
7244

7345
const classGroups = new Map<string, PlanValue[]>()
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { describe, test } from 'vitest'
2+
3+
import { emitModule } from '../src/emit'
4+
5+
import { css, expectMerges, generateFixture, importEmittedModule } from './fixture-utils'
6+
7+
// These independent CSS longhands provide a small, explicit oracle: a later class can replace an earlier one only when it sets all of the earlier class's properties. Do not use production coverage helpers to derive the expected results.
8+
const properties = ['width', 'height', 'color']
9+
const utilities = Array.from({ length: 7 }, (_, index) => index + 1).flatMap((mask) =>
10+
['a', 'b'].map((value) => ({ name: `effect-${mask}-${value}`, mask, value })),
11+
)
12+
const rows = utilities.flatMap((first) => utilities.flatMap((second) => {
13+
const third = utilities[(first.mask + second.mask) % utilities.length]!
14+
return [[first, second], [first, second, third]].map((list): [string, string] => [
15+
list.map(({ name }) => name).join(' '),
16+
list.filter((item, index) => !list.slice(index + 1).some((later) =>
17+
(later.mask & item.mask) === item.mask,
18+
)).map(({ name }) => name).join(' '),
19+
])
20+
}))
21+
22+
describe.each(['compact', 'exact'] as const)('%s effect combinations', (encoding) => {
23+
test.each(['', 'tw'])('keeps coverage and lookup decisions across representations (prefix: %s)', async (prefix) => {
24+
const stylesheet = css`
25+
@import 'tailwindcss' ${prefix ? 'prefix(tw)' : ''};
26+
@custom-variant children (& > *);
27+
@theme { --color-x-13: red; }
28+
${utilities.map(({ name, mask, value }) => `@utility ${name} {
29+
${properties.flatMap((property, index) => mask & (1 << index)
30+
? [`${property}: ${property === 'color' ? (value === 'a' ? 'red' : 'blue') : (value === 'a' ? '1px' : '2px')};`]
31+
: []).join('\n')}
32+
}`).join('\n')}
33+
@utility thing-* { opacity: --value(number); }
34+
@utility thing-width-* {
35+
width: calc(--value(integer) * 1px);
36+
height: --modifier([length]);
37+
}
38+
@utility badge { padding: 1rem; }
39+
@utility badge/icon { color: red; }
40+
@utility pull { margin-left: 1rem; }
41+
@utility -pull { margin-right: -1rem; }
42+
`
43+
const preserved = [
44+
'thing-width-2/[3px] thing-0.5 effect-4-a',
45+
'thing-0.5 thing-width-2/[3px] effect-4-a',
46+
'badge/icon badge',
47+
'pull -pull',
48+
'-pull pull',
49+
'border-x-13 border-blue-500',
50+
'hover:children:effect-7-a children:hover:effect-7-b',
51+
'effect-7-a! effect-7-b',
52+
]
53+
const cases = [
54+
...rows.flatMap((row) => ['', 'hover:', '!'].map((modifier) => mapCase(row,
55+
(name) => modifier === '!' ? `${name}!` : `${modifier}${name}`,
56+
))),
57+
...preserved.map((input): [string, string] => [input, input]),
58+
].map((row) => mapCase(row, (name) => prefix ? `${prefix}:${name}` : name))
59+
const usedClasses = [...new Set(cases.flatMap(([input]) => input.split(' ')))]
60+
for (const prune of [undefined, { usedClasses }]) {
61+
const fixture = await generateFixture(stylesheet, undefined, { encoding, prune })
62+
expectMerges(fixture.twMerge, cases)
63+
for (const format of ['ts', 'js'] as const) {
64+
const emitted = await importEmittedModule(emitModule(fixture.plan, { format }), format)
65+
expectMerges(emitted.twMerge, cases)
66+
}
67+
}
68+
})
69+
})
70+
71+
/** Decorate both sides of an independently specified case without deriving its expected merge result from runtime behavior. */
72+
function mapCase([input, expected]: [string, string], decorate: (name: string) => string): [string, string] {
73+
const apply = (list: string) => list.split(' ').map(decorate).join(' ')
74+
return [apply(input), apply(expected)]
75+
}

‎packages/tailwind-merge/scripts/test-built-package-exports.cjs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@ const assert = require('assert')
22

33
const { getDefaultConfig, twMerge } = require('..')
44
const { twMerge: twMergeEs5 } = require('../dist/es5/bundle-cjs.js')
5-
const { createClassGroupUtils, createParseClassName } = require('../dist/unstable-cjs.js')
5+
const { createClassGroupUtils, createClassGroupLookup, createParseClassName } = require('../dist/unstable-cjs.js')
66

77
assertBuiltTwMerge(twMerge)
88
assertBuiltTwMerge(twMergeEs5)
99
assert(createClassGroupUtils(getDefaultConfig()).getClassGroupId('bg-red-500') === 'bg-color')
1010
assert(createParseClassName(getDefaultConfig())('hover:p-4').baseClassName === 'p-4')
11+
assert.deepStrictEqual(createClassGroupLookup(getDefaultConfig())('hover:p-4!'), [
12+
{ className: 'p-4', classGroupId: 'p' },
13+
])
1114

1215
console.log('[tailwind-merge] Tests for built CJS package exports and ES5 bundle passed.')
1316

‎packages/tailwind-merge/scripts/test-built-package-exports.mjs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@ import assert from 'assert'
33
// Not ideal, but there seems to be no way to point the import resolver to the package.json file if this isn't a npm package.
44
import { getDefaultConfig, twMerge } from '../dist/bundle-mjs.mjs'
55
import { twMerge as twMergeEs5 } from '../dist/es5/bundle-mjs.mjs'
6-
import { createClassGroupUtils, createParseClassName } from '../dist/unstable-mjs.mjs'
6+
import { createClassGroupUtils, createClassGroupLookup, createParseClassName } from '../dist/unstable-mjs.mjs'
77

88
assertBuiltTwMerge(twMerge)
99
assertBuiltTwMerge(twMergeEs5)
1010
assert(createClassGroupUtils(getDefaultConfig()).getClassGroupId('bg-red-500') === 'bg-color')
1111
assert(createParseClassName(getDefaultConfig())('hover:p-4').baseClassName === 'p-4')
12+
assert.deepStrictEqual(createClassGroupLookup(getDefaultConfig())('hover:p-4!'), [
13+
{ className: 'p-4', classGroupId: 'p' },
14+
])
1215

1316
console.log('[tailwind-merge] Tests for built ESM package exports and ES5 bundle passed.')
1417

0 commit comments

Comments
 (0)