css-typed-vars 0.5.0 → 0.6.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
@@ -2,6 +2,7 @@
2
2
 
3
3
  <h1>css-typed-vars</h1>
4
4
  <p>Generate TypeScript typed constants from CSS custom properties</p>
5
+ <p><a href="https://stanislavkozachenko.github.io/css-typed-vars/">📖 Full documentation</a></p>
5
6
 
6
7
  <p>
7
8
  <a href="https://github.com/StanislavKozachenko/css-typed-vars/actions"><img src="https://github.com/StanislavKozachenko/css-typed-vars/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
@@ -27,6 +28,7 @@
27
28
  - [Usage](#usage)
28
29
  - [Programmatic API](#programmatic-api)
29
30
  - [Supported formats](#supported-formats)
31
+ - [@property syntax typing](#property-syntax-typing)
30
32
  - [Contributing](#contributing)
31
33
 
32
34
  ---
@@ -35,7 +37,7 @@
35
37
 
36
38
  `css-typed-vars` scans your CSS files and gives you typed constants. Use `cssVars.colorPrimary` instead — TypeScript catches missing variables at compile time.
37
39
 
38
- Each generated key also carries a `/** @default ... */` comment with the property's declared CSS value, so your editor shows it on hover and autocomplete.
40
+ Each generated key also carries a `/** @default ... */` comment with the property's declared CSS value, so your editor shows it on hover and autocomplete. If the variable is registered with [`@property`](#property-syntax-typing), its `syntax` descriptor shows up too, and an enum-like syntax (e.g. `"light | dark | system"`) gets its own exported TS union type.
39
41
 
40
42
  ## Installation
41
43
 
@@ -118,6 +120,9 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prefix theme
118
120
  npx css-typed-vars --input "src/**/*.css" --output src/cssVars.js # generates .js + .d.ts
119
121
  npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --selector ".dark" --selector "[data-theme='dark']"
120
122
  npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --check # for CI: exits 1 if out of date
123
+ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --group # nest keys by first name segment
124
+ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune --usage "src/**/*.{ts,tsx}" # drop unused vars from the output
125
+ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check --usage "src/**/*.{ts,tsx}" # for CI: exits 1 if any var is unused
121
126
  ```
122
127
 
123
128
  | Flag | Description |
@@ -128,10 +133,24 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --check # for
128
133
  | `--prefix` | Prefix for generated keys: `--prefix theme` → `themeColorPrimary` |
129
134
  | `--naming` | Key naming: `camelCase` (default), `snake`, `kebab`, `constant`, `pascal` |
130
135
  | `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
136
+ | `--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`. |
137
+ | `--prune` | Drop generated vars with no detected `cssVars.<key>` usage. Requires `--usage <glob>` (repeatable). Can't be combined with `--group`. |
138
+ | `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Useful in CI. |
139
+ | `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
140
+ | `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
131
141
  | `--watch` | Watch for file changes and regenerate |
132
142
  | `--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`. |
133
143
  | `--version`, `-v` | Print the version number and exit |
134
144
 
145
+ ### Pruning unused variables
146
+
147
+ `--prune`/`--prune-check` scan your source files for `cssVars.<key>` (dot access) or `cssVars['<key>']`/`cssVars["<key>"]` (bracket access) usage and compare that against the generated keys. This is a textual scan, not a full parser, so it has two limitations worth knowing:
148
+
149
+ - It won't see through a renamed import (`import { cssVars as vars } from './cssVars'` — usages via `vars.foo` aren't detected).
150
+ - A match inside a comment or string still counts as "used".
151
+
152
+ When in doubt, use `--prune-check` in CI to review what it would remove before turning on `--prune` for real.
153
+
135
154
  CLI flags override values from the config file.
136
155
 
137
156
  ### Config file
@@ -153,6 +172,9 @@ export default {
153
172
  prefix: 'theme',
154
173
  naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
155
174
  selectors: ['.dark', '[data-theme="dark"]'],
175
+ group: false,
176
+ prune: false,
177
+ usage: 'src/**/*.{ts,tsx}',
156
178
  };
157
179
  ```
158
180
 
@@ -251,6 +273,10 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
251
273
  | `prefix` | `string` | — | Prefix for generated keys: `'theme'` → `themeColorPrimary` |
252
274
  | `naming` | `'camelCase' \| 'snake' \| 'kebab' \| 'constant' \| 'pascal'` | `'camelCase'` | Key naming convention |
253
275
  | `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
276
+ | `group` | `boolean` | `false` | Nest keys by each variable's first hyphen segment, e.g. `cssVars.color.primary`. Can't be combined with `prefix` |
277
+ | `prune` | `boolean` | `false` | Drop vars with no detected `cssVars.<key>` usage. Requires `usage`. Can't be combined with `group` |
278
+ | `usage` | `string \| string[]` | — | Glob(s) of source files to scan for `cssVars` usage, for `prune` |
279
+ | `usageExclude` | `string \| string[]` | — | Glob(s) of source files to exclude from the usage scan |
254
280
  | `dts` | `string \| false` | inside `node_modules` | Path to write type declarations. `false` to skip |
255
281
 
256
282
  ---
@@ -308,15 +334,20 @@ await generate({
308
334
  prefix: 'theme',
309
335
  naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
310
336
  selectors: ['.dark', '[data-theme="dark"]'],
337
+ group: false, // nest keys by first hyphen segment, e.g. cssVars.color.primary
338
+ prune: false, // drop vars with no detected cssVars.<key> usage (requires `usage`)
339
+ usage: 'src/**/*.{ts,tsx}',
311
340
  });
312
341
  ```
313
342
 
314
343
  `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.
315
344
 
345
+ `findUnusedVars(options)` takes `input`/`exclude`/`selectors`/`prefix`/`naming`/`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.
346
+
316
347
  Lower-level exports:
317
348
 
318
349
  ```ts
319
- import { parseVarNames, parseVarDeclarations, generateCode, scanVarNames, scanVarDeclarations } from 'css-typed-vars';
350
+ import { parseVarNames, parseVarDeclarations, parsePropertyRules, generateCode, scanVarNames, scanVarDeclarations, scanCss, scanUsedKeys } from 'css-typed-vars';
320
351
  ```
321
352
 
322
353
  ## Supported formats
@@ -327,7 +358,38 @@ import { parseVarNames, parseVarDeclarations, generateCode, scanVarNames, scanVa
327
358
  | SCSS | `.scss` |
328
359
  | Less | `.less` |
329
360
 
330
- By default, variables are scanned from `:root {}` blocks (including attribute selectors like `:root[data-theme="dark"]`). Use the `selectors` option to also pick up variables from other selectors such as `.dark` or `[data-theme="dark"]`.
361
+ By default, variables are scanned from `:root {}` blocks (including attribute selectors like `:root[data-theme="dark"]`) and Tailwind CSS v4's `@theme {}` blocks. Use the `selectors` option to also pick up variables from other selectors such as `.dark` or `[data-theme="dark"]`.
362
+
363
+ ## @property syntax typing
364
+
365
+ If a variable is registered via the [CSS Properties and Values API](https://developer.mozilla.org/en-US/docs/Web/CSS/@property), its `syntax` descriptor is picked up automatically — no config needed:
366
+
367
+ ```css
368
+ @property --theme-mode {
369
+ syntax: "light | dark | system";
370
+ inherits: true;
371
+ initial-value: light;
372
+ }
373
+ :root {
374
+ --theme-mode: light;
375
+ }
376
+ ```
377
+
378
+ ```ts
379
+ export const cssVars = {
380
+ /** @default light */
381
+ /** @syntax light | dark | system */
382
+ themeMode: 'var(--theme-mode)',
383
+ } as const;
384
+
385
+ export type CssVarName = keyof typeof cssVars;
386
+
387
+ export type ThemeModeSyntax = 'light' | 'dark' | 'system';
388
+ ```
389
+
390
+ 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)`.
391
+
392
+ 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.
331
393
 
332
394
  ## Contributing
333
395
 
@@ -123,7 +123,7 @@ function extractValue(text, start) {
123
123
  }
124
124
  function scanDeclarations(css, selectors, onProperty) {
125
125
  const stripped = stripComments(css);
126
- const allSelectors = [":root", ...selectors ?? []];
126
+ const allSelectors = [":root", "@theme", ...selectors ?? []];
127
127
  for (const sel of allSelectors) {
128
128
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
129
129
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
@@ -151,6 +151,35 @@ function parseVarDeclarations(css, selectors) {
151
151
  scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
152
152
  return declarations;
153
153
  }
154
+ var PROPERTY_DESCRIPTORS = [
155
+ ["syntax", "syntax"],
156
+ ["inherits", "inherits"],
157
+ ["initial-value", "initialValue"]
158
+ ];
159
+ function parsePropertyRules(css) {
160
+ const stripped = stripComments(css);
161
+ const rules = /* @__PURE__ */ new Map();
162
+ const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
163
+ let match;
164
+ while (match = openRegex.exec(stripped)) {
165
+ const name = match[1];
166
+ const start = match.index + match[0].length;
167
+ const block = extractBlock(stripped, start);
168
+ const masked = maskQuotedContent(block);
169
+ const rule = {};
170
+ for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
171
+ const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
172
+ const descMatch = descRegex.exec(masked);
173
+ if (!descMatch) continue;
174
+ const nameEnd = descMatch.index + descMatch[0].length;
175
+ const colonIndex = block.indexOf(":", nameEnd);
176
+ rule[key] = extractValue(block, colonIndex + 1);
177
+ }
178
+ if (Object.keys(rule).length > 0) rules.set(name, rule);
179
+ openRegex.lastIndex = start + block.length + 1;
180
+ }
181
+ return rules;
182
+ }
154
183
 
155
184
  // src/scanner.ts
156
185
  import { readFile } from "fs/promises";
@@ -158,7 +187,7 @@ import fg from "fast-glob";
158
187
  function normalizePatterns(patterns) {
159
188
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
160
189
  }
161
- async function scanVarDeclarations(patterns, exclude, selectors) {
190
+ async function scanCss(patterns, exclude, selectors) {
162
191
  const normalized = normalizePatterns(patterns);
163
192
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
164
193
  const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
@@ -169,23 +198,56 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
169
198
  css = await readFile(file, "utf8");
170
199
  } catch (err) {
171
200
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
172
- return /* @__PURE__ */ new Map();
201
+ return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
173
202
  }
174
- return parseVarDeclarations(css, selectors);
203
+ return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
175
204
  })
176
205
  );
177
- const all = /* @__PURE__ */ new Map();
178
- for (const declarations of perFile) {
179
- for (const [name, value] of declarations) {
180
- all.set(name, value);
181
- }
206
+ const declarations = /* @__PURE__ */ new Map();
207
+ const properties = /* @__PURE__ */ new Map();
208
+ for (const result of perFile) {
209
+ for (const [name, value] of result.declarations) declarations.set(name, value);
210
+ for (const [name, rule] of result.properties) properties.set(name, rule);
182
211
  }
183
- return all;
212
+ return { declarations, properties };
213
+ }
214
+ async function scanVarDeclarations(patterns, exclude, selectors) {
215
+ return (await scanCss(patterns, exclude, selectors)).declarations;
184
216
  }
185
217
  async function scanVarNames(patterns, exclude, selectors) {
186
218
  const declarations = await scanVarDeclarations(patterns, exclude, selectors);
187
219
  return [...declarations.keys()].sort();
188
220
  }
221
+ var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
222
+ function extractUsedKeys(text, into) {
223
+ for (const match of text.matchAll(USAGE_RE)) {
224
+ into.add(match[1] ?? match[3]);
225
+ }
226
+ }
227
+ async function scanUsedKeys(patterns, exclude) {
228
+ const normalized = normalizePatterns(patterns);
229
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
230
+ const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
231
+ const perFile = await Promise.all(
232
+ files.map(async (file) => {
233
+ const used = /* @__PURE__ */ new Set();
234
+ let text;
235
+ try {
236
+ text = await readFile(file, "utf8");
237
+ } catch (err) {
238
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
239
+ return used;
240
+ }
241
+ extractUsedKeys(text, used);
242
+ return used;
243
+ })
244
+ );
245
+ const all = /* @__PURE__ */ new Set();
246
+ for (const used of perFile) {
247
+ for (const key of used) all.add(key);
248
+ }
249
+ return all;
250
+ }
189
251
 
190
252
  // src/generator.ts
191
253
  var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
@@ -199,10 +261,19 @@ function convertCase(value, naming) {
199
261
  if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
200
262
  return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
201
263
  }
202
- function toKey(cssVarName, naming = "camelCase") {
203
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
264
+ function toKeyFragment(fragment, naming = "camelCase") {
265
+ const key = convertCase(fragment, naming);
204
266
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
205
267
  }
268
+ function toKey(cssVarName, naming = "camelCase") {
269
+ return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
270
+ }
271
+ function splitGroupKey(cssVarName) {
272
+ const stripped = cssVarName.replace(/^--/, "");
273
+ const dashIndex = stripped.indexOf("-");
274
+ if (dashIndex === -1) return null;
275
+ return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
276
+ }
206
277
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
207
278
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
208
279
  var SINGLE_QUOTE_ESCAPES = {};
@@ -235,6 +306,9 @@ function formatKey(key, naming = "camelCase") {
235
306
  if (naming === "kebab") return `'${key}'`;
236
307
  return key;
237
308
  }
309
+ function computeKey(cssVarName, prefix, naming) {
310
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
311
+ }
238
312
  function findKeyCollisions(varNames, prefix, naming) {
239
313
  const byKey = /* @__PURE__ */ new Map();
240
314
  for (const name of varNames) {
@@ -253,37 +327,126 @@ function warnOnCollisions(varNames, prefix, naming) {
253
327
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
254
328
  }
255
329
  }
256
- function buildEntries(varNames, prefix, naming, declarations) {
330
+ function buildEntries(varNames, prefix, naming, declarations, properties) {
257
331
  const byKey = /* @__PURE__ */ new Map();
258
332
  for (const name of varNames) {
259
333
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
260
- byKey.set(key, { name, value: declarations?.get(name) });
334
+ byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
261
335
  }
262
336
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
263
337
  }
264
- function formatDefaultComment(value) {
265
- return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
338
+ function buildGroupedEntries(varNames, naming, declarations, properties) {
339
+ const groupMap = /* @__PURE__ */ new Map();
340
+ const ungroupedMap = /* @__PURE__ */ new Map();
341
+ for (const name of varNames) {
342
+ const value = declarations?.get(name);
343
+ const syntax = properties?.get(name)?.syntax;
344
+ const split = splitGroupKey(name);
345
+ if (!split) {
346
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
347
+ continue;
348
+ }
349
+ const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
350
+ const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
351
+ let leafMap = groupMap.get(groupKey);
352
+ if (!leafMap) {
353
+ leafMap = /* @__PURE__ */ new Map();
354
+ groupMap.set(groupKey, leafMap);
355
+ }
356
+ leafMap.set(leafKey, { name, value, syntax });
357
+ }
358
+ for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
359
+ const groups = [...groupMap].map(([key, leafMap]) => ({
360
+ key,
361
+ entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
362
+ }));
363
+ const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
364
+ return { groups, ungrouped };
365
+ }
366
+ function formatDefaultComment(value, indent = " ") {
367
+ return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
368
+ }
369
+ function unquoteCssString(value) {
370
+ const quote = value[0];
371
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
372
+ return value.slice(1, -1);
373
+ }
374
+ return value;
375
+ }
376
+ function formatSyntaxComment(syntax, indent = " ") {
377
+ return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
378
+ }
379
+ var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
380
+ function parseEnumSyntax(syntax) {
381
+ const unquoted = unquoteCssString(syntax).trim();
382
+ if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
383
+ return unquoted.split("|").map((v) => v.trim());
266
384
  }
267
- function generateCode(varNames, prefix, naming, declarations) {
268
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
269
- ...value ? [formatDefaultComment(value)] : [],
270
- ` ${key}: 'var(${name})',`
385
+ function syntaxTypeName(cssVarName) {
386
+ const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
387
+ return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
388
+ }
389
+ function buildSyntaxTypes(varNames, properties) {
390
+ if (!properties) return [];
391
+ const byName = /* @__PURE__ */ new Map();
392
+ for (const name of varNames) {
393
+ const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
394
+ if (values) byName.set(syntaxTypeName(name), values);
395
+ }
396
+ return [...byName].map(([name, values]) => ({ name, values }));
397
+ }
398
+ function renderSyntaxTypeLines(types) {
399
+ return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
400
+ }
401
+ function buildTailBlocks(varNames, group, properties) {
402
+ const blocks = [];
403
+ if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
404
+ const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
405
+ if (syntaxLines.length > 0) blocks.push(syntaxLines);
406
+ return blocks;
407
+ }
408
+ function renderEntryLines(entries, indent, lineFor) {
409
+ return entries.flatMap(({ key, name, value, syntax }) => [
410
+ ...value ? [formatDefaultComment(value, indent)] : [],
411
+ ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
412
+ `${indent}${lineFor(key, name)}`
271
413
  ]);
414
+ }
415
+ function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
416
+ const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
417
+ const lines = [];
418
+ for (const group of groups) {
419
+ lines.push(`${indent}${group.key}: {`);
420
+ lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
421
+ lines.push(`${indent}}${closeSuffix}`);
422
+ }
423
+ lines.push(...renderEntryLines(ungrouped, indent, lineFor));
424
+ return lines;
425
+ }
426
+ function assertGroupPrefixCompatible(prefix, group) {
427
+ if (group && prefix) {
428
+ throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
429
+ }
430
+ }
431
+ var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
432
+ var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
433
+ function generateCode(varNames, prefix, naming, declarations, group, properties) {
434
+ assertGroupPrefixCompatible(prefix, group);
435
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
436
+ const blocks = buildTailBlocks(varNames, group, properties);
437
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
272
438
  return [
273
439
  "// generated \u2014 do not edit",
274
440
  "export const cssVars = {",
275
441
  ...entries,
276
442
  "} as const;",
277
- "",
278
- "export type CssVarName = keyof typeof cssVars;",
443
+ ...tailBody.length > 0 ? ["", ...tailBody] : [],
279
444
  ""
280
445
  ].join("\n");
281
446
  }
282
- function generateJs(varNames, prefix, naming, declarations) {
283
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
284
- ...value ? [formatDefaultComment(value)] : [],
285
- ` ${key}: 'var(${name})',`
286
- ]);
447
+ function generateJs(varNames, prefix, naming, declarations, group, properties) {
448
+ assertGroupPrefixCompatible(prefix, group);
449
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
287
450
  return [
288
451
  "// generated \u2014 do not edit",
289
452
  "export const cssVars = {",
@@ -292,16 +455,16 @@ function generateJs(varNames, prefix, naming, declarations) {
292
455
  ""
293
456
  ].join("\n");
294
457
  }
295
- function generateDeclaration(varNames, prefix, naming, declarations) {
296
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
297
- ...value ? [formatDefaultComment(value)] : [],
298
- ` ${key}: 'var(${name})';`
299
- ]);
458
+ function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
459
+ assertGroupPrefixCompatible(prefix, group);
460
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
461
+ const blocks = buildTailBlocks(varNames, group, properties);
462
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
300
463
  return [
301
464
  "export declare const cssVars: {",
302
465
  ...entries,
303
466
  "};",
304
- "export type CssVarName = keyof typeof cssVars;",
467
+ ...tailBody,
305
468
  ""
306
469
  ].join("\n");
307
470
  }
@@ -310,9 +473,13 @@ export {
310
473
  __dirname,
311
474
  parseVarNames,
312
475
  parseVarDeclarations,
476
+ parsePropertyRules,
477
+ scanCss,
313
478
  scanVarDeclarations,
314
479
  scanVarNames,
480
+ scanUsedKeys,
315
481
  VALID_NAMINGS,
482
+ computeKey,
316
483
  warnOnCollisions,
317
484
  generateCode,
318
485
  generateJs,
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  __dirname,
3
+ computeKey,
3
4
  generateDeclaration,
4
5
  generateJs,
5
- scanVarDeclarations,
6
+ scanCss,
7
+ scanUsedKeys,
6
8
  warnOnCollisions
7
- } from "./chunk-JDZAH2YQ.js";
9
+ } from "./chunk-LH53WYFF.js";
8
10
 
9
11
  // src/unplugin.ts
10
12
  import { createUnplugin } from "unplugin";
@@ -17,8 +19,27 @@ function getDtsPath(options) {
17
19
  return options.dts ? resolve(process.cwd(), options.dts) : join(__dirname, "generated.d.ts");
18
20
  }
19
21
  var unplugin_default = createUnplugin((options) => {
20
- let cachedDeclarations = null;
21
- const scan = () => scanVarDeclarations(options.input, options.exclude, options.selectors);
22
+ if (options.prune) {
23
+ if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
24
+ if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
25
+ }
26
+ let cachedScan = null;
27
+ const scan = () => scanCss(options.input, options.exclude, options.selectors);
28
+ const applyPrune = async (names) => {
29
+ if (!options.prune) return names;
30
+ const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
31
+ const isUsed = (name) => usedKeys.has(computeKey(name, options.prefix, options.naming));
32
+ const unused = names.filter((name) => !isUsed(name));
33
+ if (unused.length > 0) {
34
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
35
+ }
36
+ return names.filter(isUsed);
37
+ };
38
+ const resolveNames = async (declarations) => {
39
+ const names = [...declarations.keys()].sort();
40
+ warnOnCollisions(names, options.prefix, options.naming);
41
+ return applyPrune(names);
42
+ };
22
43
  return {
23
44
  name: "css-typed-vars",
24
45
  vite: {
@@ -29,15 +50,15 @@ var unplugin_default = createUnplugin((options) => {
29
50
  let writeQueue = Promise.resolve();
30
51
  const rescan = async () => {
31
52
  const myGeneration = ++generation;
32
- const declarationsPromise = scan();
33
- cachedDeclarations = declarationsPromise;
34
- const declarations = await declarationsPromise;
53
+ const scanPromise = scan();
54
+ cachedScan = scanPromise;
55
+ const { declarations, properties } = await scanPromise;
56
+ if (myGeneration !== generation) return;
57
+ const names = await resolveNames(declarations);
35
58
  if (myGeneration !== generation) return;
36
- const names = [...declarations.keys()].sort();
37
- warnOnCollisions(names, options.prefix, options.naming);
38
59
  const dtsPath = getDtsPath(options);
39
60
  if (dtsPath) {
40
- const content = generateDeclaration(names, options.prefix, options.naming, declarations);
61
+ const content = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
41
62
  writeQueue = writeQueue.then(async () => {
42
63
  if (myGeneration !== generation) return;
43
64
  await writeFile(dtsPath, content, "utf8");
@@ -65,22 +86,21 @@ var unplugin_default = createUnplugin((options) => {
65
86
  }
66
87
  },
67
88
  async buildStart() {
68
- cachedDeclarations = scan();
69
- const declarations = await cachedDeclarations;
70
- const names = [...declarations.keys()].sort();
71
- warnOnCollisions(names, options.prefix, options.naming);
89
+ cachedScan = scan();
90
+ const { declarations, properties } = await cachedScan;
91
+ const names = await resolveNames(declarations);
72
92
  const dtsPath = getDtsPath(options);
73
93
  if (!dtsPath) return;
74
- await writeFile(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations), "utf8");
94
+ await writeFile(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties), "utf8");
75
95
  },
76
96
  resolveId(id) {
77
97
  if (id === VIRTUAL_ID) return RESOLVED_ID;
78
98
  },
79
99
  async load(id) {
80
100
  if (id === RESOLVED_ID) {
81
- const declarations = await (cachedDeclarations ?? scan());
82
- const names = [...declarations.keys()].sort();
83
- return generateJs(names, options.prefix, options.naming, declarations);
101
+ const { declarations, properties } = await (cachedScan ?? scan());
102
+ const names = await applyPrune([...declarations.keys()].sort());
103
+ return generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
84
104
  }
85
105
  }
86
106
  };
@@ -0,0 +1,86 @@
1
+ import {
2
+ computeKey,
3
+ generateCode,
4
+ generateDeclaration,
5
+ generateJs,
6
+ scanCss,
7
+ scanUsedKeys,
8
+ scanVarDeclarations,
9
+ warnOnCollisions
10
+ } from "./chunk-LH53WYFF.js";
11
+
12
+ // src/index.ts
13
+ import { writeFile, mkdir, readFile } from "fs/promises";
14
+ import { dirname, resolve } from "path";
15
+ function assertPruneCompatible(options) {
16
+ if (!options.prune) return;
17
+ if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
18
+ if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
19
+ }
20
+ function partitionUnused(names, usedKeys, prefix, naming) {
21
+ const used = [];
22
+ const unused = [];
23
+ for (const name of names) {
24
+ (usedKeys.has(computeKey(name, prefix, naming)) ? used : unused).push(name);
25
+ }
26
+ return { used, unused };
27
+ }
28
+ async function findUnusedVars(options) {
29
+ if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
30
+ const [declarations, usedKeys] = await Promise.all([
31
+ scanVarDeclarations(options.input, options.exclude, options.selectors),
32
+ scanUsedKeys(options.usage, options.usageExclude)
33
+ ]);
34
+ const names = [...declarations.keys()].sort();
35
+ return partitionUnused(names, usedKeys, options.prefix, options.naming).unused;
36
+ }
37
+ async function computeOutputs(options) {
38
+ assertPruneCompatible(options);
39
+ const { declarations, properties } = await scanCss(options.input, options.exclude, options.selectors);
40
+ let names = [...declarations.keys()].sort();
41
+ if (names.length === 0) {
42
+ console.warn("css-typed-vars: no CSS custom properties found.");
43
+ }
44
+ warnOnCollisions(names, options.prefix, options.naming);
45
+ if (options.prune) {
46
+ const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
47
+ const { used, unused } = partitionUnused(names, usedKeys, options.prefix, options.naming);
48
+ if (unused.length > 0) {
49
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
50
+ }
51
+ names = used;
52
+ }
53
+ const outPath = resolve(options.output);
54
+ const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
55
+ if (jsExtMatch) {
56
+ const content = generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
57
+ const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
58
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
59
+ return { outPath, content, dtsPath, dtsContent };
60
+ }
61
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations, options.group, properties) };
62
+ }
63
+ async function generate(options) {
64
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
65
+ await mkdir(dirname(outPath), { recursive: true });
66
+ await writeFile(outPath, content, "utf8");
67
+ if (dtsPath && dtsContent !== void 0) {
68
+ await writeFile(dtsPath, dtsContent, "utf8");
69
+ }
70
+ }
71
+ async function checkGenerated(options) {
72
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
73
+ const current = await readFile(outPath, "utf8").catch(() => null);
74
+ if (current !== content) return false;
75
+ if (dtsPath && dtsContent !== void 0) {
76
+ const currentDts = await readFile(dtsPath, "utf8").catch(() => null);
77
+ if (currentDts !== dtsContent) return false;
78
+ }
79
+ return true;
80
+ }
81
+
82
+ export {
83
+ findUnusedVars,
84
+ generate,
85
+ checkGenerated
86
+ };