> For the complete documentation index, see [llms.txt](https://infinitode-docs.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://infinitode-docs.gitbook.io/documentation/package-documentation/tailclass-package-documentation.md).

# TailClass Package Documentation

Scan repeated Tailwind CSS utilities, generate semantic classes, and refactor templates with TailClass for Node.js.

[TailClass](https://github.com/Infinitode/TailClass) is a zero-dependency Node.js tool that finds repeated Tailwind CSS utility patterns, suggests semantic class names, generates a shared stylesheet, and rewrites matching templates. It recognizes Tailwind v3 and v4 utilities, including variants and arbitrary values, and matches utility lists regardless of their order. It can also find shared subsets while leaving extra utilities and markers such as `group`, `peer`, and `js-*` inline.

This guide covers **TailClass 1.0.2**. For a complete, tested walkthrough, see [TailClass Usage Examples](https://infinitode-docs.gitbook.io/documentation/package-documentation/tailclass-package-documentation/tailclass-usage-examples.md). See the [npm package](https://www.npmjs.com/package/tailclass) and [GitHub repository](https://github.com/Infinitode/TailClass) for releases and source code.

## Requirements and installation

TailClass requires **Node.js 18 or later**. Install it as a development dependency in a project that already uses Tailwind CSS:

```bash
npm install --save-dev tailclass@^1.0.2
```

If you have 1.0.0 or 1.0.1, run the same install command to upgrade and update your lockfile, then verify the installed version is at least 1.0.2:

```bash
npm ls tailclass
npx tailclass --version
```

For a global installation, upgrade with `npm install -g tailclass@^1.0.2`. TailClass generates CSS containing `@apply`; your project still needs a Tailwind build pipeline to process it.

## Security in 1.0.2

[Version 1.0.2](https://github.com/Infinitode/TailClass/releases/tag/v1.0.2) fixes symlink-based path escapes and unsafe `revert --clean` deletion in 1.0.1. Upgrade from **1.0.0 or 1.0.1**, particularly when processing third-party repositories or pull requests in CI. Version 1.0.1 also introduced CSS and comment injection protections, bounded glob matching, and configuration validation. See the [changelog](https://github.com/Infinitode/TailClass/blob/v1.0.2/CHANGELOG.md) and [security policy](https://github.com/Infinitode/TailClass/blob/v1.0.2/SECURITY.md).

### Output paths and symlinks

File-configured `outputCss`, `dictionaryFile`, and `manifestFile` are checked against the real project root, including existing symlinked directories; a path that escapes the root is rejected. Backups and the auto-discovered dictionary are also checked. A symlinked directory that resolves inside the root remains usable. Explicit CLI paths such as `--output`, `--dict`, and `--report`, and programmatic path overrides, can intentionally point outside the root; use only trusted paths.

The final component of an output path must not be a symlink, even when it points inside the project, is passed explicitly, or `--force` is used. If an old configuration writes through a symlinked output file, replace the link with a regular file or configure the actual file path. `.git`, `node_modules`, and `.tailclass-backup` remain excluded from scans even with `replaceDefaultExcludes: true`.

### Overwrites and cleanup

On `apply`, existing stylesheets and manifests that do not look like TailClass output are rejected unless `--force` is supplied. Choose a separate output path rather than forcing an overwrite where possible. A dry run does not check whether existing output files are TailClass-owned; do not treat a successful preview as an overwrite-safety check. Never use `--force` without inspecting the target files and backing them up.

`revert --clean` checks ownership before removing files. It leaves files it cannot identify as TailClass output untouched, reports skipped files on stderr, and does not delete symlinks or directories. `--force` does not bypass cleanup checks. Stylesheet ownership requires parseable `@apply` rules and either a generated CSS header or matching rules in an owned manifest; the check is based on file content, not authentication. Review cleanup output and preserve backups, especially after editing generated files.

{% hint style="warning" %}
TailClass is not a sandbox. Inspect configuration, paths and symlinks, and use an isolated environment with minimal permissions and no secrets when processing untrusted projects. To report vulnerabilities privately, follow the [security policy](https://github.com/Infinitode/TailClass/blob/v1.0.2/SECURITY.md); do not open a public security issue.
{% endhint %}

## Quickstart

Run these commands from your project root. The directory argument defaults to `.`; output, dictionary, report, and configuration paths are resolved relative to the target directory, not necessarily your shell's working directory.

1. Scan without modifying files:

   ```bash
   npx tailclass scan .
   ```
2. Preview the generated CSS and source changes without writing them:

   ```bash
   npx tailclass apply . --dry-run
   ```
3. Review the preview, then generate the stylesheet and rewrite matching files. Back up modified source files as an additional precaution:

   ```bash
   npx tailclass apply . --backup
   ```

   By default this writes `tailclass.css` and `.tailclass-manifest.json` in the target directory; backups go in `.tailclass-backup/`. Commit or back up your project before applying changes, and review the resulting diff and rendered site.
4. Include the generated CSS in your main stylesheet so the Tailwind pipeline processes it. For Tailwind v4, if both stylesheets are in the project root:

   ```css
   @import "tailwindcss";
   @import "./tailclass.css";
   ```

   For Tailwind v3, include the generated file in the CSS processed by Tailwind using your project's import setup (for example, `postcss-import`) alongside the `@tailwind` directives. Adjust the import path to match the location of your main stylesheet. Use `--format tailwind-v4` for v4 output or configure `cssFormat` (the default is `tailwind-v3`). Even `plain` output uses `@apply` and requires processing by Tailwind.

By default, a pattern must have at least three utilities and occur twice, in at least one file. For example, repeated `rounded-xl border bg-white p-6 shadow-sm` layouts may be extracted to a generated `.card` rule. Names depend on the detected context and patterns; inspect the output rather than relying on a particular name.

## Audit and customize class names

Use Class List Mode to inspect utilities, occurrences, and file/line locations and create a mapping dictionary:

```bash
npx tailclass list . --report class-audit.md
```

This writes `tailclass.map.json` and a Markdown report in the target directory. Use `--report class-audit.csv` for CSV, or `--all` to include non-repeated patterns in the list. Edit a mapping's `customName` to override its suggested name, or set `enabled` to `false` to leave a qualifying pattern inline. For a non-qualifying entry added with `--all`, clear `customName` as well to disable it: in 1.0.2, a custom name can promote that entry even when `enabled` is `false`. Re-running `list` merges existing name and enabled edits by default.

You can instead provide a flat JSON dictionary. Keys may be utility strings, detected names, or pattern IDs; `false` disables a mapping:

```json
{
  "btn-primary": "brand-button",
  "nav-link": false
}
```

```bash
npx tailclass apply . --dict custom-dict.json --dry-run
```

`apply` automatically loads the configured `tailclass.map.json` if present. Use `--no-dict` to ignore it. With a generated dictionary (`mappings` array), `--strict-dict` prevents automatically adding unlisted patterns. In 1.0.2, strict mode does not filter unlisted patterns for flat dictionaries; use a generated dictionary when strict filtering is required. In list mode, `--no-write` avoids writing the dictionary and report; `--no-merge` disables merging with the existing dictionary.

## Configuration and exclusions

Create `tailclass.config.json` in the target directory:

```bash
npx tailclass init .
```

TailClass also discovers `.tailclassrc.json`, `.tailclassrc`, or a `tailclass` object in the target directory's `package.json`. Use `--config` to select a file explicitly. CLI and API options override file settings. A minimal configuration could be:

```json
{
  "include": ["src/**/*.{html,jsx,tsx,vue,svelte}"],
  "exclude": ["src/legacy/**"],
  "outputCss": "src/styles/tailclass.css",
  "cssFormat": "tailwind-v4",
  "minOccurrences": 2,
  "minClasses": 3,
  "minFiles": 1,
  "excludeClasses": ["js-*", "qa-*"],
  "subsetMatching": true
}
```

Patterns are relative to the target directory. Default exclusions include `node_modules`, build outputs, and `.tailclass-backup`; custom `exclude` entries are added to those defaults. Invalid configuration values can now produce descriptive errors, and unknown keys produce warnings on stderr (including with `--json`). Class prefixes may contain only letters, digits, hyphens, and underscores, and cannot start with a digit or a hyphen followed by a digit. Use `classPrefix`, `namingStyle` (`kebab`, `bem`, or `camel`), and `tailwindPrefix` to adapt names and utilities. Custom `rules` can match tags and utilities to suggest names; see the [configuration schema](https://github.com/Infinitode/TailClass/blob/main/schema/tailclass.config.schema.json) for all options.

To opt an individual element out, include `tc-ignore` or `no-tailclass` in its class list, or configure `excludePatterns`:

```html
<div class="tc-ignore rounded-xl border bg-white p-6 shadow-sm">Untouched</div>
```

## CLI reference

```
tailclass <command> [directory] [options]
```

| Command  | Purpose                                                                          |
| -------- | -------------------------------------------------------------------------------- |
| `scan`   | Analyze matching files without writing changes.                                  |
| `list`   | Audit patterns and generate or merge a dictionary; optionally export a report.   |
| `apply`  | Generate CSS and a manifest, and rewrite matching source files.                  |
| `revert` | Expand generated names back into utilities using the manifest and/or stylesheet. |
| `init`   | Create a starter configuration; `--force` overwrites an existing one.            |

Common options include `--dry-run`, `--backup`, `--force`, `--output` (`-o`), `--config` (`-c`), `--dict`, `--format`, `--prefix`, `--style`, `--tw-prefix`, `--min-occurrences`, `--min-classes`, `--min-files`, `--no-subset`, `--include` (`-i`), `--exclude` (`-e`), `--exclude-classes`, `--include-classes`, `--ignore-tags`, `--only-tags`, and `--json`. Quote glob arguments so the shell does not expand them. Run `npx tailclass --help` for the full CLI reference.

## Reverting changes

Preview a revert first, then expand generated names back into utility strings:

```bash
npx tailclass revert . --dry-run
npx tailclass revert .
```

Revert reads `.tailclass-manifest.json` and/or the configured output stylesheet; keep those files and use the same target directory and output configuration as the apply step. `--clean` additionally removes output files identified as TailClass-owned; skipped files are reported on stderr. It can also locate in-root paths recorded by an owned manifest if configuration has changed. Verify the paths and inspect the cleanup report; `--force` does not override the ownership checks. Revert expands classes rather than restoring an exact byte-for-byte copy of the original files; use version control or the `--backup` copies when exact restoration is needed. Review the changes before cleaning up.

## Node.js API

TailClass provides CommonJS and ES module exports and bundled TypeScript declarations. The project-level functions are synchronous:

```js
import { scanProject, generateClassList, applyAutoClasses } from "tailclass";

const { analysis } = scanProject(".", { minOccurrences: 2 });
console.log(analysis.summary);

// Inspect a dictionary without writing it.
const { dictionary } = generateClassList(".", { write: false });
console.log(dictionary.mappings);

// Preview changes without writing CSS, a manifest, or source files.
const preview = applyAutoClasses(".", { dryRun: true });
console.log(preview.cssContent, preview.totalFilesModified);
```

`revertProject(rootDir, options)` and `initConfig(rootDir, options)` provide the other project workflows. `revertProject` returns `config`, including `config.warnings` and `config.pathSources`, plus `cleanedFiles` and `cleanupSkipped` arrays when cleanup is requested. Lower-level exports include `canonicalizeClasses`, `rewriteSource`, `revertSource`, and `generateStylesheet`. See the [TypeScript declarations](https://github.com/Infinitode/TailClass/blob/main/types/index.d.ts) and [repository README](https://github.com/Infinitode/TailClass#programmatic-nodejs-api) for signatures and examples.

## Supported files and limitations

TailClass scans HTML, JavaScript and TypeScript files (including JSX/TSX), Vue, Svelte, Astro, and server templates including PHP/Blade, ERB, EJS, Handlebars, Mustache, Twig, Nunjucks, Liquid, and Jinja. It handles common class helper calls and static parts of template literals, but dynamically constructed utilities such as `` `bg-${color}-500` `` cannot be statically extracted. Review generated CSS and rewritten templates, especially dynamic expressions and project-specific classes, and test your Tailwind build.

TailClass uses a [modified MIT license](https://github.com/Infinitode/TailClass/blob/main/LICENSE); review its terms before making or distributing derivatives.
