css-typed-vars 0.7.0 → 0.9.0

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
@@ -128,6 +128,7 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
128
128
 
129
129
  | Flag | Description |
130
130
  |------|-------------|
131
+ | `--config` | Config file to use instead of looking one up in the working directory — see [Config file](#config-file) |
131
132
  | `--input` | Glob pattern for CSS/SCSS/Less files (repeatable: `--input "src/**/*.css" --input "lib/**/*.css"`) |
132
133
  | `--output` | Output file. `.ts` → TypeScript, `.js` → JavaScript + `.d.ts` alongside, `.json` → [design tokens](#design-tokens-dtcg) |
133
134
  | `--exclude` | Glob pattern for files to exclude (repeatable: `--exclude "**/a/**" --exclude "**/b/**"`) |
@@ -136,14 +137,17 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
136
137
  | `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
137
138
  | `--theme` | Named theme block, kept out of the default value and emitted as `@theme <name> <value>` JSDoc tags (repeatable: `--theme dark='[data-theme="dark"]' --theme contrast='@media (prefers-contrast: more)'`) — see [Theme values](#theme-values) |
138
139
  | `--group` | Nest keys under an object named after each variable's first hyphen segment: `--color-primary`/`--color-secondary` → `cssVars.color.primary`/`cssVars.color.secondary`. A variable with no hyphen stays top-level. Can't be combined with `--prefix`. |
139
- | `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)` runtime helpers — see [Usage](#usage). |
140
+ | `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)`/`withFallback(ref, fallback)` helpers — see [Usage](#usage). |
140
141
  | `--prune` | Drop generated vars with no detected `cssVars.<key>` usage. Requires `--usage <glob>` (repeatable). With `--group`, matches `cssVars.<group>.<key>` and keeps a whole group referenced as `cssVars.<group>`. |
141
142
  | `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Useful in CI. |
143
+ | `--lint-refs` | Report `var(--name)` references to variables not declared anywhere in the input; exits 1 if any (without a fallback) are found — see [Linting var() references](#linting-var-references) |
144
+ | `--refs-ignore` | Name or `--prefix-*` pattern for `--lint-refs` to skip (repeatable) |
142
145
  | `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
143
146
  | `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
144
- | `--watch` | Watch for file changes and regenerate |
147
+ | `--watch` | Watch the `input` files (and, with `--prune`, the `--usage` files) and regenerate on change |
145
148
  | `--check` | Check whether the output is up to date without writing; exits 1 if it would differ. Useful in CI. Can't be combined with `--watch`. |
146
149
  | `--version`, `-v` | Print the version number and exit |
150
+ | `--help`, `-h` | Print all options and exit. An unknown option or a stray argument (such as an unquoted glob the shell expanded) is an error |
147
151
 
148
152
  ### Pruning unused variables
149
153
 
@@ -156,19 +160,46 @@ When in doubt, use `--prune-check` in CI to review what it would remove before t
156
160
 
157
161
  CLI flags override values from the config file.
158
162
 
163
+ ### Linting var() references
164
+
165
+ `--lint-refs` checks the input CSS for `var(--name)` references to variables that aren't declared anywhere in it — typos, or variables that were renamed or removed. No output file is needed:
166
+
167
+ ```sh
168
+ npx css-typed-vars --input "src/**/*.css" --lint-refs
169
+ ```
170
+
171
+ ```
172
+ css-typed-vars: 1 reference(s) to undeclared variables with a fallback:
173
+ src/card.css:12:9 var(--card-gap, …)
174
+ css-typed-vars: 2 reference(s) to undeclared variables:
175
+ src/button.css:4:10 var(--colr-primary)
176
+ src/button.css:9:18 var(--radius-xl)
177
+ ```
178
+
179
+ - A variable counts as declared if any input file declares it in any block (not just `:root`), or registers it with `@property`.
180
+ - References without a fallback are errors and make the command exit `1`. References with a fallback (`var(--x, 4px)`) still work at runtime, so they're only reported as warnings.
181
+ - References inside comments and strings are ignored; positions point to the original file.
182
+ - Variables set from JavaScript or defined by another stylesheet you don't scan can be skipped with `--refs-ignore` (repeatable, a trailing `*` matches a prefix): `--refs-ignore "--tw-*" --refs-ignore --app-height`, or `refsIgnore` in the config file.
183
+
159
184
  ### Config file
160
185
 
161
186
  The CLI looks for a config file in the current working directory (in order):
162
187
 
163
188
  1. `css-typed-vars.config.js`
164
189
  2. `css-typed-vars.config.mjs`
165
- 3. `css-typed-vars.config.json`
190
+ 3. `css-typed-vars.config.cjs`
191
+ 4. `css-typed-vars.config.ts` / `.mts` — needs a Node.js version that strips types natively (22.18+ or 23.6+)
192
+ 5. `css-typed-vars.config.json`
166
193
 
167
- All options are supported in the config file:
194
+ Or point to one explicitly with `--config <file>`.
195
+
196
+ All options are supported in the config file. Wrap it in `defineConfig` for type checking and editor autocompletion (it also accepts an array, see below):
168
197
 
169
198
  ```js
170
199
  // css-typed-vars.config.js
171
- export default {
200
+ import { defineConfig } from 'css-typed-vars';
201
+
202
+ export default defineConfig({
172
203
  input: 'src/styles/**/*.{css,scss}',
173
204
  output: 'src/cssVars.ts',
174
205
  exclude: ['**/vendor/**', '**/node_modules/**'],
@@ -178,11 +209,29 @@ export default {
178
209
  themes: { dark: '[data-theme="dark"]' },
179
210
  group: false,
180
211
  helpers: false,
212
+ refsIgnore: ['--tw-*'],
181
213
  prune: false,
182
214
  usage: 'src/**/*.{ts,tsx}',
183
- };
215
+ });
216
+ ```
217
+
218
+ #### Multiple targets
219
+
220
+ Export an array to generate several files in one run — e.g. one per package in a monorepo, or a TypeScript file plus a design tokens file:
221
+
222
+ ```js
223
+ // css-typed-vars.config.js
224
+ export default [
225
+ { input: 'packages/ui/src/**/*.css', output: 'packages/ui/src/cssVars.ts' },
226
+ { input: 'packages/docs/styles/*.css', output: 'packages/docs/cssVars.ts', naming: 'kebab' },
227
+ { input: 'packages/ui/src/**/*.css', output: 'tokens/ui.json', group: true },
228
+ ];
184
229
  ```
185
230
 
231
+ - `--check`, `--prune-check` and `--lint-refs` run for every target and exit `1` if any target fails; each message is tagged with its target's output (`css-typed-vars [packages/ui/src/cssVars.ts]: ...`).
232
+ - `--watch` watches each target's `input` and regenerates only that target on change.
233
+ - Flags that set options (`--input`, `--naming`, `--group`, ...) can't be combined with an array config — set them per target instead. Mode flags (`--watch`, `--check`, ...) work as usual.
234
+
186
235
  ---
187
236
 
188
237
  ## Plugin
@@ -280,7 +329,7 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
280
329
  | `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
281
330
  | `themes` | `Record<string, string>` | — | Theme name → selector or `@media` prelude; values become `@theme` JSDoc tags — see [Theme values](#theme-values) |
282
331
  | `group` | `boolean` | `false` | Nest keys by each variable's first hyphen segment, e.g. `cssVars.color.primary`. Can't be combined with `prefix` |
283
- | `helpers` | `boolean` | `false` | Also export the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers from `css-typed-vars/vars` |
332
+ | `helpers` | `boolean` | `false` | Also export the `CssVarRef` type and `getCssVar`/`setCssVar`/`withFallback` helpers from `css-typed-vars/vars` |
284
333
  | `prune` | `boolean` | `false` | Drop vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>` with `group`) usage. Requires `usage` |
285
334
  | `usage` | `string \| string[]` | — | Glob(s) of source files to scan for `cssVars` usage, for `prune` |
286
335
  | `usageExclude` | `string \| string[]` | — | Glob(s) of source files to exclude from the usage scan |
@@ -338,7 +387,17 @@ setCssVar(cssVars.colorPrimary, '#ef4444'); // inline style on <html>
338
387
  setCssVar(cssVars.spacingMd, '12px', cardEl); // or on a specific element
339
388
  ```
340
389
 
341
- The helpers take a `cssVars` value (typed as `CssVarRef`, the union of every generated `'var(--name)'`), so they work the same with any `naming`, `prefix` or `group`. They use `getComputedStyle`/`style.setProperty`, so call them in the browser only, and the TS output needs the `DOM` lib in your `tsconfig`.
390
+ The helpers take a `cssVars` value (typed as `CssVarRef`, the union of every generated `'var(--name)'`), so they work the same with any `naming`, `prefix` or `group`. `getCssVar`/`setCssVar` use `getComputedStyle`/`style.setProperty`, so call them in the browser only, and the TS output needs the `DOM` lib in your `tsconfig`.
391
+
392
+ `withFallback` builds a `var()` with a fallback value, typed as the exact resulting string — handy in style objects and CSS-in-JS. Unlike the two above, it's a pure string helper and works anywhere, including on the server:
393
+
394
+ ```ts
395
+ import { cssVars, withFallback } from './cssVars';
396
+
397
+ withFallback(cssVars.colorPrimary, '#3b82f6'); // 'var(--color-primary, #3b82f6)'
398
+ withFallback(cssVars.spacingMd, 0); // 'var(--spacing-md, 0)'
399
+ withFallback(cssVars.colorLink, cssVars.colorPrimary); // 'var(--color-link, var(--color-primary))'
400
+ ```
342
401
 
343
402
  ---
344
403
 
@@ -356,7 +415,7 @@ await generate({
356
415
  selectors: ['.dark', '[data-theme="dark"]'],
357
416
  themes: { dark: '[data-theme="dark"]' }, // per-theme values as @theme JSDoc tags
358
417
  group: false, // nest keys by first hyphen segment, e.g. cssVars.color.primary
359
- helpers: false, // also emit getCssVar/setCssVar runtime helpers
418
+ helpers: false, // also emit getCssVar/setCssVar/withFallback helpers
360
419
  prune: false, // drop vars with no detected cssVars.<key> usage (requires `usage`)
361
420
  usage: 'src/**/*.{ts,tsx}',
362
421
  });
@@ -364,6 +423,8 @@ await generate({
364
423
 
365
424
  `checkGenerated(options)` takes the same options and returns `Promise<boolean>` — `true` if the existing output already matches what would be generated, without writing anything. Same thing `--check` does on the CLI.
366
425
 
426
+ `findUndefinedRefs({ input, exclude?, refsIgnore? })` returns `Promise<FileReference[]>` — each undeclared `var()` reference with its `file`, `line`, `column` and `hasFallback`. Same thing `--lint-refs` does on the CLI.
427
+
367
428
  `findUnusedVars(options)` takes `input`/`exclude`/`selectors`/`prefix`/`naming`/`group`/`usage`/`usageExclude` and returns `Promise<string[]>` — the CSS variable names with no detected `cssVars.<key>` usage, without writing or pruning anything. Same thing `--prune-check` does on the CLI.
368
429
 
369
430
  Lower-level exports:
@@ -406,9 +467,11 @@ export default {
406
467
 
407
468
  ```ts
408
469
  export const cssVars = {
409
- /** @default #ffffff */
410
- /** @theme dark #0b0b0f */
411
- /** @theme contrast #000000 */
470
+ /**
471
+ * @default #ffffff
472
+ * @theme dark #0b0b0f
473
+ * @theme contrast #000000
474
+ */
412
475
  colorBg: 'var(--color-bg)',
413
476
  /** @theme dark 0 0 8px #7c3aed */
414
477
  glow: 'var(--glow)',
@@ -420,6 +483,44 @@ export const cssVars = {
420
483
  - An `@media` theme matches by its prelude, ignoring whitespace and case. Other `@media` blocks are read as before.
421
484
  - On the CLI, pass `--theme <name>=<selector>` (repeatable): `--theme dark='[data-theme="dark"]'`.
422
485
 
486
+ ## Doc comments
487
+
488
+ A `/** ... */` comment directly before a declaration is carried over to the generated key, so it shows up in editor hover — and `@deprecated` makes the editor strike through every usage:
489
+
490
+ ```css
491
+ :root {
492
+ /** Page background. Use for full-bleed surfaces only. */
493
+ --color-bg: #ffffff;
494
+
495
+ /**
496
+ * Legacy link color.
497
+ * @deprecated use --color-primary
498
+ */
499
+ --color-link: #2563eb;
500
+ }
501
+ ```
502
+
503
+ ```ts
504
+ export const cssVars = {
505
+ /**
506
+ * Page background. Use for full-bleed surfaces only.
507
+ * @default #ffffff
508
+ */
509
+ colorBg: 'var(--color-bg)',
510
+ /**
511
+ * Legacy link color.
512
+ * @default #2563eb
513
+ * @deprecated use --color-primary
514
+ */
515
+ colorLink: 'var(--color-link)',
516
+ } as const;
517
+ ```
518
+
519
+ - Only `/** */` comments count — plain `/* */` comments (like section headers) are ignored, and the comment must be directly before the declaration (only whitespace in between).
520
+ - The text before the first tag becomes the description; `@deprecated [reason]` is kept, other tags are ignored.
521
+ - If a variable has doc comments in several places, the one in a base block (`:root`/`@theme`/`selectors`) wins over one in a [theme](#theme-values) block.
522
+ - In [design tokens](#design-tokens-dtcg) output they become `$description` and `$deprecated`.
523
+
423
524
  ## Design tokens (DTCG)
424
525
 
425
526
  Point `output` at a `.json` file to get a [W3C Design Tokens](https://www.designtokens.org/tr/drafts/format/) document instead of TypeScript, for Style Dictionary, Tokens Studio and similar tools:
@@ -440,7 +541,7 @@ npx css-typed-vars --input "src/**/*.css" --output tokens/tokens.json --group
440
541
  - Keys follow `naming`/`prefix`/`group`, like the generated object.
441
542
  - `$value` is the declared value (or the `@property` `initial-value`); `$type` is inferred from the `@property` syntax (`<color>`, `<length>`, `<number>`, `<time>`, ...).
442
543
  - A value that's exactly `var(--other)` becomes an alias (`{color.primary}`) when `--other` is in the file.
443
- - [Theme values](#theme-values) go under `$extensions["css-typed-vars"].themes`.
544
+ - [Theme values](#theme-values) go under `$extensions["css-typed-vars"].themes`; [doc comments](#doc-comments) become `$description`/`$deprecated`.
444
545
  - The plugin can write the file too: `cssTypedVars({ input, tokens: 'tokens/tokens.json' })`.
445
546
 
446
547
  See the [Design tokens guide](https://stanislavkozachenko.github.io/css-typed-vars/guide/design-tokens) for details.
@@ -462,8 +563,10 @@ If a variable is registered via the [CSS Properties and Values API](https://deve
462
563
 
463
564
  ```ts
464
565
  export const cssVars = {
465
- /** @default light */
466
- /** @syntax light | dark | system */
566
+ /**
567
+ * @default light
568
+ * @syntax light | dark | system
569
+ */
467
570
  themeMode: 'var(--theme-mode)',
468
571
  } as const;
469
572
 
@@ -472,7 +575,7 @@ export type CssVarName = keyof typeof cssVars;
472
575
  export type ThemeModeSyntax = 'light' | 'dark' | 'system';
473
576
  ```
474
577
 
475
- Every `syntax` shows up as a `@syntax` JSDoc comment. When it's a pipe-separated list of custom idents (an enum, like above) — as opposed to a generic data type like `<color>` or `<length>` — it also gets its own exported union type, named `<PascalCaseVarName>Syntax`. Useful when setting the property from JS: `el.style.setProperty('--theme-mode', mode satisfies ThemeModeSyntax)`.
578
+ Every `syntax` shows up as a `@syntax` JSDoc tag (in the same comment block as `@default`, so editor hover shows both). When it's a pipe-separated list of custom idents (an enum, like above) — as opposed to a generic data type like `<color>` or `<length>` — it also gets its own exported union type, named `<PascalCaseVarName>Syntax`. Useful when setting the property from JS: `el.style.setProperty('--theme-mode', mode satisfies ThemeModeSyntax)`.
476
579
 
477
580
  Note this doesn't change the type of `cssVars.themeMode` itself — that's always the literal string `'var(--theme-mode)'`, regardless of `@property`, since that's what you actually get at runtime. The union type is a separate, additional export for validating what you *assign* to the variable.
478
581
 
@@ -2,18 +2,19 @@ import {
2
2
  __dirname,
3
3
  assertPruneCompatible,
4
4
  collectVarNames,
5
+ createFileMatcher,
5
6
  generateDeclaration,
6
7
  generateJs,
7
8
  generateTokens,
8
9
  partitionUnused,
9
10
  scanCss,
10
11
  scanUsage,
11
- warnOnCollisions
12
- } from "./chunk-6YWE4A6S.js";
12
+ warnOnCollisions,
13
+ writeOutput
14
+ } from "./chunk-DHBPPGOE.js";
13
15
 
14
16
  // src/unplugin.ts
15
17
  import { createUnplugin } from "unplugin";
16
- import { writeFile } from "fs/promises";
17
18
  import { join, resolve } from "path";
18
19
  var VIRTUAL_ID = "css-typed-vars/vars";
19
20
  var RESOLVED_ID = "\0css-typed-vars/vars";
@@ -41,14 +42,15 @@ var unplugin_default = createUnplugin((options) => {
41
42
  }
42
43
  return used;
43
44
  };
44
- const generatorOptions = ({ declarations, properties, themes }) => ({
45
+ const generatorOptions = ({ declarations, properties, themes, docs }) => ({
45
46
  prefix: options.prefix,
46
47
  naming: options.naming,
47
48
  declarations,
48
49
  group: options.group,
49
50
  properties,
50
51
  helpers: options.helpers,
51
- themes
52
+ themes,
53
+ docs
52
54
  });
53
55
  const resolveNames = async (scanned) => {
54
56
  const names = collectVarNames(scanned);
@@ -76,7 +78,7 @@ var unplugin_default = createUnplugin((options) => {
76
78
  writeQueue = writeQueue.then(async () => {
77
79
  for (const [path, content] of files) {
78
80
  if (myGeneration !== generation) return;
79
- await writeFile(path, content, "utf8");
81
+ await writeOutput(path, content);
80
82
  }
81
83
  }).catch(console.error);
82
84
  await writeQueue;
@@ -88,8 +90,12 @@ var unplugin_default = createUnplugin((options) => {
88
90
  server.ws.send({ type: "full-reload" });
89
91
  }
90
92
  };
93
+ const isInput = createFileMatcher(options.input, options.exclude);
94
+ const isUsage = options.prune ? createFileMatcher(options.usage, options.usageExclude) : () => false;
95
+ const outputs = new Set([getDtsPath(options), options.tokens && resolve(process.cwd(), options.tokens)].filter((path) => !!path).map((path) => resolve(path)));
91
96
  const handle = (file) => {
92
- if (!/\.(css|scss|less)$/i.test(file)) return;
97
+ if (outputs.has(resolve(file))) return;
98
+ if (!isInput(file) && !isUsage(file)) return;
93
99
  if (debounceTimer) clearTimeout(debounceTimer);
94
100
  debounceTimer = setTimeout(() => {
95
101
  debounceTimer = null;
@@ -106,7 +112,7 @@ var unplugin_default = createUnplugin((options) => {
106
112
  const scanned = await cachedScan;
107
113
  const names = await resolveNames(scanned);
108
114
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
109
- await writeFile(path, content, "utf8");
115
+ await writeOutput(path, content);
110
116
  }
111
117
  },
112
118
  resolveId(id) {