css-typed-vars 0.7.0 → 0.8.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
@@ -136,9 +136,11 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
136
136
  | `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
137
137
  | `--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
138
  | `--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). |
139
+ | `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)`/`withFallback(ref, fallback)` helpers — see [Usage](#usage). |
140
140
  | `--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
141
  | `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Useful in CI. |
142
+ | `--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) |
143
+ | `--refs-ignore` | Name or `--prefix-*` pattern for `--lint-refs` to skip (repeatable) |
142
144
  | `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
143
145
  | `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
144
146
  | `--watch` | Watch for file changes and regenerate |
@@ -156,6 +158,27 @@ When in doubt, use `--prune-check` in CI to review what it would remove before t
156
158
 
157
159
  CLI flags override values from the config file.
158
160
 
161
+ ### Linting var() references
162
+
163
+ `--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:
164
+
165
+ ```sh
166
+ npx css-typed-vars --input "src/**/*.css" --lint-refs
167
+ ```
168
+
169
+ ```
170
+ css-typed-vars: 1 reference(s) to undeclared variables with a fallback:
171
+ src/card.css:12:9 var(--card-gap, …)
172
+ css-typed-vars: 2 reference(s) to undeclared variables:
173
+ src/button.css:4:10 var(--colr-primary)
174
+ src/button.css:9:18 var(--radius-xl)
175
+ ```
176
+
177
+ - A variable counts as declared if any input file declares it in any block (not just `:root`), or registers it with `@property`.
178
+ - 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.
179
+ - References inside comments and strings are ignored; positions point to the original file.
180
+ - 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.
181
+
159
182
  ### Config file
160
183
 
161
184
  The CLI looks for a config file in the current working directory (in order):
@@ -178,11 +201,29 @@ export default {
178
201
  themes: { dark: '[data-theme="dark"]' },
179
202
  group: false,
180
203
  helpers: false,
204
+ refsIgnore: ['--tw-*'],
181
205
  prune: false,
182
206
  usage: 'src/**/*.{ts,tsx}',
183
207
  };
184
208
  ```
185
209
 
210
+ #### Multiple targets
211
+
212
+ 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:
213
+
214
+ ```js
215
+ // css-typed-vars.config.js
216
+ export default [
217
+ { input: 'packages/ui/src/**/*.css', output: 'packages/ui/src/cssVars.ts' },
218
+ { input: 'packages/docs/styles/*.css', output: 'packages/docs/cssVars.ts', naming: 'kebab' },
219
+ { input: 'packages/ui/src/**/*.css', output: 'tokens/ui.json', group: true },
220
+ ];
221
+ ```
222
+
223
+ - `--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]: ...`).
224
+ - `--watch` watches each target's `input` and regenerates only that target on change.
225
+ - 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.
226
+
186
227
  ---
187
228
 
188
229
  ## Plugin
@@ -280,7 +321,7 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
280
321
  | `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
281
322
  | `themes` | `Record<string, string>` | — | Theme name → selector or `@media` prelude; values become `@theme` JSDoc tags — see [Theme values](#theme-values) |
282
323
  | `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` |
324
+ | `helpers` | `boolean` | `false` | Also export the `CssVarRef` type and `getCssVar`/`setCssVar`/`withFallback` helpers from `css-typed-vars/vars` |
284
325
  | `prune` | `boolean` | `false` | Drop vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>` with `group`) usage. Requires `usage` |
285
326
  | `usage` | `string \| string[]` | — | Glob(s) of source files to scan for `cssVars` usage, for `prune` |
286
327
  | `usageExclude` | `string \| string[]` | — | Glob(s) of source files to exclude from the usage scan |
@@ -338,7 +379,17 @@ setCssVar(cssVars.colorPrimary, '#ef4444'); // inline style on <html>
338
379
  setCssVar(cssVars.spacingMd, '12px', cardEl); // or on a specific element
339
380
  ```
340
381
 
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`.
382
+ 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`.
383
+
384
+ `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:
385
+
386
+ ```ts
387
+ import { cssVars, withFallback } from './cssVars';
388
+
389
+ withFallback(cssVars.colorPrimary, '#3b82f6'); // 'var(--color-primary, #3b82f6)'
390
+ withFallback(cssVars.spacingMd, 0); // 'var(--spacing-md, 0)'
391
+ withFallback(cssVars.colorLink, cssVars.colorPrimary); // 'var(--color-link, var(--color-primary))'
392
+ ```
342
393
 
343
394
  ---
344
395
 
@@ -356,7 +407,7 @@ await generate({
356
407
  selectors: ['.dark', '[data-theme="dark"]'],
357
408
  themes: { dark: '[data-theme="dark"]' }, // per-theme values as @theme JSDoc tags
358
409
  group: false, // nest keys by first hyphen segment, e.g. cssVars.color.primary
359
- helpers: false, // also emit getCssVar/setCssVar runtime helpers
410
+ helpers: false, // also emit getCssVar/setCssVar/withFallback helpers
360
411
  prune: false, // drop vars with no detected cssVars.<key> usage (requires `usage`)
361
412
  usage: 'src/**/*.{ts,tsx}',
362
413
  });
@@ -364,6 +415,8 @@ await generate({
364
415
 
365
416
  `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
417
 
418
+ `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.
419
+
367
420
  `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
421
 
369
422
  Lower-level exports:
@@ -406,9 +459,11 @@ export default {
406
459
 
407
460
  ```ts
408
461
  export const cssVars = {
409
- /** @default #ffffff */
410
- /** @theme dark #0b0b0f */
411
- /** @theme contrast #000000 */
462
+ /**
463
+ * @default #ffffff
464
+ * @theme dark #0b0b0f
465
+ * @theme contrast #000000
466
+ */
412
467
  colorBg: 'var(--color-bg)',
413
468
  /** @theme dark 0 0 8px #7c3aed */
414
469
  glow: 'var(--glow)',
@@ -420,6 +475,44 @@ export const cssVars = {
420
475
  - An `@media` theme matches by its prelude, ignoring whitespace and case. Other `@media` blocks are read as before.
421
476
  - On the CLI, pass `--theme <name>=<selector>` (repeatable): `--theme dark='[data-theme="dark"]'`.
422
477
 
478
+ ## Doc comments
479
+
480
+ 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:
481
+
482
+ ```css
483
+ :root {
484
+ /** Page background. Use for full-bleed surfaces only. */
485
+ --color-bg: #ffffff;
486
+
487
+ /**
488
+ * Legacy link color.
489
+ * @deprecated use --color-primary
490
+ */
491
+ --color-link: #2563eb;
492
+ }
493
+ ```
494
+
495
+ ```ts
496
+ export const cssVars = {
497
+ /**
498
+ * Page background. Use for full-bleed surfaces only.
499
+ * @default #ffffff
500
+ */
501
+ colorBg: 'var(--color-bg)',
502
+ /**
503
+ * Legacy link color.
504
+ * @default #2563eb
505
+ * @deprecated use --color-primary
506
+ */
507
+ colorLink: 'var(--color-link)',
508
+ } as const;
509
+ ```
510
+
511
+ - Only `/** */` comments count — plain `/* */` comments (like section headers) are ignored, and the comment must be directly before the declaration (only whitespace in between).
512
+ - The text before the first tag becomes the description; `@deprecated [reason]` is kept, other tags are ignored.
513
+ - 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.
514
+ - In [design tokens](#design-tokens-dtcg) output they become `$description` and `$deprecated`.
515
+
423
516
  ## Design tokens (DTCG)
424
517
 
425
518
  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 +533,7 @@ npx css-typed-vars --input "src/**/*.css" --output tokens/tokens.json --group
440
533
  - Keys follow `naming`/`prefix`/`group`, like the generated object.
441
534
  - `$value` is the declared value (or the `@property` `initial-value`); `$type` is inferred from the `@property` syntax (`<color>`, `<length>`, `<number>`, `<time>`, ...).
442
535
  - 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`.
536
+ - [Theme values](#theme-values) go under `$extensions["css-typed-vars"].themes`; [doc comments](#doc-comments) become `$description`/`$deprecated`.
444
537
  - The plugin can write the file too: `cssTypedVars({ input, tokens: 'tokens/tokens.json' })`.
445
538
 
446
539
  See the [Design tokens guide](https://stanislavkozachenko.github.io/css-typed-vars/guide/design-tokens) for details.
@@ -462,8 +555,10 @@ If a variable is registered via the [CSS Properties and Values API](https://deve
462
555
 
463
556
  ```ts
464
557
  export const cssVars = {
465
- /** @default light */
466
- /** @syntax light | dark | system */
558
+ /**
559
+ * @default light
560
+ * @syntax light | dark | system
561
+ */
467
562
  themeMode: 'var(--theme-mode)',
468
563
  } as const;
469
564
 
@@ -472,7 +567,7 @@ export type CssVarName = keyof typeof cssVars;
472
567
  export type ThemeModeSyntax = 'light' | 'dark' | 'system';
473
568
  ```
474
569
 
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)`.
570
+ 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
571
 
477
572
  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
573
 
@@ -9,7 +9,7 @@ import {
9
9
  scanCss,
10
10
  scanUsage,
11
11
  warnOnCollisions
12
- } from "./chunk-6YWE4A6S.js";
12
+ } from "./chunk-5HPTHW7S.js";
13
13
 
14
14
  // src/unplugin.ts
15
15
  import { createUnplugin } from "unplugin";
@@ -41,14 +41,15 @@ var unplugin_default = createUnplugin((options) => {
41
41
  }
42
42
  return used;
43
43
  };
44
- const generatorOptions = ({ declarations, properties, themes }) => ({
44
+ const generatorOptions = ({ declarations, properties, themes, docs }) => ({
45
45
  prefix: options.prefix,
46
46
  naming: options.naming,
47
47
  declarations,
48
48
  group: options.group,
49
49
  properties,
50
50
  helpers: options.helpers,
51
- themes
51
+ themes,
52
+ docs
52
53
  });
53
54
  const resolveNames = async (scanned) => {
54
55
  const names = collectVarNames(scanned);
@@ -13,6 +13,11 @@ function stepQuote(text, i, quote) {
13
13
  return { consumed: 1, closed: false };
14
14
  }
15
15
  function stripComments(text) {
16
+ return stripCommentsWithMap(text).text;
17
+ }
18
+ function stripCommentsWithMap(text) {
19
+ const removed = [];
20
+ const comments = [];
16
21
  let result = "";
17
22
  let quote = null;
18
23
  let urlDepth = 0;
@@ -47,17 +52,20 @@ function stripComments(text) {
47
52
  result += char;
48
53
  continue;
49
54
  }
55
+ comments.push([i, end + 2]);
56
+ removed.push({ at: result.length, length: end + 2 - i });
50
57
  i = end + 1;
51
58
  continue;
52
59
  }
53
60
  if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
54
61
  const nl = text.indexOf("\n", i);
62
+ removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
55
63
  i = nl === -1 ? text.length - 1 : nl - 1;
56
64
  continue;
57
65
  }
58
66
  result += char;
59
67
  }
60
- return result;
68
+ return { text: result, removed, comments };
61
69
  }
62
70
  function extractBlock(text, start) {
63
71
  let depth = 1;
@@ -121,12 +129,12 @@ function extractValue(text, start) {
121
129
  }
122
130
  return text.slice(start, i).trim();
123
131
  }
124
- function forEachProperty(block, onProperty) {
132
+ function forEachProperty(block, onProperty, offset = 0) {
125
133
  const masked = maskQuotedContent(block);
126
134
  for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
127
135
  const name = prop[0];
128
136
  const colonIndex = block.indexOf(":", prop.index + name.length);
129
- onProperty(name, extractValue(block, colonIndex + 1));
137
+ onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
130
138
  }
131
139
  }
132
140
  function forEachSelectorBlock(stripped, selectors, onBlock) {
@@ -147,7 +155,7 @@ var BASE_SELECTORS = [":root", "@theme"];
147
155
  function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
148
156
  forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
149
157
  if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
150
- forEachProperty(block, onProperty);
158
+ forEachProperty(block, onProperty, bodyStart);
151
159
  });
152
160
  }
153
161
  function parseVarNames(css, selectors) {
@@ -177,30 +185,73 @@ function forEachMediaBlock(stripped, media, onBlock) {
177
185
  }
178
186
  }
179
187
  }
188
+ function parseDocComment(body) {
189
+ const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
190
+ const doc = {};
191
+ const description = [];
192
+ let inTags = false;
193
+ for (const line of lines) {
194
+ const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
195
+ if (tag) {
196
+ inTags = true;
197
+ if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
198
+ } else if (!inTags) {
199
+ description.push(line);
200
+ }
201
+ }
202
+ const text = description.join("\n").trim();
203
+ if (text) doc.description = text;
204
+ return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
205
+ }
206
+ function makeDocReader(css, stripped) {
207
+ const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
208
+ return (strippedPos) => {
209
+ let end = toRawPosition(stripped, strippedPos);
210
+ while (end > 0 && /\s/.test(css[end - 1])) end--;
211
+ const start = commentStartByEnd.get(end);
212
+ if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
213
+ return parseDocComment(css.slice(start + 3, end - 2));
214
+ };
215
+ }
180
216
  function parseThemedDeclarations(css, selectors, themes) {
181
- const stripped = stripComments(css);
217
+ const strippedCss = stripCommentsWithMap(css);
218
+ const stripped = strippedCss.text;
219
+ const docAt = makeDocReader(css, strippedCss);
220
+ const themeDocs = /* @__PURE__ */ new Map();
182
221
  const themeValues = /* @__PURE__ */ new Map();
183
222
  const skip = [];
184
223
  for (const [themeName, themeSelector] of Object.entries(themes)) {
185
224
  const values = /* @__PURE__ */ new Map();
186
225
  themeValues.set(themeName, values);
187
- const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
226
+ const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
227
+ values.set(name, value);
228
+ const doc = docAt(position);
229
+ if (doc) themeDocs.set(name, doc);
230
+ }, offset);
188
231
  const selector = themeSelector.trim();
189
232
  if (/^@media\b/i.test(selector)) {
190
233
  forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
191
234
  skip.push(range);
192
- forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
235
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
193
236
  });
194
237
  } else {
195
238
  forEachSelectorBlock(stripped, [selector], (block, range) => {
196
239
  skip.push(range);
197
- collect(block);
240
+ collect(block, range[0]);
198
241
  });
199
242
  }
200
243
  }
201
244
  const declarations = /* @__PURE__ */ new Map();
202
- scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
203
- return { declarations, themes: themeValues };
245
+ const docs = /* @__PURE__ */ new Map();
246
+ scanDeclarations(css, selectors, (name, value, position) => {
247
+ declarations.set(name, value);
248
+ const doc = docAt(position);
249
+ if (doc) docs.set(name, doc);
250
+ }, skip, stripped);
251
+ for (const [name, doc] of themeDocs) {
252
+ if (!docs.has(name)) docs.set(name, doc);
253
+ }
254
+ return { declarations, themes: themeValues, docs };
204
255
  }
205
256
  var PROPERTY_DESCRIPTORS = [
206
257
  ["syntax", "syntax"],
@@ -231,6 +282,35 @@ function parsePropertyRules(css) {
231
282
  }
232
283
  return rules;
233
284
  }
285
+ function toRawPosition(stripped, strippedPos) {
286
+ let rawPos = strippedPos;
287
+ for (const { at, length } of stripped.removed) {
288
+ if (at > strippedPos) break;
289
+ rawPos += length;
290
+ }
291
+ return rawPos;
292
+ }
293
+ function parseVarReferences(css) {
294
+ const stripped = stripCommentsWithMap(css);
295
+ const masked = maskQuotedContent(stripped.text);
296
+ const lineStarts = [0];
297
+ for (let i = 0; i < css.length; i++) if (css[i] === "\n") lineStarts.push(i + 1);
298
+ const refs = [];
299
+ for (const match of masked.matchAll(/\bvar\(\s*(--[\w-]+)\s*(,)?/gi)) {
300
+ const rawPos = toRawPosition(stripped, match.index);
301
+ let line = lineStarts.length - 1;
302
+ while (lineStarts[line] > rawPos) line--;
303
+ refs.push({ name: match[1], hasFallback: match[2] === ",", line: line + 1, column: rawPos - lineStarts[line] + 1 });
304
+ }
305
+ return refs;
306
+ }
307
+ function parseDeclaredNames(css) {
308
+ const masked = maskQuotedContent(stripComments(css));
309
+ const names = /* @__PURE__ */ new Set();
310
+ for (const match of masked.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) names.add(match[1]);
311
+ for (const match of masked.matchAll(/@property\s+(--[\w-]+)/g)) names.add(match[1]);
312
+ return names;
313
+ }
234
314
 
235
315
  // src/scanner.ts
236
316
  import { readFile } from "fs/promises";
@@ -264,15 +344,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
264
344
  const declarations = /* @__PURE__ */ new Map();
265
345
  const properties = /* @__PURE__ */ new Map();
266
346
  const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
347
+ const docs = /* @__PURE__ */ new Map();
267
348
  for (const result of perFile) {
268
349
  if (!result) continue;
269
350
  for (const [name, value] of result.declarations) declarations.set(name, value);
270
351
  for (const [name, rule] of result.properties) properties.set(name, rule);
352
+ for (const [name, doc] of result.docs) docs.set(name, doc);
271
353
  for (const [theme, values] of result.themes) {
272
354
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
273
355
  }
274
356
  }
275
- return { declarations, properties, themes: themeValues };
357
+ return { declarations, properties, themes: themeValues, docs };
276
358
  }
277
359
  async function scanVarDeclarations(patterns, exclude, selectors) {
278
360
  return (await scanCss(patterns, exclude, selectors)).declarations;
@@ -316,6 +398,29 @@ async function scanUsage(patterns, exclude) {
316
398
  for (const text of texts) extractUsage(text, usage);
317
399
  return usage;
318
400
  }
401
+ async function scanReferences(patterns, exclude) {
402
+ const normalized = normalizePatterns(patterns);
403
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
404
+ const files = (await fg(normalized, { absolute: true, ignore: normalizedExclude })).sort();
405
+ const perFile = await Promise.all(
406
+ files.map(async (file) => {
407
+ try {
408
+ return { file, css: await readFile(file, "utf8") };
409
+ } catch (err) {
410
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
411
+ return null;
412
+ }
413
+ })
414
+ );
415
+ const references = [];
416
+ const declared = /* @__PURE__ */ new Set();
417
+ for (const result of perFile) {
418
+ if (!result) continue;
419
+ for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
420
+ for (const name of parseDeclaredNames(result.css)) declared.add(name);
421
+ }
422
+ return { references, declared };
423
+ }
319
424
  async function scanUsedKeys(patterns, exclude) {
320
425
  return (await scanUsage(patterns, exclude)).keys;
321
426
  }
@@ -414,7 +519,8 @@ function entryMeta(name, options) {
414
519
  name,
415
520
  value: options.declarations?.get(name),
416
521
  syntax: options.properties?.get(name)?.syntax,
417
- ...themes.length > 0 ? { themes } : {}
522
+ ...themes.length > 0 ? { themes } : {},
523
+ ...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
418
524
  };
419
525
  }
420
526
  function buildEntries(varNames, options) {
@@ -454,8 +560,12 @@ function buildGroupedEntries(varNames, options) {
454
560
  const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
455
561
  return { groups, ungrouped };
456
562
  }
457
- function formatDefaultComment(value, indent = " ") {
458
- return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
563
+ var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
564
+ function renderJsDoc(tags, indent) {
565
+ if (tags.length === 0) return [];
566
+ if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
567
+ const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
568
+ return [`${indent}/**`, ...body, `${indent} */`];
459
569
  }
460
570
  function unquoteCssString(value) {
461
571
  const quote = value[0];
@@ -464,11 +574,15 @@ function unquoteCssString(value) {
464
574
  }
465
575
  return value;
466
576
  }
467
- function formatSyntaxComment(syntax, indent = " ") {
468
- return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
469
- }
470
- function formatThemeComment(theme, value, indent = " ") {
471
- return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
577
+ function entryTags({ value, syntax, themes, doc }) {
578
+ const deprecated = doc?.deprecated;
579
+ return [
580
+ ...doc?.description ? [doc.description] : [],
581
+ ...value ? [`@default ${value}`] : [],
582
+ ...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
583
+ ...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
584
+ ...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
585
+ ];
472
586
  }
473
587
  var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
474
588
  function parseEnumSyntax(syntax) {
@@ -500,11 +614,9 @@ function buildTailBlocks(varNames, group, properties) {
500
614
  return blocks;
501
615
  }
502
616
  function renderEntryLines(entries, indent, lineFor) {
503
- return entries.flatMap(({ key, name, value, syntax, themes }) => [
504
- ...value ? [formatDefaultComment(value, indent)] : [],
505
- ...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
506
- ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
507
- `${indent}${lineFor(key, name)}`
617
+ return entries.flatMap((entry) => [
618
+ ...renderJsDoc(entryTags(entry), indent),
619
+ `${indent}${lineFor(entry.key, entry.name)}`
508
620
  ]);
509
621
  }
510
622
  function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
@@ -551,6 +663,12 @@ var HELPERS_TS = [
551
663
  "",
552
664
  "export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
553
665
  " el.style.setProperty(ref.slice(4, -1), value);",
666
+ "}",
667
+ "",
668
+ "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
669
+ "",
670
+ "export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
671
+ " return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
554
672
  "}"
555
673
  ];
556
674
  var HELPERS_JS = [
@@ -560,11 +678,17 @@ var HELPERS_JS = [
560
678
  "",
561
679
  "export function setCssVar(ref, value, el = document.documentElement) {",
562
680
  " el.style.setProperty(ref.slice(4, -1), value);",
681
+ "}",
682
+ "",
683
+ "export function withFallback(ref, fallback) {",
684
+ " return `${ref.slice(0, -1)}, ${fallback})`;",
563
685
  "}"
564
686
  ];
565
687
  var HELPERS_DTS = [
566
688
  "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
567
- "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
689
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
690
+ "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
691
+ "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
568
692
  ];
569
693
  function generateCode(varNames, ...args) {
570
694
  const options = normalizeOptions(args);
@@ -633,6 +757,8 @@ function generateTokens(varNames, options = {}) {
633
757
  const token = { $value: resolve(value) };
634
758
  const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
635
759
  if (type) token.$type = type;
760
+ if (meta.doc?.description) token.$description = meta.doc.description;
761
+ if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
636
762
  if (meta.themes) {
637
763
  const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve(themeValue)]));
638
764
  token.$extensions = { "css-typed-vars": { themes } };
@@ -674,11 +800,14 @@ export {
674
800
  parseVarDeclarations,
675
801
  parseThemedDeclarations,
676
802
  parsePropertyRules,
803
+ parseVarReferences,
804
+ parseDeclaredNames,
677
805
  collectVarNames,
678
806
  scanCss,
679
807
  scanVarDeclarations,
680
808
  scanVarNames,
681
809
  scanUsage,
810
+ scanReferences,
682
811
  scanUsedKeys,
683
812
  VALID_NAMINGS,
684
813
  warnOnCollisions,
@@ -7,9 +7,10 @@ import {
7
7
  generateTokens,
8
8
  partitionUnused,
9
9
  scanCss,
10
+ scanReferences,
10
11
  scanUsage,
11
12
  warnOnCollisions
12
- } from "./chunk-6YWE4A6S.js";
13
+ } from "./chunk-5HPTHW7S.js";
13
14
 
14
15
  // src/index.ts
15
16
  import { writeFile, mkdir, readFile } from "fs/promises";
@@ -23,6 +24,14 @@ async function findUnusedVars(options) {
23
24
  const names = collectVarNames(scanned);
24
25
  return partitionUnused(names, usage, options).unused;
25
26
  }
27
+ function matchesIgnore(name, patterns) {
28
+ return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
29
+ }
30
+ async function findUndefinedRefs(options) {
31
+ const { references, declared } = await scanReferences(options.input, options.exclude);
32
+ const ignore = options.refsIgnore ?? [];
33
+ return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
34
+ }
26
35
  async function computeOutputs(options) {
27
36
  assertPruneCompatible(options);
28
37
  const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
@@ -48,7 +57,8 @@ async function computeOutputs(options) {
48
57
  group: options.group,
49
58
  properties,
50
59
  helpers: options.helpers,
51
- themes: scanned.themes
60
+ themes: scanned.themes,
61
+ docs: scanned.docs
52
62
  };
53
63
  if (/\.json$/i.test(options.output)) {
54
64
  return { outPath, content: generateTokens(names, generatorOptions) };
@@ -83,6 +93,7 @@ async function checkGenerated(options) {
83
93
 
84
94
  export {
85
95
  findUnusedVars,
96
+ findUndefinedRefs,
86
97
  generate,
87
98
  checkGenerated
88
99
  };