Skip to content

Commit 7b565ca

Browse files
committed
Configurator: prune a generated config to a project's used classes (core step)
First implementation step of PROPOSAL §12 (usage-based pruning): the pure core. `generate()` accepts `prune: { usedClasses }`, a list of class names as a source scanner finds them, and returns a config that keeps only what those classes reach — the scanning side (Tailwind's sources through the oxide scanner, the `@source inline` safelist) and the Vite plugin/CLI wiring follow in the next steps. Nothing changes for callers that don't pass the option. How pruning works (prune.ts): every used class is classified with tailwind-merge's own machinery on the full materialized config — the class-name parser for prefix, variants, the important marker and postfix modifiers, the class map for the group — mirroring `mergeClassList`'s lookup order (postfix stripped first, `postfixLookupClassGroups` second chance, full name last), so the pruner knows not only the group but the exact string the class map matched. Groups no used class resolves into are dropped; inside the kept groups a walk over the plan's PlanValue trees keeps literals a matched name equals, descends into prefix objects the way the trie does (key stripped, the empty literal for "the prefix alone"), and keeps a validator whenever some matched tail satisfies it. Because the result is a subset of the full plan with lookup precedence intact (deeper literals first, validators in definition order, both preserved among survivors), a used class can never change its classification, and every class list made of used classes merges exactly like under the full config — the invariant the new tests check: curated cases, the decorated class-list samples (`sampleUsedClasses`: variants, both important spellings, postfix modifiers, arbitrary values, a negative value, an arbitrary property, scanner garbage) through `assertPruningEquivalence` on vanilla, a prefixed theme with custom utilities and sub-namespace classes, and all seven real-world fixtures. Classes outside the used set pass through unmerged — the behavior the design wants, since a class Tailwind never saw has no styles — except where a kept compact-mode validator still covers them (`rounded-md` keeps `isTshirtSize`, so `rounded-lg` stays classified); exact encoding enumerates and lets them pass, which the test pins alongside the compact behavior. Conflict maps filter to the kept groups, the emitter's shared-scale consts simply stop being referenced, and `report.pruning` records counts plus `unprunedClassGroups` — groups a used class reached through a path the walk could not attribute, kept whole as a safety net; it stays empty on every fixture. Supporting changes: tailwind-merge's unstable entry point additionally exports `createParseClassName` (with a test and the built-export smoke assertions), so sibling tooling parses class names exactly like the runtime instead of approximating the parser; `filterConflictMap` is exported from plan.ts; the emitter no longer emits a stray blank line when no shared const is referenced and writes empty conflict maps inline — both only visible on pruned output, the small pruned-vanilla snapshot documents the shape; README gains the option row. The configurator suite grows from 120 to 147 tests.
1 parent 82927c0 commit 7b565ca

15 files changed

Lines changed: 543 additions & 11 deletions

‎packages/configurator/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ Options:
7272
| `banner` | no | Extra comment lines below the generated-file notice, e.g. provenance info. |
7373
| `format` | no | `'ts'` (default) or `'js'` — the emitted module's language. |
7474
| `importSource` | no | Module specifier the emitted code imports tailwind-merge from. Defaults to `'tailwind-merge'`; override when you re-export tailwind-merge from somewhere else (the Vite plugin uses this). |
75+
| `prune` | no | `{ usedClasses }` — prunes the config to the listed class names (raw tokens as found in your sources, variants and modifiers included): class groups and scale members no listed class reaches are dropped, class lists made of listed classes merge exactly as with the full config, classes outside the list pass through unmerged. `plan.report.pruning` tells what happened. |
7576

7677
Results:
7778

‎packages/configurator/eslint.config.mjs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@ export default [
2626
rules: {
2727
'vitest/expect-expect': [
2828
'error',
29-
{ assertFunctionNames: ['expect', 'assertTailwindConformance'] },
29+
{
30+
assertFunctionNames: [
31+
'expect',
32+
'assertTailwindConformance',
33+
'assertPruningEquivalence',
34+
],
35+
},
3036
],
3137
},
3238
},

‎packages/configurator/src/emit.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export function emitModule(plan: ConfigPlan, options: EmitOptions = {}): string
3636
const usedCanonicals = resolveTransitiveUsage(candidates, firstPass)
3737
const finalNames = assignNames(candidates, usedCanonicals)
3838
const secondPass = serializeAll(plan, candidates, finalNames, format)
39-
const { configBody, constantBodies } = secondPass
39+
const { configBody } = secondPass
4040

4141
const lines: string[] = []
4242

@@ -79,14 +79,16 @@ export function emitModule(plan: ConfigPlan, options: EmitOptions = {}): string
7979
lines.push('')
8080
}
8181

82-
for (const [canonical, body] of sortByDependencies(secondPass, finalNames)) {
82+
const emittedConstants = sortByDependencies(secondPass, finalNames)
83+
for (const [canonical, body] of emittedConstants) {
8384
const comment = candidates.get(canonical)?.comment
8485
if (comment) {
8586
lines.push(`${INDENT}/** ${comment} */`)
8687
}
8788
lines.push(`${INDENT}const ${finalNames.get(canonical)} = ${body}`)
8889
}
89-
if (constantBodies.size > 0) {
90+
// Only the consts actually emitted earn the separating blank line — a pruned plan can leave every shared-scale candidate unreferenced.
91+
if (emittedConstants.length > 0) {
9092
lines.push('')
9193
}
9294

@@ -620,6 +622,11 @@ const canonicalArrayCache = new WeakMap<PlanValue[], string>()
620622
const canonicalObjectCache = new WeakMap<Extract<PlanValue, { kind: 'object' }>, string>()
621623

622624
function pushStringRecordMap(lines: string[], property: string, map: Map<string, string[]>) {
625+
if (map.size === 0) {
626+
// Possible after pruning leaves no conflict edges between the kept groups.
627+
lines.push(`${INDENT}${INDENT}${property}: {},`)
628+
return
629+
}
623630
lines.push(`${INDENT}${INDENT}${property}: {`)
624631
for (const [key, values] of map) {
625632
lines.push(`${INDENT.repeat(3)}${propertyKey(key)}: ${serializeStringArray(values)},`)

‎packages/configurator/src/generate.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { loadDesignSystems } from './design-system.ts'
88
import { emitModule } from './emit.ts'
99
import { materializeConfig } from './materialize.ts'
1010
import { type ConfigPlan, applyAugmentations, applyCustomUtilityPlan, buildPlan } from './plan.ts'
11+
import { prunePlan } from './prune.ts'
1112
import { snapshotTheme } from './snapshot.ts'
1213

1314
export interface GenerateOptions {
@@ -25,6 +26,8 @@ export interface GenerateOptions {
2526
format?: 'ts' | 'js'
2627
/** Module specifier the emitted code imports tailwind-merge's API from — see `EmitOptions.importSource`. */
2728
importSource?: string
29+
/** Shrinks the generated config to the classes a project uses: class names as a source scanner finds them (variants, important markers, and postfix modifiers included — see `createSourceScanner`). Class groups and scale members no listed class reaches are dropped; every class list made of listed classes merges exactly as with the full config, while classes outside the list pass through unmerged. The result is reported in `plan.report.pruning`. */
30+
prune?: { usedClasses: Iterable<string> }
2831
}
2932

3033
export interface GenerateResult {
@@ -95,13 +98,16 @@ export async function generate(options: GenerateOptions): Promise<GenerateResult
9598
}),
9699
)
97100

101+
// Pruning runs last, on the finished plan: only then does classification see every member a used class could reach (custom utilities, augmented classes, collision corrections included).
102+
const finalPlan = options.prune ? prunePlan(plan, options.prune.usedClasses) : plan
103+
98104
return {
99-
code: emitModule(plan, {
105+
code: emitModule(finalPlan, {
100106
banner: options.banner,
101107
format: options.format,
102108
importSource: options.importSource,
103109
}),
104-
config: materializeConfig(plan),
105-
plan,
110+
config: materializeConfig(finalPlan),
111+
plan: finalPlan,
106112
}
107113
}

‎packages/configurator/src/index.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
export { generate } from './generate.ts'
22
export type { GenerateOptions, GenerateResult } from './generate.ts'
33
export type { EncodingMode } from './compress.ts'
4-
export type { ConfigPlan, PlanReport, PlanValue, ScalePlan, ValidatorName } from './plan.ts'
4+
export type {
5+
ConfigPlan,
6+
PlanReport,
7+
PlanValue,
8+
PruneReport,
9+
ScalePlan,
10+
ValidatorName,
11+
} from './plan.ts'
512
export type { ScaleSnapshot, ThemeSnapshot } from './snapshot.ts'

‎packages/configurator/src/plan.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,22 @@ export interface PlanReport {
5252
}[]
5353
/** Theme-created classes no group could be determined for. Reported so gaps are visible instead of silently unmergeable. */
5454
unassignedClasses: { className: string; reason: string }[]
55+
/** Present when the plan was pruned to a project's used classes (see `prunePlan`). */
56+
pruning?: PruneReport
57+
}
58+
59+
/** What pruning did to a plan, for CLI output, plugin logs, and tests. Counts only — the kept class names are visible in the emitted config itself. */
60+
export interface PruneReport {
61+
/** Distinct class names handed to the pruner (raw scanner tokens included: anything that looked like a class name in the sources). */
62+
usedClassCount: number
63+
/** How many of them the full config classifies into a class group; the rest are non-Tailwind tokens, arbitrary properties, or class names the theme doesn't produce. */
64+
classifiedClassCount: number
65+
classGroupsBefore: number
66+
classGroupsAfter: number
67+
/** Class groups dropped because no used class belongs to them, in plan order. */
68+
removedClassGroups: string[]
69+
/** Class groups kept in full because a used class classified into them through a path the member-level walk could not attribute — should stay empty; non-empty means a mismatch between the walk and tailwind-merge's class map worth investigating. */
70+
unprunedClassGroups: string[]
5571
}
5672

5773
export interface ScalePlan {
@@ -416,7 +432,7 @@ function dedupeValues(values: PlanValue[]): PlanValue[] {
416432
})
417433
}
418434

419-
function filterConflictMap(
435+
export function filterConflictMap(
420436
conflictMap: Partial<Record<string, readonly string[]>>,
421437
classGroups: Map<string, PlanValue[]>,
422438
): Map<string, string[]> {

‎packages/configurator/src/prune.ts‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
import { validators } from 'tailwind-merge'
2+
import { createClassGroupUtils, createParseClassName } from 'tailwind-merge/unstable-do-not-import'
3+
4+
import { materializeConfig } from './materialize.ts'
5+
import { type ConfigPlan, type PlanValue, filterConflictMap } from './plan.ts'
6+
7+
/**
8+
* Shrinks a plan to the class names a project actually uses: class groups no used class belongs to are dropped, and within the kept groups only the members some used class reaches survive — literals a used class names, nested prefix objects a used class descends into, and validators a used class's remaining tail satisfies.
9+
*
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. Classes outside the used set lose their classification and pass through unmerged, which is the intended effect: a class Tailwind never saw has no styles, so keeping it next to a used class is at least as correct as merging it away.
11+
*
12+
* 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.
13+
*/
14+
export function prunePlan(plan: ConfigPlan, usedClasses: Iterable<string>): ConfigPlan {
15+
const config = materializeConfig(plan)
16+
const parseClassName = createParseClassName(config)
17+
const { getClassGroupId } = createClassGroupUtils(config)
18+
const postfixLookupClassGroupIds = new Set(config.postfixLookupClassGroups ?? [])
19+
20+
/** Used class names that classified, per class group — already stripped to the part the class map matched (no variants, no important marker, no postfix modifier unless the postfix lookup matched it, no leading minus). */
21+
const matchedNamesByGroup = new Map<string, Set<string>>()
22+
const seen = new Set<string>()
23+
let classifiedClassCount = 0
24+
25+
for (const rawClassName of usedClasses) {
26+
const className = rawClassName.trim()
27+
if (className === '' || seen.has(className)) {
28+
continue
29+
}
30+
seen.add(className)
31+
32+
const classification = classify(className)
33+
if (classification === null) {
34+
continue
35+
}
36+
classifiedClassCount += 1
37+
38+
let names = matchedNamesByGroup.get(classification.classGroupId)
39+
if (!names) {
40+
names = new Set()
41+
matchedNamesByGroup.set(classification.classGroupId, names)
42+
}
43+
names.add(lookupName(classification.matchedClassName))
44+
}
45+
46+
/**
47+
* Mirrors the lookup in tailwind-merge's `mergeClassList`: a class with a postfix modifier (`bg-red-500/50`) is first looked up without it, groups listed in `postfixLookupClassGroups` get a second chance with the postfix included, and a class that only resolves with the postfix kept is taken as is. Returns the group and the exact string the class map matched — that string is what the member-level walk has to keep reachable.
48+
*/
49+
function classify(
50+
className: string,
51+
): { classGroupId: string; matchedClassName: string } | null {
52+
const { isExternal, baseClassName, maybePostfixModifierPosition } =
53+
parseClassName(className)
54+
if (isExternal) {
55+
return null
56+
}
57+
58+
if (maybePostfixModifierPosition) {
59+
const withoutPostfix = baseClassName.substring(0, maybePostfixModifierPosition)
60+
let classGroupId = getClassGroupId(withoutPostfix)
61+
let matchedClassName = withoutPostfix
62+
63+
const classGroupIdWithPostfix =
64+
classGroupId && postfixLookupClassGroupIds.has(classGroupId)
65+
? getClassGroupId(baseClassName)
66+
: undefined
67+
if (classGroupIdWithPostfix && classGroupIdWithPostfix !== classGroupId) {
68+
classGroupId = classGroupIdWithPostfix
69+
matchedClassName = baseClassName
70+
}
71+
if (!classGroupId) {
72+
classGroupId = getClassGroupId(baseClassName)
73+
matchedClassName = baseClassName
74+
}
75+
return classGroupId ? { classGroupId, matchedClassName } : null
76+
}
77+
78+
const classGroupId = getClassGroupId(baseClassName)
79+
return classGroupId ? { classGroupId, matchedClassName: baseClassName } : null
80+
}
81+
82+
const classGroups = new Map<string, PlanValue[]>()
83+
const removedClassGroups: string[] = []
84+
const unprunedClassGroups: string[] = []
85+
86+
for (const [classGroupId, items] of plan.classGroups) {
87+
const names = matchedNamesByGroup.get(classGroupId)
88+
if (!names) {
89+
removedClassGroups.push(classGroupId)
90+
continue
91+
}
92+
const prunedItems = pruneItems(items, names)
93+
if (prunedItems.length === 0) {
94+
// A used class resolved into this group, but the walk found nothing it reaches — keep the group whole rather than risk undermatching; the report makes the discrepancy visible.
95+
unprunedClassGroups.push(classGroupId)
96+
classGroups.set(classGroupId, items)
97+
} else {
98+
classGroups.set(classGroupId, prunedItems)
99+
}
100+
}
101+
102+
return {
103+
...plan,
104+
classGroups,
105+
conflictingClassGroups: filterConflictMap(
106+
Object.fromEntries(plan.conflictingClassGroups),
107+
classGroups,
108+
),
109+
conflictingClassGroupModifiers: filterConflictMap(
110+
Object.fromEntries(plan.conflictingClassGroupModifiers),
111+
classGroups,
112+
),
113+
postfixLookupClassGroups: plan.postfixLookupClassGroups.filter((classGroupId) =>
114+
classGroups.has(classGroupId),
115+
),
116+
report: {
117+
...plan.report,
118+
pruning: {
119+
usedClassCount: seen.size,
120+
classifiedClassCount,
121+
classGroupsBefore: plan.classGroups.size,
122+
classGroupsAfter: classGroups.size,
123+
removedClassGroups,
124+
unprunedClassGroups,
125+
},
126+
},
127+
}
128+
}
129+
130+
/**
131+
* Keeps the items of one class-group level that some name in `names` reaches, walking nested prefix objects the way tailwind-merge's class map does: an object entry's key is a dash-separated prefix, so a name descends into it with the key stripped (`red-500` enters `{ red: […] }` as `500`), a name equal to the key enters as the empty string (the `''` literal marks "the prefix alone is a class"), and validators see the remaining tail at their level. Literal strings must match the remaining name exactly.
132+
*/
133+
function pruneItems(items: PlanValue[], names: Set<string>): PlanValue[] {
134+
const kept: PlanValue[] = []
135+
136+
for (const item of items) {
137+
if (item.kind === 'class') {
138+
if (names.has(item.value)) {
139+
kept.push(item)
140+
}
141+
} else if (item.kind === 'validator') {
142+
const validator = validators[item.name]
143+
for (const name of names) {
144+
if (validator(name)) {
145+
kept.push(item)
146+
break
147+
}
148+
}
149+
} else {
150+
const entries: [string, PlanValue[]][] = []
151+
for (const [key, entryItems] of item.entries) {
152+
const tails = new Set<string>()
153+
for (const name of names) {
154+
if (name === key) {
155+
tails.add('')
156+
} else if (name.startsWith(`${key}-`)) {
157+
tails.add(name.slice(key.length + 1))
158+
}
159+
}
160+
if (tails.size === 0) {
161+
continue
162+
}
163+
const prunedEntryItems = pruneItems(entryItems, tails)
164+
if (prunedEntryItems.length > 0) {
165+
entries.push([key, prunedEntryItems])
166+
}
167+
}
168+
if (entries.length > 0) {
169+
kept.push({ kind: 'object', entries })
170+
}
171+
}
172+
}
173+
174+
return kept
175+
}
176+
177+
/** The string the class map walks for a matched class: negative classes like `-mt-2` start their lookup after the empty first part, exactly as `getClassGroupId` skips it. */
178+
function lookupName(matchedClassName: string): string {
179+
const parts = matchedClassName.split('-')
180+
return parts[0] === '' && parts.length > 1 ? parts.slice(1).join('-') : matchedClassName
181+
}

‎packages/configurator/tests/__snapshots__/pruned-vanilla.snap.js‎

Lines changed: 29 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)