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/dist/cli.cjs CHANGED
@@ -159,7 +159,7 @@ function extractValue(text, start) {
159
159
  }
160
160
  function scanDeclarations(css, selectors, onProperty) {
161
161
  const stripped = stripComments(css);
162
- const allSelectors = [":root", ...selectors ?? []];
162
+ const allSelectors = [":root", "@theme", ...selectors ?? []];
163
163
  for (const sel of allSelectors) {
164
164
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
165
165
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
@@ -182,12 +182,41 @@ function parseVarDeclarations(css, selectors) {
182
182
  scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
183
183
  return declarations;
184
184
  }
185
+ var PROPERTY_DESCRIPTORS = [
186
+ ["syntax", "syntax"],
187
+ ["inherits", "inherits"],
188
+ ["initial-value", "initialValue"]
189
+ ];
190
+ function parsePropertyRules(css) {
191
+ const stripped = stripComments(css);
192
+ const rules = /* @__PURE__ */ new Map();
193
+ const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
194
+ let match;
195
+ while (match = openRegex.exec(stripped)) {
196
+ const name = match[1];
197
+ const start = match.index + match[0].length;
198
+ const block = extractBlock(stripped, start);
199
+ const masked = maskQuotedContent(block);
200
+ const rule = {};
201
+ for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
202
+ const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
203
+ const descMatch = descRegex.exec(masked);
204
+ if (!descMatch) continue;
205
+ const nameEnd = descMatch.index + descMatch[0].length;
206
+ const colonIndex = block.indexOf(":", nameEnd);
207
+ rule[key] = extractValue(block, colonIndex + 1);
208
+ }
209
+ if (Object.keys(rule).length > 0) rules.set(name, rule);
210
+ openRegex.lastIndex = start + block.length + 1;
211
+ }
212
+ return rules;
213
+ }
185
214
 
186
215
  // src/scanner.ts
187
216
  function normalizePatterns(patterns) {
188
217
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
189
218
  }
190
- async function scanVarDeclarations(patterns, exclude, selectors) {
219
+ async function scanCss(patterns, exclude, selectors) {
191
220
  const normalized = normalizePatterns(patterns);
192
221
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
193
222
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -198,16 +227,49 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
198
227
  css = await (0, import_promises.readFile)(file, "utf8");
199
228
  } catch (err) {
200
229
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
201
- return /* @__PURE__ */ new Map();
230
+ return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
202
231
  }
203
- return parseVarDeclarations(css, selectors);
232
+ return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
204
233
  })
205
234
  );
206
- const all = /* @__PURE__ */ new Map();
207
- for (const declarations of perFile) {
208
- for (const [name, value] of declarations) {
209
- all.set(name, value);
210
- }
235
+ const declarations = /* @__PURE__ */ new Map();
236
+ const properties = /* @__PURE__ */ new Map();
237
+ for (const result of perFile) {
238
+ for (const [name, value] of result.declarations) declarations.set(name, value);
239
+ for (const [name, rule] of result.properties) properties.set(name, rule);
240
+ }
241
+ return { declarations, properties };
242
+ }
243
+ async function scanVarDeclarations(patterns, exclude, selectors) {
244
+ return (await scanCss(patterns, exclude, selectors)).declarations;
245
+ }
246
+ var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
247
+ function extractUsedKeys(text, into) {
248
+ for (const match of text.matchAll(USAGE_RE)) {
249
+ into.add(match[1] ?? match[3]);
250
+ }
251
+ }
252
+ async function scanUsedKeys(patterns, exclude) {
253
+ const normalized = normalizePatterns(patterns);
254
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
255
+ const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
256
+ const perFile = await Promise.all(
257
+ files.map(async (file) => {
258
+ const used = /* @__PURE__ */ new Set();
259
+ let text;
260
+ try {
261
+ text = await (0, import_promises.readFile)(file, "utf8");
262
+ } catch (err) {
263
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
264
+ return used;
265
+ }
266
+ extractUsedKeys(text, used);
267
+ return used;
268
+ })
269
+ );
270
+ const all = /* @__PURE__ */ new Set();
271
+ for (const used of perFile) {
272
+ for (const key of used) all.add(key);
211
273
  }
212
274
  return all;
213
275
  }
@@ -224,10 +286,19 @@ function convertCase(value, naming) {
224
286
  if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
225
287
  return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
226
288
  }
227
- function toKey(cssVarName, naming = "camelCase") {
228
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
289
+ function toKeyFragment(fragment, naming = "camelCase") {
290
+ const key = convertCase(fragment, naming);
229
291
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
230
292
  }
293
+ function toKey(cssVarName, naming = "camelCase") {
294
+ return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
295
+ }
296
+ function splitGroupKey(cssVarName) {
297
+ const stripped = cssVarName.replace(/^--/, "");
298
+ const dashIndex = stripped.indexOf("-");
299
+ if (dashIndex === -1) return null;
300
+ return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
301
+ }
231
302
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
232
303
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
233
304
  var SINGLE_QUOTE_ESCAPES = {};
@@ -260,6 +331,9 @@ function formatKey(key, naming = "camelCase") {
260
331
  if (naming === "kebab") return `'${key}'`;
261
332
  return key;
262
333
  }
334
+ function computeKey(cssVarName, prefix, naming) {
335
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
336
+ }
263
337
  function findKeyCollisions(varNames, prefix, naming) {
264
338
  const byKey = /* @__PURE__ */ new Map();
265
339
  for (const name of varNames) {
@@ -278,37 +352,126 @@ function warnOnCollisions(varNames, prefix, naming) {
278
352
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
279
353
  }
280
354
  }
281
- function buildEntries(varNames, prefix, naming, declarations) {
355
+ function buildEntries(varNames, prefix, naming, declarations, properties) {
282
356
  const byKey = /* @__PURE__ */ new Map();
283
357
  for (const name of varNames) {
284
358
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
285
- byKey.set(key, { name, value: declarations?.get(name) });
359
+ byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
286
360
  }
287
361
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
288
362
  }
289
- function formatDefaultComment(value) {
290
- return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
363
+ function buildGroupedEntries(varNames, naming, declarations, properties) {
364
+ const groupMap = /* @__PURE__ */ new Map();
365
+ const ungroupedMap = /* @__PURE__ */ new Map();
366
+ for (const name of varNames) {
367
+ const value = declarations?.get(name);
368
+ const syntax = properties?.get(name)?.syntax;
369
+ const split = splitGroupKey(name);
370
+ if (!split) {
371
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
372
+ continue;
373
+ }
374
+ const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
375
+ const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
376
+ let leafMap = groupMap.get(groupKey);
377
+ if (!leafMap) {
378
+ leafMap = /* @__PURE__ */ new Map();
379
+ groupMap.set(groupKey, leafMap);
380
+ }
381
+ leafMap.set(leafKey, { name, value, syntax });
382
+ }
383
+ for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
384
+ const groups = [...groupMap].map(([key, leafMap]) => ({
385
+ key,
386
+ entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
387
+ }));
388
+ const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
389
+ return { groups, ungrouped };
390
+ }
391
+ function formatDefaultComment(value, indent = " ") {
392
+ return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
393
+ }
394
+ function unquoteCssString(value) {
395
+ const quote = value[0];
396
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
397
+ return value.slice(1, -1);
398
+ }
399
+ return value;
291
400
  }
292
- function generateCode(varNames, prefix, naming, declarations) {
293
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
294
- ...value ? [formatDefaultComment(value)] : [],
295
- ` ${key}: 'var(${name})',`
401
+ function formatSyntaxComment(syntax, indent = " ") {
402
+ return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
403
+ }
404
+ var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
405
+ function parseEnumSyntax(syntax) {
406
+ const unquoted = unquoteCssString(syntax).trim();
407
+ if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
408
+ return unquoted.split("|").map((v) => v.trim());
409
+ }
410
+ function syntaxTypeName(cssVarName) {
411
+ const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
412
+ return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
413
+ }
414
+ function buildSyntaxTypes(varNames, properties) {
415
+ if (!properties) return [];
416
+ const byName = /* @__PURE__ */ new Map();
417
+ for (const name of varNames) {
418
+ const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
419
+ if (values) byName.set(syntaxTypeName(name), values);
420
+ }
421
+ return [...byName].map(([name, values]) => ({ name, values }));
422
+ }
423
+ function renderSyntaxTypeLines(types) {
424
+ return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
425
+ }
426
+ function buildTailBlocks(varNames, group, properties) {
427
+ const blocks = [];
428
+ if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
429
+ const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
430
+ if (syntaxLines.length > 0) blocks.push(syntaxLines);
431
+ return blocks;
432
+ }
433
+ function renderEntryLines(entries, indent, lineFor) {
434
+ return entries.flatMap(({ key, name, value, syntax }) => [
435
+ ...value ? [formatDefaultComment(value, indent)] : [],
436
+ ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
437
+ `${indent}${lineFor(key, name)}`
296
438
  ]);
439
+ }
440
+ function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
441
+ const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
442
+ const lines = [];
443
+ for (const group of groups) {
444
+ lines.push(`${indent}${group.key}: {`);
445
+ lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
446
+ lines.push(`${indent}}${closeSuffix}`);
447
+ }
448
+ lines.push(...renderEntryLines(ungrouped, indent, lineFor));
449
+ return lines;
450
+ }
451
+ function assertGroupPrefixCompatible(prefix, group) {
452
+ if (group && prefix) {
453
+ throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
454
+ }
455
+ }
456
+ var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
457
+ var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
458
+ function generateCode(varNames, prefix, naming, declarations, group, properties) {
459
+ assertGroupPrefixCompatible(prefix, group);
460
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
461
+ const blocks = buildTailBlocks(varNames, group, properties);
462
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
297
463
  return [
298
464
  "// generated \u2014 do not edit",
299
465
  "export const cssVars = {",
300
466
  ...entries,
301
467
  "} as const;",
302
- "",
303
- "export type CssVarName = keyof typeof cssVars;",
468
+ ...tailBody.length > 0 ? ["", ...tailBody] : [],
304
469
  ""
305
470
  ].join("\n");
306
471
  }
307
- function generateJs(varNames, prefix, naming, declarations) {
308
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
309
- ...value ? [formatDefaultComment(value)] : [],
310
- ` ${key}: 'var(${name})',`
311
- ]);
472
+ function generateJs(varNames, prefix, naming, declarations, group, properties) {
473
+ assertGroupPrefixCompatible(prefix, group);
474
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
312
475
  return [
313
476
  "// generated \u2014 do not edit",
314
477
  "export const cssVars = {",
@@ -317,37 +480,68 @@ function generateJs(varNames, prefix, naming, declarations) {
317
480
  ""
318
481
  ].join("\n");
319
482
  }
320
- function generateDeclaration(varNames, prefix, naming, declarations) {
321
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
322
- ...value ? [formatDefaultComment(value)] : [],
323
- ` ${key}: 'var(${name})';`
324
- ]);
483
+ function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
484
+ assertGroupPrefixCompatible(prefix, group);
485
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
486
+ const blocks = buildTailBlocks(varNames, group, properties);
487
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
325
488
  return [
326
489
  "export declare const cssVars: {",
327
490
  ...entries,
328
491
  "};",
329
- "export type CssVarName = keyof typeof cssVars;",
492
+ ...tailBody,
330
493
  ""
331
494
  ].join("\n");
332
495
  }
333
496
 
334
497
  // src/index.ts
335
- async function computeOutputs(options) {
336
- const declarations = await scanVarDeclarations(options.input, options.exclude, options.selectors);
498
+ function assertPruneCompatible(options) {
499
+ if (!options.prune) return;
500
+ if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
501
+ if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
502
+ }
503
+ function partitionUnused(names, usedKeys, prefix, naming) {
504
+ const used = [];
505
+ const unused = [];
506
+ for (const name of names) {
507
+ (usedKeys.has(computeKey(name, prefix, naming)) ? used : unused).push(name);
508
+ }
509
+ return { used, unused };
510
+ }
511
+ async function findUnusedVars(options) {
512
+ if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
513
+ const [declarations, usedKeys] = await Promise.all([
514
+ scanVarDeclarations(options.input, options.exclude, options.selectors),
515
+ scanUsedKeys(options.usage, options.usageExclude)
516
+ ]);
337
517
  const names = [...declarations.keys()].sort();
518
+ return partitionUnused(names, usedKeys, options.prefix, options.naming).unused;
519
+ }
520
+ async function computeOutputs(options) {
521
+ assertPruneCompatible(options);
522
+ const { declarations, properties } = await scanCss(options.input, options.exclude, options.selectors);
523
+ let names = [...declarations.keys()].sort();
338
524
  if (names.length === 0) {
339
525
  console.warn("css-typed-vars: no CSS custom properties found.");
340
526
  }
341
527
  warnOnCollisions(names, options.prefix, options.naming);
528
+ if (options.prune) {
529
+ const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
530
+ const { used, unused } = partitionUnused(names, usedKeys, options.prefix, options.naming);
531
+ if (unused.length > 0) {
532
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
533
+ }
534
+ names = used;
535
+ }
342
536
  const outPath = (0, import_node_path.resolve)(options.output);
343
537
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
344
538
  if (jsExtMatch) {
345
- const content = generateJs(names, options.prefix, options.naming, declarations);
539
+ const content = generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
346
540
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
347
- const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations);
541
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
348
542
  return { outPath, content, dtsPath, dtsContent };
349
543
  }
350
- return { outPath, content: generateCode(names, options.prefix, options.naming, declarations) };
544
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations, options.group, properties) };
351
545
  }
352
546
  async function generate(options) {
353
547
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
@@ -386,6 +580,9 @@ var getArgs = (flag) => {
386
580
  };
387
581
  var watchMode = args.includes("--watch");
388
582
  var checkMode = args.includes("--check");
583
+ var groupFlag = args.includes("--group");
584
+ var pruneFlag = args.includes("--prune");
585
+ var pruneCheckMode = args.includes("--prune-check");
389
586
  async function loadConfig() {
390
587
  const candidates = [
391
588
  "css-typed-vars.config.js",
@@ -410,9 +607,9 @@ async function loadConfig() {
410
607
  }
411
608
  return {};
412
609
  }
413
- async function run(input, output, exclude, prefix, naming, selectors) {
414
- await generate({ input, output, exclude, prefix, naming, selectors });
415
- console.log(`Generated \u2192 ${output}`);
610
+ async function run(options) {
611
+ await generate(options);
612
+ console.log(`Generated \u2192 ${options.output}`);
416
613
  }
417
614
  async function main() {
418
615
  if (args.includes("--version") || args.includes("-v")) {
@@ -435,8 +632,14 @@ async function main() {
435
632
  const naming = namingRaw;
436
633
  const selectorArgs = getArgs("--selector");
437
634
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
635
+ const group = groupFlag || config.group;
636
+ const prune = pruneFlag || config.prune;
637
+ const usageArgs = getArgs("--usage");
638
+ const usage = usageArgs.length > 0 ? usageArgs : config.usage;
639
+ const usageExcludeArgs = getArgs("--usage-exclude");
640
+ const usageExclude = usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude;
438
641
  if (!input || !output) {
439
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check]");
642
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--prune --usage <glob>] [--prune-check --usage <glob>]");
440
643
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
441
644
  process.exit(1);
442
645
  }
@@ -444,8 +647,34 @@ async function main() {
444
647
  console.error("css-typed-vars: --check cannot be combined with --watch.");
445
648
  process.exit(1);
446
649
  }
650
+ if (pruneCheckMode && (watchMode || checkMode)) {
651
+ console.error("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
652
+ process.exit(1);
653
+ }
654
+ if (group && prefix) {
655
+ console.error("css-typed-vars: --group cannot be combined with --prefix.");
656
+ process.exit(1);
657
+ }
658
+ if ((prune || pruneCheckMode) && group) {
659
+ console.error("css-typed-vars: --prune/--prune-check cannot be combined with --group.");
660
+ process.exit(1);
661
+ }
662
+ if ((prune || pruneCheckMode) && !usage) {
663
+ console.error("css-typed-vars: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).");
664
+ process.exit(1);
665
+ }
666
+ if (pruneCheckMode) {
667
+ const unused = await findUnusedVars({ input, exclude, selectors, prefix, naming, usage, usageExclude });
668
+ if (unused.length > 0) {
669
+ console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
670
+ process.exit(1);
671
+ }
672
+ console.log("css-typed-vars: no unused variables.");
673
+ return;
674
+ }
675
+ const runOptions = { input, output, exclude, prefix, naming, selectors, group, prune, usage, usageExclude };
447
676
  if (checkMode) {
448
- const upToDate = await checkGenerated({ input, output, exclude, prefix, naming, selectors });
677
+ const upToDate = await checkGenerated(runOptions);
449
678
  if (!upToDate) {
450
679
  console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
451
680
  process.exit(1);
@@ -453,12 +682,12 @@ async function main() {
453
682
  console.log(`css-typed-vars: "${output}" is up to date.`);
454
683
  return;
455
684
  }
456
- await run(input, output, exclude, prefix, naming, selectors);
685
+ await run(runOptions);
457
686
  if (watchMode) {
458
687
  const patterns = Array.isArray(input) ? input : [input];
459
688
  const makeHandler = (label) => (file) => {
460
689
  console.log(`${label}: ${file}`);
461
- run(input, output, exclude, prefix, naming, selectors).catch(console.error);
690
+ run(runOptions).catch(console.error);
462
691
  };
463
692
  const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
464
693
  (0, import_chokidar.watch)(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
package/dist/cli.js CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  checkGenerated,
4
+ findUnusedVars,
4
5
  generate
5
- } from "./chunk-H3T6RMQQ.js";
6
+ } from "./chunk-VZ2BHHXD.js";
6
7
  import {
7
8
  VALID_NAMINGS
8
- } from "./chunk-JDZAH2YQ.js";
9
+ } from "./chunk-LH53WYFF.js";
9
10
 
10
11
  // src/cli.ts
11
12
  import { readFile } from "fs/promises";
@@ -29,6 +30,9 @@ var getArgs = (flag) => {
29
30
  };
30
31
  var watchMode = args.includes("--watch");
31
32
  var checkMode = args.includes("--check");
33
+ var groupFlag = args.includes("--group");
34
+ var pruneFlag = args.includes("--prune");
35
+ var pruneCheckMode = args.includes("--prune-check");
32
36
  async function loadConfig() {
33
37
  const candidates = [
34
38
  "css-typed-vars.config.js",
@@ -53,9 +57,9 @@ async function loadConfig() {
53
57
  }
54
58
  return {};
55
59
  }
56
- async function run(input, output, exclude, prefix, naming, selectors) {
57
- await generate({ input, output, exclude, prefix, naming, selectors });
58
- console.log(`Generated \u2192 ${output}`);
60
+ async function run(options) {
61
+ await generate(options);
62
+ console.log(`Generated \u2192 ${options.output}`);
59
63
  }
60
64
  async function main() {
61
65
  if (args.includes("--version") || args.includes("-v")) {
@@ -78,8 +82,14 @@ async function main() {
78
82
  const naming = namingRaw;
79
83
  const selectorArgs = getArgs("--selector");
80
84
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
85
+ const group = groupFlag || config.group;
86
+ const prune = pruneFlag || config.prune;
87
+ const usageArgs = getArgs("--usage");
88
+ const usage = usageArgs.length > 0 ? usageArgs : config.usage;
89
+ const usageExcludeArgs = getArgs("--usage-exclude");
90
+ const usageExclude = usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude;
81
91
  if (!input || !output) {
82
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check]");
92
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--prune --usage <glob>] [--prune-check --usage <glob>]");
83
93
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
84
94
  process.exit(1);
85
95
  }
@@ -87,8 +97,34 @@ async function main() {
87
97
  console.error("css-typed-vars: --check cannot be combined with --watch.");
88
98
  process.exit(1);
89
99
  }
100
+ if (pruneCheckMode && (watchMode || checkMode)) {
101
+ console.error("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
102
+ process.exit(1);
103
+ }
104
+ if (group && prefix) {
105
+ console.error("css-typed-vars: --group cannot be combined with --prefix.");
106
+ process.exit(1);
107
+ }
108
+ if ((prune || pruneCheckMode) && group) {
109
+ console.error("css-typed-vars: --prune/--prune-check cannot be combined with --group.");
110
+ process.exit(1);
111
+ }
112
+ if ((prune || pruneCheckMode) && !usage) {
113
+ console.error("css-typed-vars: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).");
114
+ process.exit(1);
115
+ }
116
+ if (pruneCheckMode) {
117
+ const unused = await findUnusedVars({ input, exclude, selectors, prefix, naming, usage, usageExclude });
118
+ if (unused.length > 0) {
119
+ console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
120
+ process.exit(1);
121
+ }
122
+ console.log("css-typed-vars: no unused variables.");
123
+ return;
124
+ }
125
+ const runOptions = { input, output, exclude, prefix, naming, selectors, group, prune, usage, usageExclude };
90
126
  if (checkMode) {
91
- const upToDate = await checkGenerated({ input, output, exclude, prefix, naming, selectors });
127
+ const upToDate = await checkGenerated(runOptions);
92
128
  if (!upToDate) {
93
129
  console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
94
130
  process.exit(1);
@@ -96,12 +132,12 @@ async function main() {
96
132
  console.log(`css-typed-vars: "${output}" is up to date.`);
97
133
  return;
98
134
  }
99
- await run(input, output, exclude, prefix, naming, selectors);
135
+ await run(runOptions);
100
136
  if (watchMode) {
101
137
  const patterns = Array.isArray(input) ? input : [input];
102
138
  const makeHandler = (label) => (file) => {
103
139
  console.log(`${label}: ${file}`);
104
- run(input, output, exclude, prefix, naming, selectors).catch(console.error);
140
+ run(runOptions).catch(console.error);
105
141
  };
106
142
  const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
107
143
  watch(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));