@eightshift/frontend-libs-tailwind 3.4.0 → 4.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/CODEOWNERS +1 -1
- package/CHANGELOG.md +19 -1
- package/README.md +187 -0
- package/bin/tw-sweep.mjs +281 -0
- package/bun/build.mjs +341 -0
- package/bun/cli.mjs +77 -0
- package/bun/css.mjs +145 -0
- package/bun/discovery.mjs +121 -0
- package/bun/editor.mjs +105 -0
- package/bun/eightshift-css.mjs +66 -0
- package/bun/eightshift-discovery.mjs +135 -0
- package/bun/flat-publication.mjs +343 -0
- package/bun/index.mjs +118 -0
- package/bun/media.mjs +49 -0
- package/bun/preset.mjs +118 -0
- package/bun/publish.mjs +236 -0
- package/bun/release.mjs +182 -0
- package/{webpack/responsive-compiler.mjs → bun/responsive.mjs} +18 -39
- package/bun/ssr.mjs +89 -0
- package/bun/theme-build.mjs +464 -0
- package/bun/theme-discovery.mjs +171 -0
- package/bun/watch.mjs +211 -0
- package/bun/wordpress.mjs +173 -0
- package/linters/oxlint.config.mjs +65 -0
- package/linters/tw-ignore.mjs +45 -0
- package/linters/tw-sweep-extract.mjs +545 -0
- package/package.json +16 -16
- package/test/fixtures/theme/src/Blocks/custom/card/card.php +23 -0
- package/test/fixtures/theme/src/Blocks/custom/card/manifest.json +13 -0
- package/test/fixtures/theme/src/Plugins/Forms.php +15 -0
- package/test/fixtures/theme/src/card.js +2 -0
- package/test/fixtures/theme/tailwind.css +6 -0
- package/test/fixtures/theme/tw-ignore.json +1 -0
- package/test/tw-sweep.test.mjs +119 -0
- package/bun.lock +0 -1433
- package/webpack/base.mjs +0 -126
- package/webpack/helpers.mjs +0 -55
- package/webpack/index.mjs +0 -46
- package/webpack/production.mjs +0 -60
- package/webpack/project.mjs +0 -50
package/.github/CODEOWNERS
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
@infinum/wordpress-team
|
|
1
|
+
* @infinum/wordpress-team
|
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,23 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
|
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
9
|
+
## [4.0.0]
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- **Breaking:** the conventional theme build requires a stable WordPress 7.0 or newer installation.
|
|
14
|
+
- **Breaking:** removed the Webpack configuration, `webpack/*` API and its build dependencies. Migrate project build scripts to Bun or another independently configured build pipeline.
|
|
15
|
+
- Bun build helpers include a conventional theme preset, CSS processing and watch support. They are not a drop-in replacement for Webpack: projects must verify their layout, WordPress integration and generated asset metadata. The Tailwind lint plugin still transitively requires `tsconfig-paths-webpack-plugin` for resolution, not the Webpack bundler.
|
|
16
|
+
|
|
17
|
+
## [3.5.0]
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- `tw-sweep` CLI (`bunx tw-sweep`, also `lint:tw`): checks Tailwind classes in block manifests and PHP against the project's Tailwind entry and reports unknown and non-canonical classes. `--write` rewrites non-canonical ones. PHP sources: `class="…"` attributes, string arguments of `tailwindClasses`/`getTwPart` (after the part name), `getTwClasses`, `clsx` and `classnames`, and non-key string literals between `// tw-sweep-classes-start.` and `// tw-sweep-classes-end.` (the full stop keeps PHPCS happy; the markers match without it too).
|
|
22
|
+
- `linters/oxlint.config.mjs`: `createOxlintConfig({ entryPoint })` for oxlint with `eslint-plugin-better-tailwindcss`.
|
|
23
|
+
- `tw-ignore.json`: one unknown-class ignore list (JSON array of regex strings) read by both `tw-sweep` and `createOxlintConfig`. Invalid patterns fail loudly.
|
|
24
|
+
- lint-staged does not run commands through a shell, so chain tools as an array: `"*.js": ["bun lintJs", "bun lintJs:oxlint"]`.
|
|
25
|
+
|
|
9
26
|
## [3.4.0]
|
|
10
27
|
|
|
11
28
|
### Added
|
|
@@ -383,7 +400,8 @@ Co-authored with @piqusy
|
|
|
383
400
|
|
|
384
401
|
- Initial release.
|
|
385
402
|
|
|
386
|
-
[
|
|
403
|
+
[4.0.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.5.0...4.0.0
|
|
404
|
+
[3.5.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.4.0...3.5.0
|
|
387
405
|
[3.4.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.4.0...3.4.0
|
|
388
406
|
[3.3.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.2.0...3.3.0
|
|
389
407
|
[3.2.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.1.2...3.2.0
|
package/README.md
CHANGED
|
@@ -12,6 +12,193 @@ This library is meant to bring you the modern front-end development tools to the
|
|
|
12
12
|
## Documentation
|
|
13
13
|
**For the full documentation please check this [link](https://eightshift.com).**
|
|
14
14
|
|
|
15
|
+
## Bun build migration
|
|
16
|
+
|
|
17
|
+
The Webpack configuration and `webpack/*` imports have been removed. Projects must replace their Webpack configuration and scripts; this is a breaking change. The Bun helpers are available from `@eightshift/frontend-libs-tailwind/bun/build.mjs`, including `build`, `generateDiscovery`, `generateResponsiveClasses`, and `wordpressPlugin`.
|
|
18
|
+
|
|
19
|
+
The Bun helpers are not a drop-in replacement for Webpack. Start with the theme preset for the conventional Eightshift theme layout. Use the lower-level API below for other layouts.
|
|
20
|
+
|
|
21
|
+
The conventional theme build requires a stable WordPress 7.0 or newer installation. Each build reads `wp-includes/version.php` before modifying output and fails if the version is missing, unrecognized, or too old. By default, the WordPress root is three directories above the theme root; set `EIGHTSHIFT_WP_ROOT` to its absolute path for other layouts. The public asset URL defaults to the theme's path under that root plus `/public/`. If that does not match the site's URL layout, set `publicPrefix` in `defineThemeBuild` or `EIGHTSHIFT_PUBLIC_PREFIX` in the environment to the root-relative public URL path, including its trailing slash (for example, `/wp-content/themes/example/public/`). The option takes precedence over the environment variable. The lower-level build API does not enforce this version check.
|
|
22
|
+
|
|
23
|
+
### Migrate a conventional theme
|
|
24
|
+
|
|
25
|
+
1. Keep a working copy of your current build and compare its outputs before removing Webpack. Install a version of this library that contains the Bun build helpers, using Bun, and commit the updated lockfile when that version is available.
|
|
26
|
+
2. Replace the Webpack configuration with `eightshift.build.mjs` at the project root:
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
|
|
30
|
+
|
|
31
|
+
export default defineThemeBuild({
|
|
32
|
+
root: import.meta.dirname,
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
3. Update the relevant `package.json` scripts:
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"scripts": {
|
|
41
|
+
"start": "eightshift-build watch",
|
|
42
|
+
"build": "eightshift-build build",
|
|
43
|
+
"build:sourcemaps": "eightshift-build build --sourcemaps"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
4. Run `bun run build` and compare the generated assets and site behavior with the previous build. Use `bun run start` for an initial build and subsequent rebuilds, or `bun run build:sourcemaps` for external source maps. The CLI accepts `--config path` to select another configuration. It is `eightshift-build`, not `bun build`: the library orchestrates CSS, discovery, WordPress dependencies and publication around Bun's bundler.
|
|
49
|
+
5. Update CI and deployment to use Bun and the new scripts. Only remove Webpack dependencies and configuration after verifying the new build. Ensure the deployment environment has access to WordPress and its compatible script metadata for dependency extraction.
|
|
50
|
+
|
|
51
|
+
The default preset discovers conventional block and component assets, builds frontend, editor and admin scripts and styles, and builds conventional SSR entries when present. SVG imports in frontend and admin scripts emit files referenced by root-relative public URLs; editor SVG imports produce SVG text instead. The default build clears `public/` first, writes intermediate assets inside `public/.build`, and publishes the final assets and `public/manifest.json` directly to `public/`. Successful builds remove `public/.build`; failed builds can leave incomplete output. Do not keep manually maintained files in `public/`. Frontend and admin use classic-script bootstraps that dynamically import their bundled modules; the editor is packaged separately. Preserve the generated chunks alongside the entry scripts. The default preset always produces production-optimized assets, including in watch mode; watch does not provide hot reload. With `--sourcemaps`, external maps are generated for the editor entry and its lazy chunks as well as the browser bundles. SSR execution may still require Node in the project's PHP integration.
|
|
52
|
+
|
|
53
|
+
The manifest maps the conventional `applicationBlocksFrontend`, `applicationBlocksEditor` and `applicationAdmin` script and style keys to their generated files. Each entry also has `.asset.json` metadata containing WordPress dependency handles and a release version; the manifest maps its legacy `.json` key to that metadata as well. **The build does not enqueue assets:** confirm that your installed PHP integration reads the generated metadata and merges its dependencies with the registered handles. Existing PHP/library versions may not support this; update or adapt them before switching, and check that the frontend, editor and admin load without missing globals. Do not assume Bun's `external` option supplies WordPress global mappings.
|
|
54
|
+
|
|
55
|
+
Each build clears the previous `public/` contents. Run only one build or publication per theme at a time; output directories are not locked against concurrent builds. The PHP manifest cache update is not coordinated with PHP cache rebuilds: if they overlap, stale asset URLs can remain until the next successful build or cache reset. Build failures may leave the site without working assets; use a separate deployment process if atomic releases are required, and account for cached pages that may still request removed files. Verify block registration, editor controls and save/reload behavior, frontend styles and lazy assets, representative admin screens, script dependencies, browser console and asset URLs. Keep the previous Webpack build available for rollback until the new build is verified.
|
|
56
|
+
|
|
57
|
+
### Lower-level build API
|
|
58
|
+
|
|
59
|
+
For a nonstandard project, run the following as a project-root `build.mjs`, adapting the paths to your project:
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
import { join } from 'node:path';
|
|
63
|
+
import { build } from '@eightshift/frontend-libs-tailwind/bun/build.mjs';
|
|
64
|
+
import { processCss } from '@eightshift/frontend-libs-tailwind/bun/css.mjs';
|
|
65
|
+
import { watchBuild } from '@eightshift/frontend-libs-tailwind/bun/watch.mjs';
|
|
66
|
+
|
|
67
|
+
const root = process.cwd();
|
|
68
|
+
const production = process.argv.includes('--production');
|
|
69
|
+
const run = () => build({
|
|
70
|
+
root,
|
|
71
|
+
outdir: 'build',
|
|
72
|
+
entries: { app: 'src/app.js' },
|
|
73
|
+
wpRoot: '../../..', // WordPress root from wp-content/themes/<theme>
|
|
74
|
+
responsive: {},
|
|
75
|
+
css: async ({ outdir, responsive }) => {
|
|
76
|
+
await processCss({
|
|
77
|
+
projectDir: root,
|
|
78
|
+
outputFile: join(outdir, 'app.css'),
|
|
79
|
+
files: [{ file: 'src/tailwind.css', scan: true, scanFiles: [responsive.frontend] }],
|
|
80
|
+
production,
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
buildOptions: { minify: production },
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
if (process.argv.includes('--watch')) {
|
|
87
|
+
const watcher = watchBuild({
|
|
88
|
+
projectDir: root,
|
|
89
|
+
sources: ['src'],
|
|
90
|
+
ignored: ['build'],
|
|
91
|
+
build: run,
|
|
92
|
+
});
|
|
93
|
+
process.on('SIGINT', async () => { await watcher.stop(); process.exit(); });
|
|
94
|
+
process.on('SIGTERM', async () => { await watcher.stop(); process.exit(); });
|
|
95
|
+
} else {
|
|
96
|
+
await run();
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Run `bun run build.mjs`, add `--production` for minification, or `--watch` for an initial build followed by rebuilds. Watch covers only the listed paths, so include other inputs such as configuration files; generated output must be ignored. Directories are watched recursively, files through their parent directories, and missing sources through their nearest existing parents until they appear. Builds run serially with a 200 ms debounce; errors go to `onError` (default `console.error`). `initial: false` skips the initial build. `stop()` closes the watcher and waits for an active build. There is no development server or hot reload.
|
|
101
|
+
|
|
102
|
+
`build` requires named entries and an output directory. By default, it builds each entry separately as browser ESM with splitting and hashed filenames, writes `manifest.json` and an `<entry>/<entry>.asset.json` with dependencies and a version hash, and returns `{ outdir, entries }`. Integrate these files with your WordPress enqueue code; this package does not enqueue them. Output is staged and published only after success. An existing output directory must have the build's ownership marker, and output paths and trees cannot contain symlinks. Do not use a directory containing the project root. `buildOptions` can override Bun defaults such as `target`, `format`, `splitting`, `naming`, loaders and plugins; callers must ensure the resulting format matches their WordPress loading strategy. Entry points, output directory and write mode are controlled by the build API.
|
|
103
|
+
|
|
104
|
+
For projects that prefer a validated configuration, `createPreset` and `buildPreset` are exported from `@eightshift/frontend-libs-tailwind/bun/preset.mjs`. Pass `wordpress: false`, `discovery: false`, `responsive: false` or `css: false` to disable the corresponding feature; discovery, responsive generation and CSS are opt-in. Configure CSS surfaces or pass a custom CSS callback. `buildOptions` accepts the same overrides as `build`. When an editor entry is enabled, `buildOptions.sourcemap` supports only `none` and `external`. The editor entry and each lazy chunk are bundled separately: modules included in more than one bundle may initialize more than once and have separate state. Avoid relying on shared module identity or one-time side effects across those bundles.
|
|
105
|
+
|
|
106
|
+
For `defineBuild` watch configurations with `ssr` or `publish` callbacks, explicitly set `watch.sources` or `watch.ignored`. Exclude every path those callbacks write inside the project root, including paths outside the preset output directory, to avoid rebuild loops.
|
|
107
|
+
|
|
108
|
+
`defineThemeBuild` from `bun/theme-build.mjs` supplies the conventional theme layout and flat publication. `entries` replaces the complete entry map; `editor` replaces the editor preset or may be `false`. `responsive` accepts the preset's options or `false`. `css` accepts an async callback receiving `{ root, outdir, stage, responsive, require }` or `false`; `extraCss` still runs afterwards. `discovery` accepts a plugin factory receiving `{ root, setEditorWorker, getEditorWorker }` (also async) or `false`; with either override, callers must provide discovery compatible with their entry sources. `frontendStyles` applies only to default discovery. The built-in editor worker plugin runs before plugins returned by `createPlugins`; replace it via `media.editorWorker` when custom handling is needed. The returned plugin array is not modified. `ssr` replaces `buildSsr` or can be `false`; do not specify both. `publish` replaces the flat publisher with an async callback receiving the build state, or `false` leaves the intermediate build unpublished in `public/.build`. With custom or disabled publication, the SSR callback runs after the browser build and receives the build state and `mode: 'production'`.
|
|
109
|
+
|
|
110
|
+
### Additional and lazy stylesheets
|
|
111
|
+
|
|
112
|
+
Use `extraCss` to compile ordered stylesheets separately from the standard frontend, editor and admin CSS. This is useful for a library used by only one frontend component:
|
|
113
|
+
|
|
114
|
+
```js
|
|
115
|
+
import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
|
|
116
|
+
|
|
117
|
+
export default defineThemeBuild({
|
|
118
|
+
root: import.meta.dirname,
|
|
119
|
+
extraCss: [{
|
|
120
|
+
files: ['package:@vidstack/react/player/styles/base.css'],
|
|
121
|
+
keys: ['components/video'],
|
|
122
|
+
}],
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- `files` is a non-empty array processed in order. Paths are relative to the project root; absolute paths and `package:` module specifiers are also supported. Each item may instead be a `processCss` options object with a `file` property.
|
|
127
|
+
- `output` is optional. By default the filename is `extra-<hash>.css`, using the first 20 hexadecimal characters of the SHA-256 hash of the compiled CSS bytes. Set `output: 'video.css'` for a stable filename. Names must be flat CSS filenames and must not collide with other outputs.
|
|
128
|
+
- `keys` optionally lists frontend importer keys, such as `components/video` or `custom/example`. Each must match a discovered `src/Blocks/{components,custom}/**/assets/index.js` file, and a key can belong to only one stylesheet group. When an importer is used, its stylesheet loads before the JavaScript; the load is shared between callers. A failed load rejects, removes the link, and can be retried. Without `keys`, the file is built and published but is not loaded automatically.
|
|
129
|
+
- `href` optionally overrides the URL used by those importers. By default it points to the generated output; custom URLs must be deployed and kept in sync by the project. It has no effect without `keys`.
|
|
130
|
+
|
|
131
|
+
The default flat publisher includes generated stylesheets in `public/` and its manifest; no alias is required for lazy loading. The output hash changes when compiled CSS changes, including rewritten asset URLs. CSS assets are copied with their own content-hashed names. Publication replaces `public/`, so cached older pages can request files no longer present; retain old releases externally if that matters. For a stable PHP manifest key, set an explicit `output` and an appropriate `aliases` entry. Custom publishers must preserve the CSS and the URL expected by the importer.
|
|
132
|
+
|
|
133
|
+
The build regenerates discovery and CSS on each rebuild. Watch monitors the configured project paths, not `node_modules` or arbitrary external files by default; customize `watch.sources` for additional inputs. Default theme builds use production CSS processing, including Lightning CSS minification and its browser targets, even in watch mode. `extraCss` may also be an async hook receiving `{ root, stage, require }`, or `false` to disable it. Hooks are responsible for their own filenames and loading behavior. `frontendStyles` separately attaches existing URLs to keys; both automatic mechanisms require default discovery.
|
|
134
|
+
|
|
135
|
+
Default flat publication requires frontend, admin and editor entries, an editor build, and CSS at the conventional filenames. It scans the conventional SSR source glob and expects matching outputs in `public/.build/ssr/production`; use `ssr: false` to omit SSR or supply custom publication for a different layout. Disabling responsive generation requires custom or disabled CSS. Custom publication is required when disabling CSS or the editor, or changing the entry set. With custom or disabled publication, intermediate output remains in `public/.build`; the project owns its publication and cleanup.
|
|
136
|
+
|
|
137
|
+
WordPress externalization is enabled by default. Set `wpRoot` to the WordPress installation when using externalized `@wordpress/*` imports; export discovery reads its core scripts and requires compatible installed package metadata. The adapter also maps React and selected common dependencies to WordPress globals. Those globals and script handles must be available at runtime. Set `wordpress: false` to disable this adapter. For direct Bun integration, `wordpressPlugin({ projectRoot, wpRoot })` returns `{ plugin, dependencies }`; use a fresh adapter for each build and absolute paths.
|
|
138
|
+
|
|
139
|
+
`processCss` compiles the `files` array in order into one output file. Each item is a path or `{ file, scan, sources, scanFiles, removeSources }`: scanning is opt-in; `sources` adds Tailwind scanner source objects, `scanFiles` adds explicit candidate files, and `removeSources` removes exact source-rule strings (and fails if absent). Relative paths resolve from `projectDir`. Local URL assets are copied next to the CSS with content-hashed names. Production uses Lightning CSS and the `browsers` option (default `>= 0.25%`); the return value includes `outputFile` and discovered `dependencies`. Watch does not automatically use those dependencies. `responsive: {}` generates frontend and editor class lists from `src/**/manifest.json`, expanding responsive classes for `sm` and `md`; customize `breakpoints`, `manifestGlob`, and `output`. Pass the relevant generated list to CSS scanning, as above. The standalone `generateResponsiveClasses({ projectDir, ... })` is also exported from `bun/build.mjs`.
|
|
140
|
+
|
|
141
|
+
For Webpack context replacements, generate a module before building and import its named context in your application:
|
|
142
|
+
|
|
143
|
+
```js
|
|
144
|
+
import { generateDiscovery } from '@eightshift/frontend-libs-tailwind/bun/build.mjs';
|
|
145
|
+
|
|
146
|
+
await generateDiscovery({
|
|
147
|
+
root: process.cwd(),
|
|
148
|
+
output: 'src/generated/blocks.mjs',
|
|
149
|
+
definitions: [{ name: 'blocks', directory: 'src/blocks', pattern: /\.js$/, mode: 'sync' }],
|
|
150
|
+
});
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The generated `blocks` function accepts keys such as `./card.js`, and `blocks.keys()` lists them. `mode: 'lazy'` returns promises; synchronous JSON returns parsed values, JS returns module namespaces, and synchronous CSS imports are side effects returning an empty object. Lazy CSS is unsupported. Missing directories produce empty contexts and symlinks are skipped. Regenerate when files are added or removed; if generated files are watched, exclude them to avoid rebuild loops. Alternatively, `build` accepts `discovery: { output, definitions }` and generates the module inside its staging output, exposed as `discovery` to the CSS callback; its output path must be relative to staging, not a stable source import path. Responsive outputs are likewise staged and published.
|
|
154
|
+
|
|
155
|
+
Verify your assets, WordPress dependencies, CSS and development workflow before migrating. The Tailwind lint plugin still transitively installs `tsconfig-paths-webpack-plugin` for module resolution; the Webpack bundler and former Webpack build plugins are not installed by this package.
|
|
156
|
+
|
|
157
|
+
## Tailwind class linting
|
|
158
|
+
|
|
159
|
+
Two tools check classes against your project's own Tailwind entry: oxlint for JS, and `tw-sweep` for block manifests and PHP. Both read one ignore list.
|
|
160
|
+
|
|
161
|
+
1. Add `oxlint` to your project's `devDependencies`. Isolated installs (pnpm, `bun --linker isolated`) do not expose this package's binaries.
|
|
162
|
+
2. Create `oxlint.config.ts`:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import { defineConfig } from 'oxlint';
|
|
166
|
+
import { createOxlintConfig } from '@eightshift/frontend-libs-tailwind/linters/oxlint.config.mjs';
|
|
167
|
+
|
|
168
|
+
export default defineConfig(createOxlintConfig({ entryPoint: 'tailwind.css' }));
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
3. Create `tw-ignore.json` for classes that are not Tailwind utilities (JS hooks, BEM selectors, other design-system prefixes). It is a JSON array of regex strings; an invalid pattern stops both tools:
|
|
172
|
+
|
|
173
|
+
```json
|
|
174
|
+
["^es:", "^js-", "^my-block__"]
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
4. Wire the scripts. lint-staged does not run commands through a shell, so use an array instead of `&&`:
|
|
178
|
+
|
|
179
|
+
```json
|
|
180
|
+
"scripts": {
|
|
181
|
+
"lintJs:oxlint": "oxlint",
|
|
182
|
+
"lintTw": "tw-sweep",
|
|
183
|
+
"test": "bun run lintJs && bun run lintJs:oxlint && bun run lintTw"
|
|
184
|
+
},
|
|
185
|
+
"lint-staged": {
|
|
186
|
+
"*.js": ["bun lintJs", "bun lintJs:oxlint"],
|
|
187
|
+
"src/Blocks/**/manifest.json": "tw-sweep",
|
|
188
|
+
"src/**/*.php": "tw-sweep"
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
`tw-sweep` reports unknown and non-canonical classes; `tw-sweep --write` rewrites the non-canonical ones. In PHP it reads static `class="…"` attributes and the string arguments of `tailwindClasses`, `getTwPart`, `getTwClasses`, `clsx` and `classnames`. For class maps that no helper wraps, such as selectors returned from a filter, mark the code:
|
|
193
|
+
|
|
194
|
+
```php
|
|
195
|
+
// tw-sweep-classes-start.
|
|
196
|
+
$selectors['field']['parts']['label'] = ['flex items-center text-body-sm'];
|
|
197
|
+
// tw-sweep-classes-end.
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Every string literal between the markers that is not an array key is checked. Run `tw-sweep --help` for all flags.
|
|
201
|
+
|
|
15
202
|
## Who do I talk to?
|
|
16
203
|
|
|
17
204
|
If you have any questions or problems, please [open an issue](https://github.com/infinum/eightshift-frontend-libs/issues) on GitHub and we will do our best to give you a timely answer.
|
package/bin/tw-sweep.mjs
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// bin/tw-sweep.mjs
|
|
3
|
+
// Project-wide Tailwind class check for sources oxlint cannot read:
|
|
4
|
+
// block manifests and PHP. Reports classes the design system does not know
|
|
5
|
+
// (unknown) and classes with a canonical spelling (non-canonical), using
|
|
6
|
+
// @tailwindcss/node against the project's own Tailwind entry.
|
|
7
|
+
|
|
8
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
10
|
+
import { resolve, relative } from 'node:path';
|
|
11
|
+
import process from 'node:process';
|
|
12
|
+
import { glob } from 'glob';
|
|
13
|
+
import { __unstable__loadDesignSystem } from '@tailwindcss/node';
|
|
14
|
+
import { extractGroups, REGION_START, REGION_END } from '../linters/tw-sweep-extract.mjs';
|
|
15
|
+
import { loadTwIgnore, TW_IGNORE_FILE } from '../linters/tw-ignore.mjs';
|
|
16
|
+
|
|
17
|
+
const EXIT_OK = 0;
|
|
18
|
+
const EXIT_VIOLATIONS = 1;
|
|
19
|
+
const EXIT_USAGE = 2;
|
|
20
|
+
|
|
21
|
+
function parseArgs(argv) {
|
|
22
|
+
const opts = {
|
|
23
|
+
files: [],
|
|
24
|
+
include: null,
|
|
25
|
+
exclude: null,
|
|
26
|
+
entry: null,
|
|
27
|
+
ignoreFile: TW_IGNORE_FILE,
|
|
28
|
+
unknown: true,
|
|
29
|
+
write: false,
|
|
30
|
+
rootFontSize: 16,
|
|
31
|
+
help: false,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
for (let i = 0; i < argv.length; i++) {
|
|
35
|
+
const a = argv[i];
|
|
36
|
+
|
|
37
|
+
if (a === '--entry') opts.entry = argv[++i];
|
|
38
|
+
else if (a === '--include') opts.include = argv[++i].split(',').map((s) => s.trim());
|
|
39
|
+
else if (a === '--exclude') opts.exclude = argv[++i].split(',').map((s) => s.trim());
|
|
40
|
+
else if (a === '--ignore-file') opts.ignoreFile = argv[++i];
|
|
41
|
+
else if (a === '--no-unknown') opts.unknown = false;
|
|
42
|
+
else if (a === '--root-font-size') opts.rootFontSize = Number(argv[++i]);
|
|
43
|
+
else if (a === '--write') opts.write = true;
|
|
44
|
+
else if (a === '--check') opts.write = false;
|
|
45
|
+
else if (a === '-h' || a === '--help') opts.help = true;
|
|
46
|
+
else if (a.startsWith('--')) {
|
|
47
|
+
console.error(`Unknown flag: ${a}`);
|
|
48
|
+
process.exit(EXIT_USAGE);
|
|
49
|
+
} else {
|
|
50
|
+
opts.files.push(a);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return opts;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function printHelp() {
|
|
58
|
+
console.log(`tw-sweep — find unknown and non-canonical Tailwind classes in manifests and PHP
|
|
59
|
+
|
|
60
|
+
Usage:
|
|
61
|
+
tw-sweep [flags] [file...]
|
|
62
|
+
|
|
63
|
+
Flags:
|
|
64
|
+
--entry <path> Tailwind CSS entry. Default: the first ./tailwind.css, tailwind-frontend.css
|
|
65
|
+
or tailwind-editor.css that imports 'tailwindcss', searched upward,
|
|
66
|
+
then wp-content/themes/*. Files without that import are skipped.
|
|
67
|
+
--include <glob,...> Globs to scan (default: src/Blocks/**/manifest.json, src/**/*.php).
|
|
68
|
+
--exclude <glob,...> Extra globs to skip (always skipped: public, node_modules, vendor*).
|
|
69
|
+
--ignore-file <path> Unknown-class ignore list, a JSON array of regex strings
|
|
70
|
+
(default: ./${TW_IGNORE_FILE}; shared with the oxlint config).
|
|
71
|
+
--no-unknown Only report non-canonical classes.
|
|
72
|
+
--root-font-size <px> For canonicalization (default: 16).
|
|
73
|
+
--write Rewrite non-canonical classes in place. Unknown classes are
|
|
74
|
+
only reported.
|
|
75
|
+
--check Report only (default).
|
|
76
|
+
-h, --help This help.
|
|
77
|
+
|
|
78
|
+
Sources: manifest twClasses* strings; PHP class="…" attributes; string arguments of
|
|
79
|
+
tailwindClasses/getTwPart (after the part name), getTwClasses, clsx and classnames;
|
|
80
|
+
and every non-key string literal between // ${REGION_START}. and // ${REGION_END}.
|
|
81
|
+
Values that contain PHP, $ interpolation or % placeholders are skipped.
|
|
82
|
+
|
|
83
|
+
Exit codes: 0 clean, 1 violations, 2 usage error.
|
|
84
|
+
`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// A usable entry imports Tailwind itself. Projects often keep theme tokens in a
|
|
88
|
+
// tailwind.css that the real (prefixed) entry imports; using that file would
|
|
89
|
+
// report every class as unknown.
|
|
90
|
+
function importsTailwind(path) {
|
|
91
|
+
return existsSync(path) && /@import\s+(['"])tailwindcss\1/.test(readFileSync(path, 'utf8'));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function findDefaultEntry(cwd) {
|
|
95
|
+
const candidates = ['tailwind.css', 'tailwind-frontend.css', 'tailwind-editor.css'];
|
|
96
|
+
|
|
97
|
+
for (let dir = cwd; ; dir = resolve(dir, '..')) {
|
|
98
|
+
for (const name of candidates) {
|
|
99
|
+
if (importsTailwind(resolve(dir, name))) return resolve(dir, name);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const wpThemes = resolve(dir, 'wp-content/themes');
|
|
103
|
+
|
|
104
|
+
if (existsSync(wpThemes)) {
|
|
105
|
+
for (const theme of readdirSync(wpThemes)) {
|
|
106
|
+
for (const name of candidates) {
|
|
107
|
+
if (importsTailwind(resolve(wpThemes, theme, name))) return resolve(wpThemes, theme, name);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (resolve(dir, '..') === dir) return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function offsetToLineCol(content, offset) {
|
|
117
|
+
const before = content.slice(0, offset);
|
|
118
|
+
const line = before.split('\n').length;
|
|
119
|
+
|
|
120
|
+
return { line, col: offset - before.lastIndexOf('\n') };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// CSS.escape (CSSOM spec), which Tailwind also uses for class selectors.
|
|
124
|
+
function cssEscape(value) {
|
|
125
|
+
let out = '';
|
|
126
|
+
|
|
127
|
+
for (let i = 0; i < value.length; i++) {
|
|
128
|
+
const code = value.charCodeAt(i);
|
|
129
|
+
const char = value[i];
|
|
130
|
+
|
|
131
|
+
if (code === 0) {
|
|
132
|
+
out += '\uFFFD';
|
|
133
|
+
} else if ((code >= 0x1 && code <= 0x1f) || code === 0x7f || (i === 0 && code >= 0x30 && code <= 0x39) || (i === 1 && code >= 0x30 && code <= 0x39 && value.charCodeAt(0) === 0x2d)) {
|
|
134
|
+
out += `\\${code.toString(16)} `;
|
|
135
|
+
} else if (i === 0 && value.length === 1 && char === '-') {
|
|
136
|
+
out += `\\${char}`;
|
|
137
|
+
} else if (code >= 0x80 || char === '-' || char === '_' || /[0-9A-Za-z]/.test(char)) {
|
|
138
|
+
out += char;
|
|
139
|
+
} else {
|
|
140
|
+
out += `\\${char}`;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function main() {
|
|
148
|
+
const args = parseArgs(process.argv.slice(2));
|
|
149
|
+
|
|
150
|
+
if (args.help) {
|
|
151
|
+
printHelp();
|
|
152
|
+
return EXIT_OK;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const cwd = process.cwd();
|
|
156
|
+
const entryPath = args.entry ? resolve(cwd, args.entry) : findDefaultEntry(cwd);
|
|
157
|
+
|
|
158
|
+
if (!entryPath || !existsSync(entryPath)) {
|
|
159
|
+
console.error(entryPath ? `Entry CSS not found: ${entryPath}` : "Could not locate a Tailwind CSS entry that imports 'tailwindcss'. Pass --entry <path>.");
|
|
160
|
+
return EXIT_USAGE;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
let ignore;
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
ignore = loadTwIgnore(args.ignoreFile, cwd).map((pattern) => new RegExp(pattern));
|
|
167
|
+
} catch (error) {
|
|
168
|
+
console.error(error.message);
|
|
169
|
+
return EXIT_USAGE;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let files;
|
|
173
|
+
|
|
174
|
+
if (args.files.length) {
|
|
175
|
+
files = args.files.map((f) => resolve(cwd, f));
|
|
176
|
+
} else {
|
|
177
|
+
const includes = args.include ?? ['src/Blocks/**/manifest.json', 'src/**/*.php'];
|
|
178
|
+
const excludes = ['public/**', 'node_modules/**', 'vendor/**', 'vendor-prefixed/**', ...(args.exclude ?? [])];
|
|
179
|
+
const found = new Set();
|
|
180
|
+
|
|
181
|
+
for (const pattern of includes) {
|
|
182
|
+
for (const m of await glob(pattern, { cwd, ignore: excludes, absolute: true })) found.add(m);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
files = [...found].sort();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (files.length === 0) {
|
|
189
|
+
process.stderr.write('No files matched.\n');
|
|
190
|
+
return EXIT_OK;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const ds = await __unstable__loadDesignSystem(await readFile(entryPath, 'utf8'), { base: resolve(entryPath, '..') });
|
|
194
|
+
const verdicts = new Map();
|
|
195
|
+
|
|
196
|
+
// Selectors and at-rule preludes of a class's CSS, with the class name
|
|
197
|
+
// replaced by a placeholder. Values may legitimately change under
|
|
198
|
+
// canonicalization (16px → calc(var(--spacing) * 16) with a 1px spacing
|
|
199
|
+
// token); selectors must not. Canonicalizing arbitrary variants can drop
|
|
200
|
+
// `\_` escapes or wrap the selector in :where(), which changes the result.
|
|
201
|
+
const selectorShape = (className) => {
|
|
202
|
+
const css = ds.candidatesToCss([className])[0] ?? '';
|
|
203
|
+
|
|
204
|
+
return css
|
|
205
|
+
.replaceAll(`.${cssEscape(className)}`, '.X')
|
|
206
|
+
.split('{')
|
|
207
|
+
.slice(0, -1)
|
|
208
|
+
.map((part) => part.split(/[;}]/).pop().trim())
|
|
209
|
+
.join(' { ');
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
// One class at a time: batches drop unknown classes and merge pairs
|
|
213
|
+
// (top-0 bottom-0 → inset-y-0), which would break token alignment.
|
|
214
|
+
const judge = (className) => {
|
|
215
|
+
if (!verdicts.has(className)) {
|
|
216
|
+
if (ignore.some((re) => re.test(className))) {
|
|
217
|
+
verdicts.set(className, { ok: true });
|
|
218
|
+
} else if (ds.candidatesToCss([className])[0] === null) {
|
|
219
|
+
verdicts.set(className, { unknown: true });
|
|
220
|
+
} else {
|
|
221
|
+
const [canonical] = ds.canonicalizeCandidates([className], { rem: args.rootFontSize });
|
|
222
|
+
const safe = canonical && canonical !== className && selectorShape(canonical) === selectorShape(className);
|
|
223
|
+
|
|
224
|
+
verdicts.set(className, safe ? { canonical } : { ok: true });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return verdicts.get(className);
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
let unknownCount = 0;
|
|
232
|
+
let canonicalCount = 0;
|
|
233
|
+
|
|
234
|
+
for (const file of files) {
|
|
235
|
+
const content = await readFile(file, 'utf8');
|
|
236
|
+
const rel = relative(cwd, file);
|
|
237
|
+
const replacements = [];
|
|
238
|
+
|
|
239
|
+
for (const group of extractGroups(content, file)) {
|
|
240
|
+
for (const token of group.tokens) {
|
|
241
|
+
const verdict = judge(token.className);
|
|
242
|
+
const { line, col } = offsetToLineCol(content, token.start);
|
|
243
|
+
|
|
244
|
+
if (verdict.unknown && args.unknown) {
|
|
245
|
+
console.log(`${rel}:${line}:${col} unknown ${token.className}`);
|
|
246
|
+
unknownCount++;
|
|
247
|
+
} else if (verdict.canonical) {
|
|
248
|
+
console.log(`${rel}:${line}:${col} ${token.className} → ${verdict.canonical}`);
|
|
249
|
+
replacements.push({ ...token, canonical: verdict.canonical });
|
|
250
|
+
canonicalCount++;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (args.write && replacements.length) {
|
|
256
|
+
let next = content;
|
|
257
|
+
|
|
258
|
+
for (const r of replacements.sort((a, b) => b.start - a.start)) {
|
|
259
|
+
next = next.slice(0, r.start) + (r.encode ? r.encode(r.canonical) : r.canonical) + next.slice(r.end);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
await writeFile(file, next, 'utf8');
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (unknownCount + canonicalCount === 0) {
|
|
267
|
+
return EXIT_OK;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
console.error(`\n${unknownCount} unknown, ${canonicalCount} non-canonical class(es)${args.write ? ' (non-canonical rewritten)' : ''}.`);
|
|
271
|
+
|
|
272
|
+
return unknownCount > 0 || !args.write ? EXIT_VIOLATIONS : EXIT_OK;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
main().then(
|
|
276
|
+
(code) => process.exit(code),
|
|
277
|
+
(err) => {
|
|
278
|
+
console.error(err && err.stack ? err.stack : String(err));
|
|
279
|
+
process.exit(EXIT_USAGE);
|
|
280
|
+
},
|
|
281
|
+
);
|