### Install cnfast with npm Source: https://github.com/aidenybai/cnfast/blob/main/README.md Install the cnfast package using npm. ```bash npm install cnfast ``` -------------------------------- ### Start development mode with nr dev Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Starts the development mode for the project. Run after building. ```bash nr dev ``` -------------------------------- ### Install dependencies with ni Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Installs project dependencies using @antfu/ni. Run from the repository root after cloning. ```bash ni ``` -------------------------------- ### Build and walk the trie example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/class-map.md Shows how to create a class map from the default config and access a node's classGroupId. The example logs the classGroupId for 'px' and the CLASS_PART_SEPARATOR constant. ```typescript import { getDefaultConfig } from "cnfast"; import { createClassMap, CLASS_PART_SEPARATOR } from "./lib/class-map.js"; // deep import const root = createClassMap(getDefaultConfig()); // "px-4" terminates at the node for ["px"], which carries the "px" group id const pxNode = root.nextPart.get("px"); console.log(pxNode?.classGroupId); // "px" console.log(CLASS_PART_SEPARATOR); // "-" ``` -------------------------------- ### Run cnfast development commands Source: https://github.com/aidenybai/cnfast/blob/main/README.md Development commands for cnfast: install dependencies, build, and test. ```bash ni nr build nr test ``` -------------------------------- ### mergeConfigs usage example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/config.md Shows how to import and use mergeConfigs with getDefaultConfig to override and extend class groups. The example demonstrates that overridden groups are replaced exactly, while extended groups are concatenated. ```ts import { getDefaultConfig, mergeConfigs } from "cnfast"; const config = mergeConfigs(getDefaultConfig(), { override: { classGroups: { "text-decoration": ["underline", "overline"] } }, extend: { classGroups: { "font-size": [{ text: ["display", "title", "body"] }], "text-decoration-strike": ["line-through"], }, }, }); config.classGroups["font-size"]; // base font-size group + { text: ["display", "title", "body"] } config.classGroups["text-decoration"]; // exactly ["underline", "overline"] (overridden) ``` -------------------------------- ### Build all packages with nr build Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Builds all packages in the monorepo. Run after installing dependencies. ```bash nr build ``` -------------------------------- ### clsx and cx basic usage example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/clsx.md Demonstrates clsx and cx with various inputs including strings, objects, arrays, and empty calls. ```typescript import { clsx, cx } from "cnfast"; clsx("foo", true && "bar", "baz"); // "foo bar baz" clsx({ foo: true, bar: false }, "baz"); // "foo baz" clsx(["foo", 0, false, "bar"]); // "foo bar" clsx(); // "" cx("a", "b"); // "a b" (alias, identical behavior) ``` -------------------------------- ### Direct engine use example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/merge-engine.md Shows how to create an engine with the default config and merge class strings. Demonstrates conflict resolution, whitespace normalization, and the fast path for single tokens. ```typescript import { getDefaultConfig } from "cnfast"; import { createMergeClassList } from "./lib/merge-class-list.js"; const engine = createMergeClassList(getDefaultConfig()); engine.mergeClassList("p-2 text-sm hover:p-3 p-4"); // "text-sm hover:p-3 p-4" engine.mergeClassList("px-2 px-4"); // "px-4" engine.mergeClassList(" a b "); // "a b" engine.mergeClassList(""); // "" engine.mergeClassList("single"); // "single" (fast path) ``` -------------------------------- ### createCn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/core.md Documentation for the createCn function, including its signature, parameters, return type, and usage examples. ```APIDOC ## `createCn` ### Description Creates a customized `cn`-shaped class name function with a custom merge configuration. ### Signature ```ts export const createCn = ( config: ConfigExtension | ((defaultConfig: AnyConfig) => AnyConfig), ): ClassNameFunction ``` ### Parameters - **`config`** (`ConfigExtension` | `((defaultConfig: AnyConfig) => AnyConfig)`) - Required - Either a `{ override?, extend? }` extension applied over `getDefaultConfig()` via `mergeConfigs`, or a function that receives the default config and returns a full `AnyConfig`. ### Return Type `ClassNameFunction` - A new `cn`-shaped function whose merge engine is built against the customized config. The returned function goes through the same optimized execution paths as the default `cn`. ### Throws None. ### Example — basic use with `extend` / `override` ```ts import { createCn } from "cnfast"; const themed = createCn({ override: { classGroups: { "text-decoration": ["underline", "overline"] } }, extend: { classGroups: { "text-decoration-strike": ["line-through"], "font-size": [{ text: ["display", "title", "body"] }], }, }, }); themed("text-red-500 text-title"); // "text-red-500 text-title" (custom group no longer conflicts with color) themed("text-title text-body"); // "text-body" (both in custom font-size group) themed("underline line-through"); // "underline line-through" (override split the group) themed("px-2 px-4"); // "px-4" (default groups unchanged) ``` ### Example — function form (full config control) ```ts import { createCn, getDefaultConfig } from "cnfast"; // Use the function form to compute a config from the default: append one // class to the existing font-size group. const withDisplayClass = createCn((defaultConfig) => ({ ...defaultConfig, classGroups: { ...defaultConfig.classGroups, "font-size": [...defaultConfig.classGroups["font-size"], { text: ["display"] }], }, })); withDisplayClass("text-title text-display"); // "text-display" ``` ``` -------------------------------- ### getDefaultConfig usage example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/config.md Shows how to import and use getDefaultConfig. Access class groups and conflicting class groups, and demonstrates that each call returns a new object safe to mutate. ```ts import { getDefaultConfig } from "cnfast"; const config = getDefaultConfig(); config.classGroups["px"]; // readonly tuple incl. isArbitraryVariable, isArbitraryValue, themeSpacing, ... config.conflictingClassGroups["font-size"]; // ["leading"] // Each call returns a new object — safe to mutate if you build a custom factory: const mine = getDefaultConfig(); mine.classGroups = { ...mine.classGroups, "font-size": [...mine.classGroups["font-size"], { text: ["display"] }] }; ``` -------------------------------- ### Run cnfast migrate with dry-run and yes flags Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Example invocations of `cnfast migrate`: one with `--dry-run` to preview changes, and one with `-c` and `-y` to apply without confirmation. ```bash cnfast migrate --cwd ./my-app --dry-run # preview rewrites without touching files cnfast migrate -c ./my-app -y # apply without confirmation ``` -------------------------------- ### Example: createSortModifiers usage Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/merge-engine.md Example usage of createSortModifiers with getDefaultConfig. Shows sorting of modifiers with comments indicating sorted segments, pinned order-sensitive modifiers, and arbitrary modifiers. ```ts import { getDefaultConfig } from "cnfast"; import { createSortModifiers } from "./lib/sort-modifiers.js"; const sortModifiers = createSortModifiers(getDefaultConfig()); sortModifiers(["focus", "hover"]); // ["focus", "hover"] (sorted segment) sortModifiers(["focus", "before", "hover"]); // ["focus", "before", "hover"] (before pinned) sortModifiers(["flex", "[&>p]"]); // ["flex", "[&>p]"] (arbitrary pinned) ``` -------------------------------- ### Prepared parts example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/merge-engine.md Shows how to merge pre-split class parts using mergePreparedParts, which is the path cn's N-argument calls use. The classList is the concatenation used for cache keys and offsets. ```typescript import { getDefaultConfig } from "cnfast"; import { createMergeClassList } from "./lib/merge-class-list.js"; const engine = createMergeClassList(getDefaultConfig()); const parts = ["p-2", "text-sm", "p-4"]; engine.mergePreparedParts(parts, parts.length, parts.join(" ")); // "text-sm p-4" ``` -------------------------------- ### twJoin usage example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/tw-merge.md Example usage of `twJoin` from the `cnfast` package. It joins truthy class values, ignoring falsy values and null, and flattens nested arrays. The output is a single string with classes separated by spaces. ```ts import { twJoin } from "cnfast"; twJoin("px-2", isActive && "bg-blue-500", ["text-sm", null]); // "px-2 bg-blue-500 text-sm" ``` -------------------------------- ### Basic usage of cn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/core.md Basic usage examples of `cn` covering strings, conflict resolution, conditionals, objects, nested arrays, and zero arguments. ```ts import { cn } from "cnfast"; // single string cn("px-2 py-1"); // "px-2 py-1" // multiple strings: last class in a conflict group wins cn("px-2 py-1", "px-4"); // "py-1 px-4" // conditionals and objects const isActive = true; const hasError = true; cn("px-2", isActive && "bg-blue-500", { "text-red-500": hasError, "text-green-500": false }); // "px-2 bg-blue-500 text-red-500" // arrays nested arbitrarily cn(["hover:bg-black", ["focus:ring-2", null]]); // "hover:bg-black focus:ring-2" // zero args cn(); // "" ``` -------------------------------- ### createCn basic use with extend and override Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/core.md Shows how to use createCn with override and extend to customize class groups. The example demonstrates the resulting behavior for conflicting classes, showing that override splits groups and extend adds new ones while default groups remain unchanged. ```ts import { createCn } from "cnfast"; const themed = createCn({ override: { classGroups: { "text-decoration": ["underline", "overline"] } }, extend: { classGroups: { "text-decoration-strike": ["line-through"], "font-size": [{ text: ["display", "title", "body"] }], }, }, }); themed("text-red-500 text-title"); // "text-red-500 text-title" (custom group no longer conflicts with color) themed("text-title text-body"); // "text-body" (both in custom font-size group) themed("underline line-through"); // "underline line-through" (override split the group) themed("px-2 px-4"); // "px-4" (default groups unchanged) ``` -------------------------------- ### parseClassName usage example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/merge-engine.md Example usage of parseClassName with two class tokens, showing the returned objects for each. ```ts import { parseClassName } from "./lib/parse-class-name.js"; parseClassName("hover:focus:px-4!"); // { isExternal: undefined, modifiers: ["hover", "focus"], hasImportantModifier: true, // baseClassName: "px-4", maybePostfixModifierPosition: undefined } parseClassName("text-lg/7"); // { modifiers: [], hasImportantModifier: false, baseClassName: "text-lg/7", // maybePostfixModifierPosition: 7 } ``` -------------------------------- ### Verifying lazy initialization Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/tw-merge.md Verifies that the config factory is invoked lazily and exactly once per instance. The example shows that configCalls remains 0 until the first merge call, and after two merges it is 1, confirming the factory runs only once. ```ts import { createTailwindMerge, getDefaultConfig } from "cnfast"; let configCalls = 0; const lazyMerge = createTailwindMerge(() => { configCalls++; return getDefaultConfig(); }); console.log(configCalls); // 0 — config factory not called lazyMerge("px-2 px-3"); // "px-3" lazyMerge("flex hidden"); // "hidden" console.log(configCalls); // 1 — factory ran exactly once ``` -------------------------------- ### createCallSiteCn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/call-site-cn.md Documentation for the createCallSiteCn function, including its signature, parameters, return type, memoization semantics, and usage examples. ```APIDOC ## createCallSiteCn(classNameFunction?) ### Description Creates a memoizing wrapper around a class name function (default `cn`) that caches results for repeated calls with identical primitive arguments, improving performance for call-site-level class resolution. ### Method Function call ### Endpoint `createCallSiteCn(classNameFunction?: ClassNameFunction): ClassNameFunction` ### Parameters #### Function Parameters - **classNameFunction** (`ClassNameFunction`) - Optional - Default: `cn` - The underlying function that resolves the class list. Any `ClassNameFunction` works, including the result of `createCn(...)`. ### Return Type `ClassNameFunction` — a memoizing wrapper with the same call shape `(...classValues: ClassValue[]) => string` and identical output to the wrapped function. ### Memoization Semantics - Bounded ring of `CALL_SITE_MEMO_ROW_COUNT` = 4 rows; each row holds `CALL_SITE_MEMO_ARGUMENT_SLOTS_PER_ROW` = 12 argument slots. - A row is stored only when the call has `argumentCount <= 12` **and** every argument is a primitive (`null`, or `typeof value !== "object" && typeof value !== "function"`). Object, array, or function arguments are never memoized because their contents can change without identity change — such calls always fall through to the wrapped function. - Primitives are compared with `===` against the stored row, so distinct falsy kinds (`false`, `null`, `undefined`, `0`, `""`) are distinguished. - When the ring is full, the oldest row (`nextMemoRowIndex` wraps to 0) is overwritten. Empty slot count initial state is `EMPTY_CALL_SITE_MEMO_ARGUMENT_COUNT` = `-1` so zero-argument calls hit the `argumentCount` mismatch check correctly. ### Throws None; propagates whatever the wrapped `classNameFunction` does (in practice nothing). ### Example — basic use ```ts import { cn, createCallSiteCn } from "cnfast"; const callSiteCn = createCallSiteCn(); // wraps default cn callSiteCn("px-2 py-1", "px-4"); // first call resolves through cn callSiteCn("px-2 py-1", "px-4"); // memo hit — cn is not invoked; output is identical callSiteCn("px-2 py-1"); // arity differs → miss → resolved fresh ``` ### Example — wrapping a custom configuration and handling non-memoizable inputs ```ts import { createCallSiteCn, createCn, type ClassValue } from "cnfast"; const themed = createCn({ extend: { classGroups: { "font-size": [{ text: ["title"] }] } }, }); const themedCallSite = createCallSiteCn(themed); // repeated primitive calls are served from the memo themedCallSite("text-title text-body"); // object/array/function arguments bypass the memo and are resolved every time const dynamic: Record = { "text-red-500": true }; themedCallSite("px-2", dynamic); // always resolved via themed() ``` ### Zero-argument call ```ts const callSiteCn = createCallSiteCn(); callSiteCn(); // "" — stored as a memo row with argumentCount 0 callSiteCn(); // "" — memo hit ``` ``` -------------------------------- ### resolveClassValue usage example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/clsx.md Shows how to deep-import resolveClassValue and its output for arrays, numbers, and falsy values. ```typescript import { resolveClassValue } from "./clsx"; // deep import; not top-level resolveClassValue(["a", { b: true, c: 0 }, ["d", null]]); // "a b d" resolveClassValue(42); // "42" resolveClassValue(false); // "" ``` -------------------------------- ### Zero-argument call with createCallSiteCn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/call-site-cn.md Zero-argument call example. The first call returns an empty string and stores a memo row with argumentCount 0; the second call is a memo hit and returns the same empty string. ```ts const callSiteCn = createCallSiteCn(); callSiteCn(); // "" — stored as a memo row with argumentCount 0 callSiteCn(); // "" — memo hit ``` -------------------------------- ### Import and use cn from cnfast Source: https://github.com/aidenybai/cnfast/blob/main/README.md Import the cn function from cnfast and use it to merge Tailwind CSS classes. The example shows the output of the function call. ```ts import { cn } from "cnfast"; cn("px-2 py-1", isActive && "px-4", { "text-red-500": hasError }); // "py-1 px-4 text-red-500" ``` -------------------------------- ### Add cnfast to shadcn/ui project Source: https://github.com/aidenybai/cnfast/blob/main/README.md Add or replace the cn utility in a shadcn/ui project using the registry. This rewrites lib/utils.ts to re-export cnfast and installs the package. ```bash npx shadcn@latest add aidenybai/cnfast/cn ``` -------------------------------- ### createSortModifiers Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/merge-engine.md Documentation for the createSortModifiers function, including its signature, parameters, return type, and usage example. ```APIDOC ## `createSortModifiers` ### Description Creates a function that sorts modifiers into tailwind-merge-compatible order, keeping arbitrary and order-sensitive modifiers pinned in place while sorting the segments between them alphabetically. ### Signature ```ts export const createSortModifiers = (config: AnyConfig) => (modifiers: readonly string[]) => string[] ``` ### Parameters - **config** (`AnyConfig`) - Required - Reads `config.orderSensitiveModifiers`. ### Return Type `(modifiers: readonly string[]) => string[]` — a function that sorts modifiers into tailwind-merge-compatible order: arbitrary (`[…]`) and order-sensitive modifiers (`*`, `**`, `after`, `backdrop`, `before`, `details-content`, `file`, `first-letter`, `first-line`, `marker`, `placeholder`, `selection` under the default config) stay pinned in place, and the segments between them are sorted alphabetically. ### Example ```ts import { getDefaultConfig } from "cnfast"; import { createSortModifiers } from "./lib/sort-modifiers.js"; const sortModifiers = createSortModifiers(getDefaultConfig()); sortModifiers(["focus", "hover"]); // ["focus", "hover"] (sorted segment) sortModifiers(["focus", "before", "hover"]); // ["focus", "before", "hover"] (before pinned) sortModifiers(["flex", "[&>p]"]); // ["flex", "[&>p]"] (arbitrary pinned) ``` ``` -------------------------------- ### Using migrateSource to rewrite an import Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Example usage of migrateSource. It imports the function and calls it with a sample import statement, showing that the import is rewritten from 'tailwind-merge' to 'cnfast' and changeCount is 1. ```typescript import { migrateSource } from "./utils/migrate-source.js"; const { code, changeCount } = migrateSource(`import { twMerge } from "tailwind-merge";`); // code: `import { twMerge } from "cnfast";` changeCount: 1 ``` -------------------------------- ### Enumerate conflict rows with groupIndexes and conflictRowsBase Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/class-groups.md Shows how to enumerate conflict rows for a group using groupIndexes, groupNames, and conflictRowsBase. The example prints the conflict groups for "px" (["pr", "pl"]) and for "p" (all side padding groups). ```ts import { getDefaultConfig } from "cnfast"; import { createClassGroupLookup } from "./lib/class-groups.js"; const lookup = createClassGroupLookup(getDefaultConfig()); const pxIndex = lookup.groupIndexes.get("px")!; console.log(lookup.groupNames[pxIndex]); // "px" // All groups that "px" conflicts with, resolved back to names: const pxConflicts = lookup.conflictRowsBase[pxIndex].map((i) => lookup.groupNames[i]); console.log(pxConflicts); // ["pr", "pl"] // The "p" group conflicts with every side padding group: const pIndex = lookup.groupIndexes.get("p")!; console.log(lookup.conflictRowsBase[pIndex].map((i) => lookup.groupNames[i])); // ["px", "py", "ps", "pe", "pbs", "pbe", "pt", "pr", "pb", "pl"] ``` -------------------------------- ### parseClassName Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/merge-engine.md Documentation for the parseClassName function, including its signature, parameters, return type, behavior notes, and usage examples. ```APIDOC ## `parseClassName` ### Description Parses a single class token into its constituent parts: modifiers, important modifier, base class name, and postfix modifier position. ### Signature ```ts export const parseClassName = (className: string): ParsedClassName ``` ### Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `className` | `string` | yes | Any single class token | ### Return type `ParsedClassName` (see [types.md](../types.md)): | Field | Type | Description | | --- | --- | --- | | `isExternal` | `boolean \| undefined` | Always `undefined` for `parseClassName` output (set by callers); present for shape parity | | `modifiers` | `string[]` | Variant modifiers split on `:` (shared frozen `EMPTY_MODIFIERS` array when none) | | `hasImportantModifier` | `boolean` | True when the class ends or starts with `!` | | `baseClassName` | `string` | Class without modifiers and without the `!` prefix/suffix | | `maybePostfixModifierPosition` | `number \| undefined` | Offset of `/` inside the base (postfix modifier), `undefined` when absent or before the base start | ### Behavior notes (from source) - The scanner walks once, tracking bracket `[…]` and paren `(…)` depth so `:`/`/` inside arbitrary values do not split the token. - `!` is consumed from the **end** of the base first; otherwise from the **start**. - Reads `charCodeAt` numbers, never indexed strings. ### Example ```ts import { parseClassName } from "./lib/parse-class-name.js"; parseClassName("hover:focus:px-4!"); // { isExternal: undefined, modifiers: ["hover", "focus"], hasImportantModifier: true, // baseClassName: "px-4", maybePostfixModifierPosition: undefined } parseClassName("text-lg/7"); // { modifiers: [], hasImportantModifier: false, baseClassName: "text-lg/7", // maybePostfixModifierPosition: 7 } ``` ``` -------------------------------- ### Using validators to check value formats Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/validators.md Import validators from './lib/validators.js' and test values like fractions, numbers, percentages, arbitrary values, and named container queries. The example shows expected boolean results for each check, including edge cases like non-length arbitrary values. ```ts import { isArbitraryLength, isArbitraryValue, isArbitraryVariable, isFraction, isNamedContainerQuery, isNumber, isPercent, } from "./lib/validators.js"; isFraction("1/2"); // true isNumber("-42"); // true isPercent("75%"); // true isArbitraryValue("[bg-red-500]"); // true (label "bg", value "red-500") isArbitraryLength("[10px]"); // true (raw length value) isArbitraryLength("[3]"); // false (not a length unit) isArbitraryVariable("(--my-color:theme(colors.red.500))"); // true (label "--my-color") isNamedContainerQuery("@container/size/"); // true ``` -------------------------------- ### Classic conditional-cn pattern example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/clsx.md Shows using cn (which fuses twMerge and clsx) to conditionally apply classes based on props. ```typescript import { cn } from "cnfast"; // cn = twMerge(clsx(...)) fused type ButtonProps = { primary?: boolean; disabled?: boolean }; function buttonClass({ primary, disabled }: ButtonProps): string { return cn( "inline-flex items-center rounded", primary ? "bg-blue-600 text-white" : "bg-gray-200 text-gray-800", disabled && "opacity-50 pointer-events-none", ); } ``` -------------------------------- ### twMerge basic usage Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/tw-merge.md Basic usage examples of twMerge showing conflict resolution, modifier awareness, and handling of falsy values. The rightmost class per conflict group wins. ```ts import { twMerge } from "cnfast"; twMerge("px-2 py-1 bg-red-500", "px-4 bg-blue-500"); // "py-1 px-4 bg-blue-500" twMerge("flex", "hidden"); // "hidden" twMerge("hover:block", "hover:flex"); // "hover:flex" (modifier-aware) twMerge("text-red-500", ["text-blue-500", null]); // "text-blue-500" ``` -------------------------------- ### Custom instance with custom config factory Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/tw-merge.md Creates a custom TailwindMerge instance with a custom config factory that extends the default config with a new class group for font-size. The example shows that the custom class group is used to merge conflicting classes, resulting in "text-display". ```ts import { createTailwindMerge, getDefaultConfig, mergeConfigs } from "cnfast"; const myTwMerge = createTailwindMerge(() => mergeConfigs(getDefaultConfig(), { extend: { classGroups: { "font-size": [{ text: ["display"] }], }, }, }), ); myTwMerge("text-xs text-display"); // "text-display" ``` -------------------------------- ### Before and after migration of cn helper Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Before and after of a shadcn-style helper after running `cnfast migrate`. Imports from `clsx` and `tailwind-merge` are rewritten to `cnfast`. ```ts // before import { clsx, type ClassValue } from "clsx"; import { twMerge } from "tailwind-merge"; export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs)); ``` ```ts // after running cnfast migrate import { clsx, type ClassValue } from "cnfast"; import { twMerge } from "cnfast"; export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs)); ``` -------------------------------- ### Migrate existing project with npx cnfast migrate Source: https://github.com/aidenybai/cnfast/blob/main/README.md Run the migration command to convert an existing clsx, classnames, or tailwind-merge project to cnfast. ```bash npx cnfast migrate ``` -------------------------------- ### Project structure tree Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Shows the top-level directory structure of the project, highlighting the main package folder. ```text packages/ └── cnfast/ # Library, CLI, tests, and benchmarks ``` -------------------------------- ### Run pre-commit checks with pnpm Source: https://github.com/aidenybai/cnfast/blob/main/AGENTS.md Run all checks before committing. The commands run tests, linting, type checking, and formatting. ```bash pnpm test # runs tests pnpm lint pnpm typecheck # runs type checking pnpm format ``` -------------------------------- ### Typical Config customization with createCn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/configuration.md Shows how to customize the cnfast configuration by overriding and extending class groups and conflicting class group modifiers. The override replaces the 'text-decoration' class group, while extend appends to 'font-size' and adds a conflict with 'leading'. ```ts import { createCn } from "cnfast"; const themed = createCn({ override: { classGroups: { "text-decoration": ["underline", "overline"] } }, extend: { classGroups: { "font-size": [{ text: ["display", "title", "body"] }] }, conflictingClassGroupModifiers: { "font-size": ["leading"] }, }, }); ``` -------------------------------- ### Wrapping custom configuration with createCallSiteCn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/call-site-cn.md Wraps a custom configuration created with createCn. Repeated primitive calls are served from the memo, while object/array/function arguments bypass the memo and are resolved every time via the wrapped function. ```ts import { createCallSiteCn, createCn, type ClassValue } from "cnfast"; const themed = createCn({ extend: { classGroups: { "font-size": [{ text: ["title"] }] } }, }); const themedCallSite = createCallSiteCn(themed); // repeated primitive calls are served from the memo themedCallSite("text-title text-body"); // object/array/function arguments bypass the memo and are resolved every time const dynamic: Record = { "text-red-500": true }; themedCallSite("px-2", dynamic); // always resolved via themed() ``` -------------------------------- ### Run tests with pnpm test Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Runs the test suite for the project. ```bash pnpm test ``` -------------------------------- ### Add a changeset with nr changeset Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Generates a changeset for publishing packages. Follow the prompts to describe changes. ```bash nr changeset ``` -------------------------------- ### getDefaultConfig Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/config.md Returns a fresh configuration object for cnfast, containing theme, classGroups, conflictingClassGroups, conflictingClassGroupModifiers, postfixLookupClassGroups, and orderSensitiveModifiers. Each call returns a new object, safe to mutate. ```APIDOC ## getDefaultConfig ### Description Returns a fresh configuration object for cnfast, containing theme, classGroups, conflictingClassGroups, conflictingClassGroupModifiers, postfixLookupClassGroups, and orderSensitiveModifiers. Each call returns a new object, safe to mutate. ### Signature ```ts declare const getDefaultConfig: () => Config; ``` ### Parameters None. ### Return Type `Config` — a fresh config object each call containing: - `theme`: `ThemeObject` keyed by `DefaultThemeGroupIds` (`animate`, `aspect`, `blur`, `breakpoint`, `color`, `container`, `drop-shadow`, `ease`, `font-weight`, `font`, `inset-shadow`, `leading`, `perspective`, `radius`, `shadow`, `spacing`, `text`, `text-shadow`, `tracking`) - `classGroups`: ~380 conflict groups keyed by `DefaultClassGroupIds` (e.g. `px`, `flex-direction`, `shadow`, …) - `conflictingClassGroups`: base conflict edges (e.g. `"px": ["pl", "pr", "ps", "pe", "pt", "pb", "py", "p", "m", ...]`) - `conflictingClassGroupModifiers`: modifier-context conflict edges (e.g. `"font-size": ["leading"]`) - `postfixLookupClassGroups`: `["container-type"]` - `orderSensitiveModifiers`: `["*", "**", "after", "backdrop", "before", "details-content", "file", "first-letter", "first-line", "marker", "placeholder", "selection"]` ### Example ```ts import { getDefaultConfig } from "cnfast"; const config = getDefaultConfig(); config.classGroups["px"]; // readonly tuple incl. isArbitraryVariable, isArbitraryValue, themeSpacing, ... config.conflictingClassGroups["font-size"]; // ["leading"] // Each call returns a new object — safe to mutate if you build a custom factory: const mine = getDefaultConfig(); mine.classGroups = { ...mine.classGroups, "font-size": [...mine.classGroups["font-size"], { text: ["display"] }] }; ``` ``` -------------------------------- ### Basic cva usage with variants and compoundVariants Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cva.md Defines a button component with variants for intent, size, and disabled states, plus compound variants and default variants. Shows how to call the resulting function with no arguments or with variant overrides, and notes that custom classes are appended last. ```ts import { cva } from "cnfast"; const button = cva("inline-flex items-center rounded-md", { variants: { intent: { primary: "bg-blue-600 text-white", secondary: "bg-gray-200 text-gray-800", danger: "bg-red-600 text-white", }, size: { small: "text-sm px-2 py-1", medium: "text-base px-4 py-2", }, disabled: { true: "opacity-50 pointer-events-none", false: "cursor-pointer", }, }, compoundVariants: [ { intent: "primary", size: "medium", class: "shadow-md" }, { intent: "danger", disabled: false, className: "ring-2 ring-red-300" }, ], defaultVariants: { intent: "primary", size: "medium", disabled: false }, }); button(); // "inline-flex items-center rounded-md bg-blue-600 text-white text-base px-4 py-2 cursor-pointer shadow-md" button({ intent: "danger" }); // base + danger + medium + enabled + compound danger/medium-only button({ intent: "secondary", class: "uppercase" }); // custom class appended last button({ disabled: true, className: "animate-pulse" }); ``` -------------------------------- ### Define cnfast migrate subcommand Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Defines the `cnfast migrate` subcommand with options `-c, --cwd`, `-d, --dry-run`, and `-y, --yes`. The action is omitted; behavior is described in the surrounding text. ```ts export const migrate = new Command() .name("migrate") .description("rewrite clsx / classnames / tailwind-merge imports to cnfast") .option("-c, --cwd ", "working directory (defaults to current directory)", process.cwd()) .option("-d, --dry-run", "preview changes without writing files", false) .option("-y, --yes", "apply changes without confirmation", false) .action(async (options: MigrateOptions) => { ... }); ``` -------------------------------- ### Compose a full custom instance with createTailwindMerge Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/config.md Example of composing a custom Tailwind merge instance by merging the default config with a custom extension for conflicting class group modifiers. The resulting tw function resolves conflicts as shown. ```typescript import { createTailwindMerge, getDefaultConfig, mergeConfigs } from "cnfast"; const tw = createTailwindMerge(() => mergeConfigs(getDefaultConfig(), { extend: { conflictingClassGroupModifiers: { "font-size": ["leading"] } }, }), ); tw("text-sm", "leading-none"); // "leading-none" (leading now conflicts under font-size modifier) ``` -------------------------------- ### Validator nodes accept arbitrary values example Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/class-map.md Demonstrates that arbitrary values like 'w-[10px]' fall back to the width node's validators. It checks if any validator matches the arbitrary value and returns the correct group id. ```typescript import { getDefaultConfig } from "cnfast"; import { createClassMap } from "./lib/class-map.js"; import { isArbitraryValue } from "./lib/validators.js"; const root = createClassMap(getDefaultConfig()); const widthNode = root.nextPart.get("w"); // group "w" // arbitrary values like "w-[10px]" and w-[var(--x)] fall back to widthNode.validators const validators = widthNode?.validators ?? []; validators.some((v) => v.validator("w-[10px]") && v.classGroupId === "w"); // true ``` -------------------------------- ### Replace shadcn/ui cn helper with cnfast Source: https://github.com/aidenybai/cnfast/blob/main/README.md Replace the shadcn/ui cn helper with cnfast. The before code shows the original implementation using clsx and tailwind-merge, and the after code shows the cnfast replacement. ```ts // before import { clsx, type ClassValue } from "clsx"; import { twMerge } from "tailwind-merge"; export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs)); // after export { cn } from "cnfast"; ``` -------------------------------- ### createCn Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/core.md Documentation for the `createCn` factory function, which creates a `ClassNameFunction` instance with a custom `twMerge` implementation. ```APIDOC ## `createCn` ### Description `createCn` is a factory function that creates a `ClassNameFunction` instance. It is exported at line 595 of `core.ts`. ### Signature ```ts export const createCn: (twMerge: typeof twMerge) => ClassNameFunction; ``` ### Parameters - `twMerge` (function) - Required - A `twMerge` function used to merge conflicting Tailwind classes. ### Return Type `ClassNameFunction` - A function that accepts variadic class values and returns a merged class string. ### Example ```ts import { createCn } from "cnfast"; import { twMerge } from "tailwind-merge"; const customCn = createCn(twMerge); customCn("px-2", "px-4"); // "px-4" ``` ``` -------------------------------- ### Define root cnfast CLI program Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Defines the root `cnfast` commander program with name, description, and version flag. Adds the `migrate` subcommand. `SIGINT` and `SIGTERM` terminate the process with exit code 0. ```ts const program = new Command() .name("cnfast") .description("CLI for cnfast") .version(VERSION, "-v, --version", "display the version number"); program.addCommand(migrate); ``` -------------------------------- ### getDefaultConfig implementation (src/lib/default-config.ts:31) Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/config.md Returns a fresh config object each call, building theme getters for Tailwind v4 theme namespaces. The config uses 'as const satisfies' to ensure literal types. Safe to mutate the returned object if building a custom factory. ```ts // src/lib/default-config.ts:31 export const getDefaultConfig = () => { // builds theme getters for the Tailwind v4 theme namespaces, then returns // ... as const satisfies Config; }; ``` -------------------------------- ### Config interface with theme, classGroups, and conflict settings Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/types.md Defines the main configuration object passed to createCn and mergeConfigs. Includes theme scales, class group definitions, conflict edges, and modifier settings. The postfixLookupClassGroups field is optional. ```typescript export interface Config { theme: NoInfer>; classGroups: NoInfer>>; conflictingClassGroups: NoInfer>>; conflictingClassGroupModifiers: NoInfer>>; postfixLookupClassGroups?: readonly NoInferString[]; orderSensitiveModifiers: string[]; } ``` -------------------------------- ### Create a new branch Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Creates a new branch for your feature or fix. ```bash git checkout -b feat/your-feature-name ``` -------------------------------- ### mergeConfigs(baseConfig, { extend, override }) Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/config.md Merges configuration extensions and overrides into a base config. The base config is mutated in place and returned. Override entries replace base entries, while extend entries are concatenated onto base arrays. ```APIDOC ## mergeConfigs(baseConfig, { extend, override }) ### Description Merges configuration extensions and overrides into a base config. The base config is mutated in place and returned. Override entries replace base entries, while extend entries are concatenated onto base arrays. ### Method Function ### Signature ```ts export const mergeConfigs = ( baseConfig: AnyConfig, { extend = {}, override = {} }: ConfigExtension, ): AnyConfig => { ... }; ``` ### Parameters - **baseConfig** (`AnyConfig`) - Required - The base config; **mutated in place** and returned - **extend** (`Partial`) - Optional (default `{}`) - Entries whose arrays are concatenated onto the base arrays - **override** (`Partial`) - Optional (default `{}`) - Entries that entirely replace the base entries ### Semantics - `override.theme/classGroups/conflictingClassGroups/conflictingClassGroupModifiers`: for each key present in the override object, the base entry is **replaced** (`overrideConfigProperties`). - `override.postfixLookupClassGroups` / `override.orderSensitiveModifiers`: if defined, the whole base array is **replaced** (`overrideProperty`). - `extend.theme/classGroups/…`: arrays for the same key are **concatenated** (`base.concat(mergeValue)`), key by key; keys not in the base are added. - `extend.postfixLookupClassGroups` / `extend.orderSensitiveModifiers`: concatenated onto the base arrays (`mergeArrayProperties`). - Applies `override` first, then `extend`. ### Example ```ts import { getDefaultConfig, mergeConfigs } from "cnfast"; const config = mergeConfigs(getDefaultConfig(), { override: { classGroups: { "text-decoration": ["underline", "overline"] } }, extend: { classGroups: { "font-size": [{ text: ["display", "title", "body"] }], "text-decoration-strike": ["line-through"], }, }, }); config.classGroups["font-size"]; // base font-size group + { text: ["display", "title", "body"] } config.classGroups["text-decoration"]; // exactly ["underline", "overline"] (overridden) ``` ``` -------------------------------- ### Lint and format commands Source: https://github.com/aidenybai/cnfast/blob/main/CONTRIBUTING.md Commands to check and fix lint errors, and format code with oxfmt. ```bash nr lint # Check for lint errors nr lint:fix # Fix lint errors nr format # Format code with oxfmt ``` -------------------------------- ### createCn function form for full config control Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/core.md Demonstrates the function form of createCn for full config control. It receives the default config and returns a new config with an appended class to the font-size group, resulting in the later class winning. ```ts import { createCn, getDefaultConfig } from "cnfast"; // Use the function form to compute a config from the default: append one // class to the existing font-size group. const withDisplayClass = createCn((defaultConfig) => ({ ...defaultConfig, classGroups: { ...defaultConfig.classGroups, "font-size": [...defaultConfig.classGroups["font-size"], { text: ["display"] }], }, })); withDisplayClass("text-title text-display"); // "text-display" ``` -------------------------------- ### spinner Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Creates an ora spinner instance with the given text. ```APIDOC ## spinner ### Description Creates an ora spinner instance with the given text. ### Signature ```ts export const spinner = (text: string) => ora({ text }); ``` ### Parameters - `text` (string) - Required - The text to display next to the spinner. ### Returns - `ora.Ora` - An ora spinner instance. ``` -------------------------------- ### logger Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/cli.md Provides console logging wrappers with colored output for different levels. ```APIDOC ## logger ### Description Provides console logging wrappers with colored output for different levels. ### Properties - `error` - Logs an error message. - `warn` - Logs a warning message. - `success` - Logs a success message. - `info` - Logs an info message. - `log` - Logs a standard message. - `break` - Logs a blank line. ``` -------------------------------- ### twJoin implementation (src/lib/tw-join.ts) Source: https://github.com/aidenybai/cnfast/blob/main/_autodocs/api-reference/tw-merge.md Implementation of the `twJoin` function that joins truthy class name values with single spaces, recursively flattening arrays. It accepts only `ClassNameValue` (strings, falsy values, or nested arrays) and returns an empty string for empty input. Unlike `clsx`, it does not accept objects or numbers. ```ts // src/lib/tw-join.ts:8 export const twJoin = (...classValues: ClassNameValue[]): string => { let index = 0; let classValue: ClassNameValue; let resolvedClassName: string; let classList = ""; while (index < classValues.length) { if ((classValue = classValues[index++])) { if ((resolvedClassName = resolveClassNameValue(classValue))) { if (classList) classList += SPACE_CHARACTER; classList += resolvedClassName; } } } return classList; }; ``` -------------------------------- ### Generation-stamped claim tracker with Int32Array Source: https://github.com/aidenybai/cnfast/blob/main/docs/architecture.md Implements a generation-stamped claim tracker using an Int32Array indexed by conflict-key ID. Each merge increments a generation counter; a key is claimed when its stored stamp equals the current generation. The loop reads the array directly for performance, and the array grows in the cold interning path when new IDs appear. ```typescript currentGeneration = (currentGeneration + 1) | 0; if (currentGeneration === 0) currentGeneration = 1; const generation = currentGeneration; // ... per token, after looking up its descriptor: if (claimedGeneration[classId] === generation) continue; claimedGeneration[classId] = generation; ```