@better-css-modules/core 0.1.3 → 0.2.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @better-css-modules/core
2
2
 
3
- Core library for better-css-modules. Provides CSS Modules parsing, type definition generation, unused class detection, file watching, and a webpack loader.
3
+ The analysis behind better-css-modules: config loading, `.d.ts` generation and the checks. The CLI and every bundler plugin are built on it. Install it next to them for `defineConfig`, which the config file imports.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,61 +8,54 @@ Core library for better-css-modules. Provides CSS Modules parsing, type definiti
8
8
  pnpm add -D @better-css-modules/core
9
9
  ```
10
10
 
11
- ## API
11
+ ## The config file
12
12
 
13
13
  ```ts
14
- import {
15
- defineConfig,
16
- loadConfig,
17
- extractClassNames,
18
- parseFile,
19
- generateDts,
20
- writeDts,
21
- generateAll,
22
- scanUnusedClasses,
23
- startWatcher,
24
- } from "@better-css-modules/core";
25
-
26
- // Extract class names from CSS
27
- const classNames = extractClassNames(".container { color: red; }");
28
- // => ['container']
29
-
30
- // Generate .d.ts content
31
- const dts = generateDts(classNames);
32
-
33
- // Generate all .d.ts files based on config
34
- const config = await loadConfig(process.cwd());
35
- await generateAll(config, process.cwd());
14
+ // better-css-modules.config.ts
15
+ import { defineConfig } from "@better-css-modules/core";
36
16
 
37
- // Detect unused class names
38
- const warnings = await scanUnusedClasses(process.cwd());
17
+ export default defineConfig({
18
+ globalCss: ["./src/globals.css"],
19
+ layer: "components",
20
+ });
39
21
  ```
40
22
 
41
- ## webpack Loader
23
+ `defineConfig` returns the config as it is and types it. The settings are described in the [project README](https://github.com/k35o/better-css-modules#configuration).
42
24
 
43
- A webpack-compatible loader is available at `@better-css-modules/core/loader`. This is used internally by `@better-css-modules/turbopack` for Turbopack integration.
44
-
45
- ## Configuration
25
+ ## API
46
26
 
47
27
  ```ts
48
- import { defineConfig } from "@better-css-modules/core";
28
+ import {
29
+ check,
30
+ ConfigError,
31
+ formatDiagnostic,
32
+ generate,
33
+ loadConfig,
34
+ } from "@better-css-modules/core";
49
35
 
50
- export default defineConfig({
51
- include: ["src/**/*.module.css"],
52
- exclude: [],
53
- outDir: "__generated__",
54
- watch: false,
55
- silent: false,
56
- });
36
+ try {
37
+ const config = await loadConfig();
38
+ const { files } = await generate(config);
39
+ const { diagnostics, modules, tokens } = await check(config);
40
+ for (const diagnostic of diagnostics) console.log(formatDiagnostic(diagnostic, process.cwd()));
41
+ console.log(`${files.length} types, ${modules} modules, tokens: ${tokens.join(", ")}`);
42
+ } catch (error) {
43
+ if (!(error instanceof ConfigError)) throw error;
44
+ console.error(error.message);
45
+ process.exitCode = 2;
46
+ }
57
47
  ```
58
48
 
59
- | Option | Type | Default | Description |
60
- | --------- | ---------- | ------------------------- | -------------------------------------------- |
61
- | `include` | `string[]` | `["src/**/*.module.css"]` | Glob patterns for target CSS Modules files |
62
- | `exclude` | `string[]` | `[]` | Glob patterns to exclude |
63
- | `outDir` | `string` | `"__generated__"` | Output directory for generated `.d.ts` files |
64
- | `watch` | `boolean` | `false` | Enable watch mode (CLI only) |
65
- | `silent` | `boolean` | `false` | Suppress console output |
49
+ - `loadConfig({ cwd?, config? })` loads the config file `config` names, relative to `cwd`, or the `better-css-modules.config.*` in `cwd` (by default the working directory), and returns it as a `ResolvedConfig`: the defaults filled in, checked, and with `root`, the directory every relative path starts from, and `file`, the config file or `null`.
50
+ - `generate(config)` writes the `.d.ts` files and their declaration maps, removes the ones it wrote for stylesheets that are gone, and returns a `GenerateResult`: `files`, `removed` and the syntax `diagnostics`.
51
+ - `check(config)` runs every check and returns a `CheckResult`: the sorted `diagnostics`, how many `modules` it checked, and the token categories (`tokens`) the global CSS restricts.
52
+ - `formatDiagnostic(diagnostic, cwd)` gives the `file:line:col error rule: message` line of the CLI, and `formatGitHubAnnotation(diagnostic, cwd)` the GitHub Actions workflow command of `--format github`.
53
+ - `ConfigError` is a mistake in the config or in the files it names. `loadConfig` throws it, and so does `check` when `include` matches no file, the global CSS cannot be read, or it does not declare the `layer`.
54
+ - The types `Config`, `ResolvedConfig`, `GenerateResult`, `CheckResult`, `Diagnostic` and `RuleId` describe these.
55
+
56
+ `@better-css-modules/core/internal` holds what the CLI and the plugins share. It is for those packages only and outside semver.
57
+
58
+ The rules `check` reports are described in the [project README](https://github.com/k35o/better-css-modules#rules).
66
59
 
67
60
  ## License
68
61
 
@@ -0,0 +1,276 @@
1
+ import "postcss";
2
+ //#region src/config.d.ts
3
+ /** The config as written in `better-css-modules.config.*`; every key is optional. */
4
+ interface Config {
5
+ /** Glob patterns for target files */
6
+ include?: string[];
7
+ /** Exclusion patterns */
8
+ exclude?: string[];
9
+ /** Output directory, inside the project root */
10
+ outDir?: string;
11
+ /** Leave out the progress lines; diagnostics and errors are always printed */
12
+ silent?: boolean;
13
+ /**
14
+ * Declare the classes as named exports instead of a default export, as
15
+ * webpack's css-loader and Rspack's built-in CSS export them by default.
16
+ */
17
+ namedExports?: boolean;
18
+ /**
19
+ * Global stylesheets that declare the design tokens, in cascade order:
20
+ * `./` or `../` paths relative to the config, or package specifiers.
21
+ */
22
+ globalCss?: string[];
23
+ /** Cascade layer the bundler plugins wrap every CSS Modules file in; unset leaves files as written */
24
+ layer?: string;
25
+ }
26
+ /** The config with its defaults filled in, checked, and tied to the project root. */
27
+ interface ResolvedConfig {
28
+ /** The directory every relative path is resolved against: the config file's, or the cwd without one. */
29
+ root: string;
30
+ /** Absolute path of the config file, or null without one. */
31
+ file: string | null;
32
+ include: string[];
33
+ exclude: string[];
34
+ /** Relative to `root`, with `/` separators; `"."` puts each `.d.ts` next to its stylesheet. */
35
+ outDir: string;
36
+ silent: boolean;
37
+ namedExports: boolean;
38
+ globalCss: string[];
39
+ layer?: string;
40
+ }
41
+ /** A mistake in the config or the files it names, which stops generating or checking. */
42
+ declare class ConfigError extends Error {
43
+ name: string;
44
+ }
45
+ declare function defineConfig(config: Config): Config;
46
+ /**
47
+ * Load the config file `config` names, or the one in `cwd` when it names none,
48
+ * and resolve it. Without a config file the defaults apply, rooted at `cwd`.
49
+ */
50
+ declare function loadConfig({ cwd, config }?: {
51
+ cwd?: string;
52
+ config?: string;
53
+ }): Promise<ResolvedConfig>;
54
+ //#endregion
55
+ //#region src/tokens.d.ts
56
+ /**
57
+ * The categories of design tokens. A custom property belongs to a category by
58
+ * its name: `--<category>` itself or `--<category>-*`. This table is the single
59
+ * definition of what each category covers; the README lists it for users.
60
+ */
61
+ declare const tokenCategories: {
62
+ color: {
63
+ properties: {
64
+ color: "colors";
65
+ "background-color": "colors";
66
+ "outline-color": "colors";
67
+ "text-decoration-color": "colors";
68
+ "text-emphasis-color": "colors";
69
+ "column-rule-color": "colors";
70
+ "caret-color": "colors";
71
+ "accent-color": "colors";
72
+ "scrollbar-color": "colors";
73
+ fill: "colors";
74
+ stroke: "colors";
75
+ "stop-color": "colors";
76
+ "flood-color": "colors";
77
+ "lighting-color": "colors";
78
+ "-webkit-text-fill-color": "colors";
79
+ "-webkit-text-stroke-color": "colors";
80
+ "-webkit-tap-highlight-color": "colors";
81
+ background: "layer-color";
82
+ outline: "layer-color";
83
+ "text-decoration": "layer-color";
84
+ "text-emphasis": "layer-color";
85
+ "column-rule": "layer-color";
86
+ "-webkit-text-stroke": "layer-color";
87
+ "box-shadow": "shadow-color";
88
+ "text-shadow": "shadow-color";
89
+ "background-image": "gradient-colors";
90
+ "border-image": "gradient-colors";
91
+ "border-image-source": "gradient-colors";
92
+ };
93
+ keywords: string[];
94
+ };
95
+ spacing: {
96
+ properties: {
97
+ inset: "value";
98
+ top: "value";
99
+ right: "value";
100
+ bottom: "value";
101
+ left: "value";
102
+ "inset-block": "value";
103
+ "inset-block-start": "value";
104
+ "inset-block-end": "value";
105
+ "inset-inline": "value";
106
+ "inset-inline-start": "value";
107
+ "inset-inline-end": "value";
108
+ gap: "value";
109
+ "row-gap": "value";
110
+ "column-gap": "value";
111
+ };
112
+ keywords: string[];
113
+ percentages: true;
114
+ };
115
+ radius: {
116
+ properties: {
117
+ "border-radius": "value";
118
+ "border-top-left-radius": "value";
119
+ "border-top-right-radius": "value";
120
+ "border-bottom-right-radius": "value";
121
+ "border-bottom-left-radius": "value";
122
+ "border-start-start-radius": "value";
123
+ "border-start-end-radius": "value";
124
+ "border-end-start-radius": "value";
125
+ "border-end-end-radius": "value";
126
+ };
127
+ keywords: never[];
128
+ percentages: true;
129
+ };
130
+ shadow: {
131
+ properties: {
132
+ "box-shadow": "shadows";
133
+ "text-shadow": "shadows";
134
+ };
135
+ keywords: string[];
136
+ };
137
+ "font-size": {
138
+ properties: {
139
+ "font-size": "value";
140
+ font: "font";
141
+ };
142
+ keywords: never[];
143
+ };
144
+ "font-weight": {
145
+ properties: {
146
+ "font-weight": "value";
147
+ font: "font";
148
+ };
149
+ keywords: string[];
150
+ };
151
+ "line-height": {
152
+ properties: {
153
+ "line-height": "value";
154
+ font: "font";
155
+ };
156
+ keywords: string[];
157
+ };
158
+ "z-index": {
159
+ properties: {
160
+ "z-index": "value";
161
+ };
162
+ keywords: string[];
163
+ };
164
+ duration: {
165
+ properties: {
166
+ "transition-duration": "value";
167
+ "transition-delay": "value";
168
+ "animation-duration": "value";
169
+ "animation-delay": "value";
170
+ transition: "times";
171
+ animation: "times";
172
+ };
173
+ keywords: string[];
174
+ };
175
+ breakpoint: {
176
+ properties: {};
177
+ keywords: never[];
178
+ };
179
+ };
180
+ type TokenCategory = keyof typeof tokenCategories;
181
+ //#endregion
182
+ //#region src/rules.d.ts
183
+ /** Every rule but the token categories, with how it can be disabled. */
184
+ declare const RULES: {
185
+ readonly "usage/unused-class": "either";
186
+ readonly "usage/unused-module": "file-wide";
187
+ readonly "usage/unanalyzable": "file-wide";
188
+ readonly "pure/selector": "either";
189
+ readonly "pure/subject": "either";
190
+ readonly "pure/global": "either";
191
+ readonly "pure/id": "either";
192
+ readonly "pure/important": "either";
193
+ readonly "pure/at-rule": "either";
194
+ readonly "pure/value": "either";
195
+ readonly "pure/scope": "either";
196
+ readonly "tokens/unknown": "either";
197
+ readonly "tokens/internal": "either";
198
+ readonly "tokens/declaration": "either";
199
+ readonly "layer/nested": "either";
200
+ readonly "layer/composes": {
201
+ readonly never: "the plugins stop the build at composes in a layer";
202
+ };
203
+ readonly syntax: {
204
+ readonly never: "the bundlers cannot read the stylesheet either";
205
+ };
206
+ readonly "invalid-composes": {
207
+ readonly never: "the bundlers reject composes there";
208
+ };
209
+ readonly "invalid-disable": {
210
+ readonly never: "fix or remove the disable comment instead";
211
+ };
212
+ };
213
+ /** The identifier of a rule, which diagnostics carry and disable comments name. */
214
+ type RuleId = keyof typeof RULES | `tokens/${TokenCategory}`;
215
+ //#endregion
216
+ //#region src/diagnostic.d.ts
217
+ interface Diagnostic {
218
+ /** Absolute path of the file the diagnostic points at. */
219
+ file: string;
220
+ /** 1-based line. */
221
+ line: number;
222
+ /** 1-based column. */
223
+ column: number;
224
+ /** 1-based line of the end of the range. */
225
+ endLine?: number;
226
+ /** 1-based column just after the last character of the range, as in SARIF. */
227
+ endColumn?: number;
228
+ rule: RuleId;
229
+ message: string;
230
+ }
231
+ /** `path:line:col error rule: message`, with the path relative to `cwd`. */
232
+ declare function formatDiagnostic(diagnostic: Diagnostic, cwd: string): string;
233
+ /** GitHub Actions workflow command that annotates the file in a pull request. */
234
+ declare function formatGitHubAnnotation(diagnostic: Diagnostic, cwd: string): string;
235
+ //#endregion
236
+ //#region src/project.d.ts
237
+ /** What telling the included CSS Modules files apart reads of the config. */
238
+ type ModuleOptions = Pick<ResolvedConfig, "root" | "include" | "exclude" | "outDir">;
239
+ //#endregion
240
+ //#region src/layer.d.ts
241
+ interface WrapResult {
242
+ code: string;
243
+ /** Source map, as JSON. */
244
+ map: string;
245
+ }
246
+ /** What wrapping modules in the layer reads of the config. */
247
+ type LayerConfig = ModuleOptions & Pick<ResolvedConfig, "globalCss" | "layer">;
248
+ /**
249
+ * What the bundler plugins run on each stylesheet: it wraps the CSS Modules
250
+ * files the config includes in the layer it names, and resolves to null for
251
+ * any other file, or for every file when the config names no layer.
252
+ *
253
+ * `depend` receives each file of the global CSS it read, also when reading
254
+ * one failed, before the layer is resolved, so that the bundler wraps the
255
+ * module again once the file is fixed or the layer declared. The global CSS
256
+ * is read again only after one of its files has changed, and a read that
257
+ * failed is tried again on the next call.
258
+ */
259
+ declare function createLayerWrapper(config: LayerConfig): (source: string, file: string, depend: (file: string) => void) => Promise<WrapResult | null>;
260
+ //#endregion
261
+ //#region src/dts.d.ts
262
+ interface GenerateResult {
263
+ /** Paths of the `.d.ts` files, written or already up to date. */
264
+ files: string[];
265
+ /** Paths of the `.d.ts` files removed because no included stylesheet produces them any more. */
266
+ removed: string[];
267
+ /** The syntax problems of the stylesheets, sorted. */
268
+ diagnostics: Diagnostic[];
269
+ }
270
+ /**
271
+ * Generate `.d.ts` files for every CSS Modules file the config includes, and
272
+ * remove the ones it wrote for stylesheets it no longer includes.
273
+ */
274
+ declare function generate(config: ResolvedConfig): Promise<GenerateResult>;
275
+ //#endregion
276
+ export { Diagnostic as a, RuleId as c, ConfigError as d, ResolvedConfig as f, createLayerWrapper as i, TokenCategory as l, loadConfig as m, generate as n, formatDiagnostic as o, defineConfig as p, LayerConfig as r, formatGitHubAnnotation as s, GenerateResult as t, Config as u };