css-typed-vars 0.4.17 → 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
@@ -138,10 +138,28 @@ function maskQuotedContent(text) {
138
138
  }
139
139
  return result;
140
140
  }
141
- function parseVarNames(css, selectors) {
141
+ function extractValue(text, start) {
142
+ let i = start;
143
+ let quote = null;
144
+ for (; i < text.length; i++) {
145
+ const char = text[i];
146
+ if (quote) {
147
+ const step = stepQuote(text, i, quote);
148
+ if (step.closed) quote = null;
149
+ i += step.consumed - 1;
150
+ continue;
151
+ }
152
+ if (char === '"' || char === "'") {
153
+ quote = char;
154
+ continue;
155
+ }
156
+ if (char === ";" || char === "}") break;
157
+ }
158
+ return text.slice(start, i).trim();
159
+ }
160
+ function scanDeclarations(css, selectors, onProperty) {
142
161
  const stripped = stripComments(css);
143
- const names = /* @__PURE__ */ new Set();
144
- const allSelectors = [":root", ...selectors ?? []];
162
+ const allSelectors = [":root", "@theme", ...selectors ?? []];
145
163
  for (const sel of allSelectors) {
146
164
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
147
165
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
@@ -149,53 +167,138 @@ function parseVarNames(css, selectors) {
149
167
  while (match = openRegex.exec(stripped)) {
150
168
  const start = match.index + match[0].length;
151
169
  const block = extractBlock(stripped, start);
152
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
153
- names.add(prop[0]);
170
+ const masked = maskQuotedContent(block);
171
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
172
+ const name = prop[0];
173
+ const colonIndex = block.indexOf(":", prop.index + name.length);
174
+ onProperty(name, extractValue(block, colonIndex + 1));
154
175
  }
155
176
  openRegex.lastIndex = start + block.length + 1;
156
177
  }
157
178
  }
158
- return [...names];
179
+ }
180
+ function parseVarDeclarations(css, selectors) {
181
+ const declarations = /* @__PURE__ */ new Map();
182
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
183
+ return declarations;
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;
159
213
  }
160
214
 
161
215
  // src/scanner.ts
162
- async function scanVarNames(patterns, exclude, selectors) {
163
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
164
- (p) => p.replace(/\\/g, "/")
165
- );
166
- const normalizedExclude = exclude ? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => p.replace(/\\/g, "/")) : [];
216
+ function normalizePatterns(patterns) {
217
+ return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
218
+ }
219
+ async function scanCss(patterns, exclude, selectors) {
220
+ const normalized = normalizePatterns(patterns);
221
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
167
222
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
168
- const all = /* @__PURE__ */ new Set();
169
- await Promise.all(
223
+ const perFile = await Promise.all(
170
224
  files.map(async (file) => {
171
225
  let css;
172
226
  try {
173
227
  css = await (0, import_promises.readFile)(file, "utf8");
174
228
  } catch (err) {
175
229
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
176
- return;
230
+ return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
177
231
  }
178
- for (const name of parseVarNames(css, selectors)) {
179
- all.add(name);
232
+ return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
233
+ })
234
+ );
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;
180
265
  }
266
+ extractUsedKeys(text, used);
267
+ return used;
181
268
  })
182
269
  );
183
- return [...all].sort();
270
+ const all = /* @__PURE__ */ new Set();
271
+ for (const used of perFile) {
272
+ for (const key of used) all.add(key);
273
+ }
274
+ return all;
184
275
  }
185
276
 
186
277
  // src/generator.ts
187
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
278
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
188
279
  function convertCase(value, naming) {
189
280
  if (!VALID_NAMINGS.includes(naming)) {
190
281
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
191
282
  }
192
283
  if (naming === "kebab") return value;
193
- return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
284
+ if (naming === "snake") return value.replace(/-+/g, "_");
285
+ if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
286
+ if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
287
+ return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
194
288
  }
195
- function toKey(cssVarName, naming = "camelCase") {
196
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
289
+ function toKeyFragment(fragment, naming = "camelCase") {
290
+ const key = convertCase(fragment, naming);
197
291
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
198
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
+ }
199
302
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
200
303
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
201
304
  var SINGLE_QUOTE_ESCAPES = {};
@@ -221,13 +324,16 @@ function applyPrefix(key, prefix, naming = "camelCase") {
221
324
  }
222
325
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
223
326
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
224
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
327
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
225
328
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
226
329
  }
227
330
  function formatKey(key, naming = "camelCase") {
228
331
  if (naming === "kebab") return `'${key}'`;
229
332
  return key;
230
333
  }
334
+ function computeKey(cssVarName, prefix, naming) {
335
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
336
+ }
231
337
  function findKeyCollisions(varNames, prefix, naming) {
232
338
  const byKey = /* @__PURE__ */ new Map();
233
339
  for (const name of varNames) {
@@ -246,28 +352,126 @@ function warnOnCollisions(varNames, prefix, naming) {
246
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.`);
247
353
  }
248
354
  }
249
- function buildEntries(varNames, prefix, naming) {
355
+ function buildEntries(varNames, prefix, naming, declarations, properties) {
250
356
  const byKey = /* @__PURE__ */ new Map();
251
357
  for (const name of varNames) {
252
358
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
253
- byKey.set(key, name);
359
+ byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
360
+ }
361
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
362
+ }
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;
400
+ }
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);
254
420
  }
255
- return [...byKey].map(([key, name]) => ({ key, name }));
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(" | ")};`);
256
425
  }
257
- function generateCode(varNames, prefix, naming) {
258
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
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)}`
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]);
259
463
  return [
260
464
  "// generated \u2014 do not edit",
261
465
  "export const cssVars = {",
262
466
  ...entries,
263
467
  "} as const;",
264
- "",
265
- "export type CssVarName = keyof typeof cssVars;",
468
+ ...tailBody.length > 0 ? ["", ...tailBody] : [],
266
469
  ""
267
470
  ].join("\n");
268
471
  }
269
- function generateJs(varNames, prefix, naming) {
270
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
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);
271
475
  return [
272
476
  "// generated \u2014 do not edit",
273
477
  "export const cssVars = {",
@@ -276,34 +480,86 @@ function generateJs(varNames, prefix, naming) {
276
480
  ""
277
481
  ].join("\n");
278
482
  }
279
- function generateDeclaration(varNames, prefix, naming) {
280
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
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]);
281
488
  return [
282
489
  "export declare const cssVars: {",
283
490
  ...entries,
284
491
  "};",
285
- "export type CssVarName = keyof typeof cssVars;",
492
+ ...tailBody,
286
493
  ""
287
494
  ].join("\n");
288
495
  }
289
496
 
290
497
  // src/index.ts
291
- async function generate(options) {
292
- const names = await scanVarNames(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
+ ]);
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();
293
524
  if (names.length === 0) {
294
525
  console.warn("css-typed-vars: no CSS custom properties found.");
295
526
  }
296
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
+ }
297
536
  const outPath = (0, import_node_path.resolve)(options.output);
298
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
299
537
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
300
538
  if (jsExtMatch) {
301
- await (0, import_promises2.writeFile)(outPath, generateJs(names, options.prefix, options.naming), "utf8");
539
+ const content = generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
302
540
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
303
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
304
- } else {
305
- await (0, import_promises2.writeFile)(outPath, generateCode(names, options.prefix, options.naming), "utf8");
541
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
542
+ return { outPath, content, dtsPath, dtsContent };
543
+ }
544
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations, options.group, properties) };
545
+ }
546
+ async function generate(options) {
547
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
548
+ await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
549
+ await (0, import_promises2.writeFile)(outPath, content, "utf8");
550
+ if (dtsPath && dtsContent !== void 0) {
551
+ await (0, import_promises2.writeFile)(dtsPath, dtsContent, "utf8");
552
+ }
553
+ }
554
+ async function checkGenerated(options) {
555
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
556
+ const current = await (0, import_promises2.readFile)(outPath, "utf8").catch(() => null);
557
+ if (current !== content) return false;
558
+ if (dtsPath && dtsContent !== void 0) {
559
+ const currentDts = await (0, import_promises2.readFile)(dtsPath, "utf8").catch(() => null);
560
+ if (currentDts !== dtsContent) return false;
306
561
  }
562
+ return true;
307
563
  }
308
564
 
309
565
  // src/cli.ts
@@ -323,6 +579,10 @@ var getArgs = (flag) => {
323
579
  return result;
324
580
  };
325
581
  var watchMode = args.includes("--watch");
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");
326
586
  async function loadConfig() {
327
587
  const candidates = [
328
588
  "css-typed-vars.config.js",
@@ -347,9 +607,9 @@ async function loadConfig() {
347
607
  }
348
608
  return {};
349
609
  }
350
- async function run(input, output, exclude, prefix, naming, selectors) {
351
- await generate({ input, output, exclude, prefix, naming, selectors });
352
- console.log(`Generated \u2192 ${output}`);
610
+ async function run(options) {
611
+ await generate(options);
612
+ console.log(`Generated \u2192 ${options.output}`);
353
613
  }
354
614
  async function main() {
355
615
  if (args.includes("--version") || args.includes("-v")) {
@@ -372,17 +632,62 @@ async function main() {
372
632
  const naming = namingRaw;
373
633
  const selectorArgs = getArgs("--selector");
374
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;
375
641
  if (!input || !output) {
376
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch]");
642
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--prune --usage <glob>] [--prune-check --usage <glob>]");
377
643
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
378
644
  process.exit(1);
379
645
  }
380
- await run(input, output, exclude, prefix, naming, selectors);
646
+ if (checkMode && watchMode) {
647
+ console.error("css-typed-vars: --check cannot be combined with --watch.");
648
+ process.exit(1);
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 };
676
+ if (checkMode) {
677
+ const upToDate = await checkGenerated(runOptions);
678
+ if (!upToDate) {
679
+ console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
680
+ process.exit(1);
681
+ }
682
+ console.log(`css-typed-vars: "${output}" is up to date.`);
683
+ return;
684
+ }
685
+ await run(runOptions);
381
686
  if (watchMode) {
382
687
  const patterns = Array.isArray(input) ? input : [input];
383
688
  const makeHandler = (label) => (file) => {
384
689
  console.log(`${label}: ${file}`);
385
- run(input, output, exclude, prefix, naming, selectors).catch(console.error);
690
+ run(runOptions).catch(console.error);
386
691
  };
387
692
  const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
388
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,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ checkGenerated,
4
+ findUnusedVars,
3
5
  generate
4
- } from "./chunk-EHRNYU34.js";
6
+ } from "./chunk-VZ2BHHXD.js";
5
7
  import {
6
8
  VALID_NAMINGS
7
- } from "./chunk-WYLYZXQJ.js";
9
+ } from "./chunk-LH53WYFF.js";
8
10
 
9
11
  // src/cli.ts
10
12
  import { readFile } from "fs/promises";
@@ -27,6 +29,10 @@ var getArgs = (flag) => {
27
29
  return result;
28
30
  };
29
31
  var watchMode = args.includes("--watch");
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");
30
36
  async function loadConfig() {
31
37
  const candidates = [
32
38
  "css-typed-vars.config.js",
@@ -51,9 +57,9 @@ async function loadConfig() {
51
57
  }
52
58
  return {};
53
59
  }
54
- async function run(input, output, exclude, prefix, naming, selectors) {
55
- await generate({ input, output, exclude, prefix, naming, selectors });
56
- console.log(`Generated \u2192 ${output}`);
60
+ async function run(options) {
61
+ await generate(options);
62
+ console.log(`Generated \u2192 ${options.output}`);
57
63
  }
58
64
  async function main() {
59
65
  if (args.includes("--version") || args.includes("-v")) {
@@ -76,17 +82,62 @@ async function main() {
76
82
  const naming = namingRaw;
77
83
  const selectorArgs = getArgs("--selector");
78
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;
79
91
  if (!input || !output) {
80
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch]");
92
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--prune --usage <glob>] [--prune-check --usage <glob>]");
81
93
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
82
94
  process.exit(1);
83
95
  }
84
- await run(input, output, exclude, prefix, naming, selectors);
96
+ if (checkMode && watchMode) {
97
+ console.error("css-typed-vars: --check cannot be combined with --watch.");
98
+ process.exit(1);
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 };
126
+ if (checkMode) {
127
+ const upToDate = await checkGenerated(runOptions);
128
+ if (!upToDate) {
129
+ console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
130
+ process.exit(1);
131
+ }
132
+ console.log(`css-typed-vars: "${output}" is up to date.`);
133
+ return;
134
+ }
135
+ await run(runOptions);
85
136
  if (watchMode) {
86
137
  const patterns = Array.isArray(input) ? input : [input];
87
138
  const makeHandler = (label) => (file) => {
88
139
  console.log(`${label}: ${file}`);
89
- run(input, output, exclude, prefix, naming, selectors).catch(console.error);
140
+ run(runOptions).catch(console.error);
90
141
  };
91
142
  const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
92
143
  watch(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));