css-typed-vars 0.10.1 → 0.12.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
@@ -144,6 +144,7 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
144
144
  | `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Doesn't need `--output`. Useful in CI. |
145
145
  | `--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) |
146
146
  | `--refs-ignore` | Name or `--prefix-*` pattern for `--lint-refs` to skip (repeatable) |
147
+ | `--refs-source` | Source files whose `var()` references `--lint-refs` checks too (repeatable) — see [below](#in-source-files) |
147
148
  | `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
148
149
  | `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
149
150
  | `--watch` | Watch the `input` files (and, with `--prune`, the `--usage` files) and regenerate on change |
@@ -183,6 +184,24 @@ css-typed-vars: 2 reference(s) to undeclared variables:
183
184
  - References inside comments and strings are ignored; positions point to the original file.
184
185
  - 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.
185
186
 
187
+ #### In source files
188
+
189
+ `var(--name)` strings in components are just as easy to get wrong. Add `--refs-source` (repeatable, or `refsSource` in the config file) to check them against the same declarations:
190
+
191
+ ```sh
192
+ npx css-typed-vars --input "src/**/*.css" --lint-refs --refs-source "src/**/*.{ts,tsx,vue,html}"
193
+ ```
194
+
195
+ ```
196
+ css-typed-vars: 1 reference(s) to undeclared variables:
197
+ src/Card.tsx:14:22 var(--colr-primary)
198
+ ```
199
+
200
+ - Finds `var(--name)` anywhere in the file — in strings, template literals, Tailwind classes like `bg-[var(--brand)]` — and Tailwind v4's `bg-(--brand)` shorthand.
201
+ - Variables a source file sets itself count as declared: an object key (`{ '--gap': '4px' }`), a `style` attribute (`style="--gap: 4px"`), `setProperty('--gap', ...)` or a Tailwind arbitrary property (`[--gap:4px]`). This applies to the CSS references too.
202
+ - Like the `--prune` usage scan, this is textual: a reference inside a comment counts too.
203
+ - The target's own output file is skipped even if the glob matches it — `--check` is what tells whether it's stale.
204
+
186
205
  ### Config file
187
206
 
188
207
  The CLI looks for a config file in the current working directory (in order):
@@ -212,11 +231,24 @@ export default defineConfig({
212
231
  group: false,
213
232
  helpers: false,
214
233
  refsIgnore: ['--tw-*'],
234
+ refsSource: 'src/**/*.{ts,tsx}',
215
235
  prune: false,
216
236
  usage: 'src/**/*.{ts,tsx}',
217
237
  });
218
238
  ```
219
239
 
240
+ For a JSON config, point `$schema` at the bundled JSON Schema to get the same autocompletion and validation in your editor:
241
+
242
+ ```json
243
+ {
244
+ "$schema": "./node_modules/css-typed-vars/schema.json",
245
+ "input": "src/styles/**/*.css",
246
+ "output": "src/cssVars.ts"
247
+ }
248
+ ```
249
+
250
+ An unknown key in any config file (a typo like `"ouput"`) is reported as a warning, with the closest option suggested.
251
+
220
252
  #### Multiple targets
221
253
 
222
254
  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:
@@ -242,6 +274,8 @@ No file is generated — CSS variables are served as a virtual module directly b
242
274
 
243
275
  TypeScript types are written to `node_modules/css-typed-vars/dist/generated.d.ts` automatically on each build or dev server start.
244
276
 
277
+ In watch builds (`vite build --watch`, `rollup --watch`, `webpack --watch`, esbuild's `context.watch()`), editing a scanned CSS file triggers a rebuild.
278
+
245
279
  ### Vite
246
280
 
247
281
  ```ts
@@ -425,7 +459,7 @@ await generate({
425
459
 
426
460
  `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.
427
461
 
428
- `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.
462
+ `findUndefinedRefs({ input, exclude?, refsIgnore?, refsSource? })` returns `Promise<FileReference[]>` — each undeclared `var()` reference with its `file`, `line`, `column` and `hasFallback`. Same thing `--lint-refs` does on the CLI.
429
463
 
430
464
  `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.
431
465
 
@@ -447,6 +481,8 @@ By default, variables are scanned from `:root {}` blocks (including attribute se
447
481
 
448
482
  ## Theme values
449
483
 
484
+ When a variable is declared in several files, the last file read wins. Files are read in `input` order (a file matched by several globs counts at the last one), and within a glob a directory's files come before its subdirectories', alphabetically — so `styles/themes/dark.css` overrides `styles/tokens.css`.
485
+
450
486
  By default, a variable redeclared in another block (`:root[data-theme="dark"]`, or a `selectors` entry) simply overwrites its `@default` value — last one wins. The `themes` option names those blocks instead, so each theme's value is kept separately:
451
487
 
452
488
  ```js
@@ -315,6 +315,29 @@ function parseVarReferences(css) {
315
315
  }
316
316
  return refs;
317
317
  }
318
+ var SOURCE_REF_RE = /\bvar\(\s*(--[\w-]+)\s*(,)?|(?<=[\w-]-)\((?:[\w-]+:)?(--[\w-]+)\)/g;
319
+ function parseSourceVarReferences(text) {
320
+ const lineStarts = [0];
321
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") lineStarts.push(i + 1);
322
+ const refs = [];
323
+ for (const match of text.matchAll(SOURCE_REF_RE)) {
324
+ let line = lineStarts.length - 1;
325
+ while (lineStarts[line] > match.index) line--;
326
+ refs.push({
327
+ name: match[1] ?? match[3],
328
+ hasFallback: match[2] === ",",
329
+ line: line + 1,
330
+ column: match.index - lineStarts[line] + 1
331
+ });
332
+ }
333
+ return refs;
334
+ }
335
+ function parseSourceDeclaredNames(text) {
336
+ const names = /* @__PURE__ */ new Set();
337
+ for (const match of text.matchAll(/(?<![\w-])(--[\w-]+)['"`]?\s*:/g)) names.add(match[1]);
338
+ for (const match of text.matchAll(/\bsetProperty\(\s*['"`](--[\w-]+)['"`]/g)) names.add(match[1]);
339
+ return names;
340
+ }
318
341
  function parseDeclaredNames(css) {
319
342
  const masked = maskQuotedContent(stripComments(css));
320
343
  const names = /* @__PURE__ */ new Set();
@@ -325,12 +348,45 @@ function parseDeclaredNames(css) {
325
348
 
326
349
  // src/scanner.ts
327
350
  import { readFile as readFile2 } from "fs/promises";
328
- import { dirname as dirname2, relative, resolve } from "path";
329
- import fg from "fast-glob";
351
+ import { dirname as dirname2, posix, relative, resolve } from "path";
330
352
  import picomatch from "picomatch";
353
+ import { glob } from "tinyglobby";
331
354
  function normalizePatterns(patterns) {
332
355
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
333
356
  }
357
+ function comparePaths(a, b) {
358
+ const as = a.split("/");
359
+ const bs = b.split("/");
360
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
361
+ if (as[i] === bs[i]) continue;
362
+ const aIsFile = i === as.length - 1;
363
+ const bIsFile = i === bs.length - 1;
364
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
365
+ return as[i] < bs[i] ? -1 : 1;
366
+ }
367
+ return as.length - bs.length;
368
+ }
369
+ async function globFiles(pattern, ignore) {
370
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
371
+ return glob(pattern, { absolute: true, ignore, expandDirectories: false });
372
+ }
373
+ const { base, glob: rest, isGlob } = picomatch.scan(pattern);
374
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [posix.dirname(pattern), posix.basename(pattern)];
375
+ const matches = await glob(relativeGlob, { cwd, absolute: true, expandDirectories: false });
376
+ if (ignore.length === 0) return matches;
377
+ const isIgnored = picomatch(ignore, { dot: true });
378
+ return matches.filter((file) => !isIgnored(file));
379
+ }
380
+ async function findFiles(patterns, exclude) {
381
+ const normalized = normalizePatterns(patterns);
382
+ const ignore = [
383
+ ...exclude ? normalizePatterns(exclude) : [],
384
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
385
+ ];
386
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
387
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
388
+ return [...new Set(files.reverse())].reverse();
389
+ }
334
390
  function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
335
391
  const compile = (globs) => picomatch(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
336
392
  const include = compile(patterns);
@@ -342,12 +398,20 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
342
398
  return matches(include) && !matches(ignore);
343
399
  };
344
400
  }
401
+ function globWatchRoots(patterns, cwd = process.cwd()) {
402
+ const roots = /* @__PURE__ */ new Map();
403
+ for (const pattern of normalizePatterns(patterns)) {
404
+ const { base, glob: glob2, isGlob } = picomatch.scan(pattern);
405
+ const dir = resolve(cwd, isGlob ? base || "." : dirname2(pattern));
406
+ const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob2) ? void 0 : glob2.split("/").length - 1;
407
+ const previous = roots.get(dir);
408
+ const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
409
+ roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
410
+ }
411
+ return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
412
+ }
345
413
  function globBaseDirs(patterns, cwd = process.cwd()) {
346
- const dirs = normalizePatterns(patterns).map((pattern) => {
347
- const { base, isGlob } = picomatch.scan(pattern);
348
- return resolve(cwd, isGlob ? base || "." : dirname2(pattern));
349
- });
350
- return [...new Set(dirs)];
414
+ return globWatchRoots(patterns, cwd).map((root) => root.dir);
351
415
  }
352
416
  function collectVarNames(scanned) {
353
417
  const names = new Set(scanned.declarations.keys());
@@ -357,9 +421,7 @@ function collectVarNames(scanned) {
357
421
  return [...names].sort();
358
422
  }
359
423
  async function scanCss(patterns, exclude, selectors, themes = {}) {
360
- const normalized = normalizePatterns(patterns);
361
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
362
- const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
424
+ const files = await findFiles(patterns, exclude);
363
425
  const perFile = await Promise.all(
364
426
  files.map(async (file) => {
365
427
  let css;
@@ -385,7 +447,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
385
447
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
386
448
  }
387
449
  }
388
- return { declarations, properties, themes: themeValues, docs };
450
+ return { declarations, properties, themes: themeValues, docs, files };
389
451
  }
390
452
  async function scanVarDeclarations(patterns, exclude, selectors) {
391
453
  return (await scanCss(patterns, exclude, selectors)).declarations;
@@ -423,10 +485,8 @@ function extractUsage(text, into) {
423
485
  }
424
486
  }
425
487
  async function scanUsage(patterns, exclude) {
426
- const normalized = normalizePatterns(patterns);
427
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
428
- const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
429
- const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
488
+ const files = await findFiles(patterns, exclude);
489
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
430
490
  const texts = await Promise.all(
431
491
  files.map(async (file) => {
432
492
  try {
@@ -440,10 +500,10 @@ async function scanUsage(patterns, exclude) {
440
500
  for (const text of texts) extractUsage(text, usage);
441
501
  return usage;
442
502
  }
443
- async function scanReferences(patterns, exclude) {
444
- const normalized = normalizePatterns(patterns);
445
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
446
- const files = (await fg(normalized, { absolute: true, ignore: normalizedExclude })).sort();
503
+ async function scanReferences(patterns, exclude, source = false) {
504
+ const parseReferences = source ? parseSourceVarReferences : parseVarReferences;
505
+ const parseDeclared = source ? parseSourceDeclaredNames : parseDeclaredNames;
506
+ const files = (await findFiles(patterns, exclude)).sort();
447
507
  const perFile = await Promise.all(
448
508
  files.map(async (file) => {
449
509
  try {
@@ -458,8 +518,8 @@ async function scanReferences(patterns, exclude) {
458
518
  const declared = /* @__PURE__ */ new Set();
459
519
  for (const result of perFile) {
460
520
  if (!result) continue;
461
- for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
462
- for (const name of parseDeclaredNames(result.css)) declared.add(name);
521
+ for (const ref of parseReferences(result.css)) references.push({ ...ref, file: result.file });
522
+ for (const name of parseDeclared(result.css)) declared.add(name);
463
523
  }
464
524
  return { references, declared };
465
525
  }
@@ -846,6 +906,7 @@ export {
846
906
  parseVarReferences,
847
907
  parseDeclaredNames,
848
908
  createFileMatcher,
909
+ globWatchRoots,
849
910
  globBaseDirs,
850
911
  collectVarNames,
851
912
  scanCss,
@@ -11,7 +11,7 @@ import {
11
11
  scanUsage,
12
12
  warnOnCollisions,
13
13
  writeOutput
14
- } from "./chunk-XCAFJREQ.js";
14
+ } from "./chunk-RZLASYCF.js";
15
15
 
16
16
  // src/index.ts
17
17
  import { readFile } from "fs/promises";
@@ -32,9 +32,13 @@ function matchesIgnore(name, patterns) {
32
32
  return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
33
33
  }
34
34
  async function findUndefinedRefs(options) {
35
- const { references, declared } = await scanReferences(options.input, options.exclude);
35
+ const [css, source] = await Promise.all([
36
+ scanReferences(options.input, options.exclude),
37
+ options.refsSource ? scanReferences(options.refsSource, void 0, true) : null
38
+ ]);
39
+ const declared = /* @__PURE__ */ new Set([...css.declared, ...source?.declared ?? []]);
36
40
  const ignore = options.refsIgnore ?? [];
37
- return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
41
+ return [...css.references, ...source?.references ?? []].filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
38
42
  }
39
43
  async function computeOutputs(options) {
40
44
  assertPruneCompatible(options);
@@ -12,7 +12,7 @@ import {
12
12
  scanUsage,
13
13
  warnOnCollisions,
14
14
  writeOutput
15
- } from "./chunk-XCAFJREQ.js";
15
+ } from "./chunk-RZLASYCF.js";
16
16
 
17
17
  // src/unplugin.ts
18
18
  import { createUnplugin } from "unplugin";
@@ -31,18 +31,23 @@ function outputFiles(options, names, generatorOptions) {
31
31
  if (options.tokens) files.push([resolve(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
32
32
  return files;
33
33
  }
34
- var unplugin_default = createUnplugin((options) => {
34
+ var unplugin_default = createUnplugin((options, meta) => {
35
35
  assertPruneCompatible(options);
36
36
  let cachedScan = null;
37
+ let devServer = false;
37
38
  const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
38
39
  const applyPrune = async (names) => {
39
- if (!options.prune) return names;
40
+ if (!options.prune) return { names, usageFiles: [] };
40
41
  const usage = await scanUsage(options.usage, options.usageExclude);
41
42
  const { used, unused } = partitionUnused(names, usage, options);
42
43
  if (unused.length > 0) {
43
44
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
44
45
  }
45
- return used;
46
+ return { names: used, usageFiles: usage.files };
47
+ };
48
+ const watchFiles = (context, scanned, usageFiles) => {
49
+ if (devServer) return;
50
+ for (const file of [...scanned.files, ...usageFiles]) context.addWatchFile(resolve(file));
46
51
  };
47
52
  const generatorOptions = ({ declarations, properties, themes, docs }) => ({
48
53
  prefix: options.prefix,
@@ -63,6 +68,9 @@ var unplugin_default = createUnplugin((options) => {
63
68
  name: "css-typed-vars",
64
69
  vite: {
65
70
  enforce: "pre",
71
+ configResolved(config) {
72
+ devServer = config.command === "serve";
73
+ },
66
74
  configureServer(server) {
67
75
  let generation = 0;
68
76
  let debounceTimer = null;
@@ -73,7 +81,7 @@ var unplugin_default = createUnplugin((options) => {
73
81
  cachedScan = scanPromise;
74
82
  const scanned = await scanPromise;
75
83
  if (myGeneration !== generation) return;
76
- const names = await resolveNames(scanned);
84
+ const { names } = await resolveNames(scanned);
77
85
  if (myGeneration !== generation) return;
78
86
  const files = outputFiles(options, names, generatorOptions(scanned));
79
87
  if (files.length > 0) {
@@ -113,7 +121,8 @@ var unplugin_default = createUnplugin((options) => {
113
121
  async buildStart() {
114
122
  cachedScan = scan();
115
123
  const scanned = await cachedScan;
116
- const names = await resolveNames(scanned);
124
+ const { names, usageFiles } = await resolveNames(scanned);
125
+ if (meta.framework !== "esbuild") watchFiles(this, scanned, usageFiles);
117
126
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
118
127
  await writeOutput(path, content);
119
128
  }
@@ -124,7 +133,8 @@ var unplugin_default = createUnplugin((options) => {
124
133
  async load(id) {
125
134
  if (id === RESOLVED_ID) {
126
135
  const scanned = await (cachedScan ?? scan());
127
- const names = await applyPrune(collectVarNames(scanned));
136
+ const { names, usageFiles } = await applyPrune(collectVarNames(scanned));
137
+ watchFiles(this, scanned, usageFiles);
128
138
  return generateJs(names, generatorOptions(scanned));
129
139
  }
130
140
  }