css-typed-vars 0.10.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -33,26 +33,11 @@ var import_node_path4 = require("path");
33
33
  var import_node_url = require("url");
34
34
  var import_chokidar = require("chokidar");
35
35
 
36
- // src/index.ts
37
- var import_promises3 = require("fs/promises");
38
- var import_node_path3 = require("path");
39
-
40
- // src/write.ts
36
+ // src/scanner.ts
41
37
  var import_promises = require("fs/promises");
42
38
  var import_node_path = require("path");
43
- async function writeOutput(path, content) {
44
- const current = await (0, import_promises.readFile)(path, "utf8").catch(() => null);
45
- if (current === content) return false;
46
- await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
47
- await (0, import_promises.writeFile)(path, content, "utf8");
48
- return true;
49
- }
50
-
51
- // src/scanner.ts
52
- var import_promises2 = require("fs/promises");
53
- var import_node_path2 = require("path");
54
- var import_fast_glob = __toESM(require("fast-glob"), 1);
55
39
  var import_picomatch = __toESM(require("picomatch"), 1);
40
+ var import_tinyglobby = require("tinyglobby");
56
41
 
57
42
  // src/parser.ts
58
43
  function stepQuote(text, i, quote) {
@@ -343,6 +328,29 @@ function parseVarReferences(css) {
343
328
  }
344
329
  return refs;
345
330
  }
331
+ var SOURCE_REF_RE = /\bvar\(\s*(--[\w-]+)\s*(,)?|(?<=[\w-]-)\((?:[\w-]+:)?(--[\w-]+)\)/g;
332
+ function parseSourceVarReferences(text) {
333
+ const lineStarts = [0];
334
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") lineStarts.push(i + 1);
335
+ const refs = [];
336
+ for (const match of text.matchAll(SOURCE_REF_RE)) {
337
+ let line = lineStarts.length - 1;
338
+ while (lineStarts[line] > match.index) line--;
339
+ refs.push({
340
+ name: match[1] ?? match[3],
341
+ hasFallback: match[2] === ",",
342
+ line: line + 1,
343
+ column: match.index - lineStarts[line] + 1
344
+ });
345
+ }
346
+ return refs;
347
+ }
348
+ function parseSourceDeclaredNames(text) {
349
+ const names = /* @__PURE__ */ new Set();
350
+ for (const match of text.matchAll(/(?<![\w-])(--[\w-]+)['"`]?\s*:/g)) names.add(match[1]);
351
+ for (const match of text.matchAll(/\bsetProperty\(\s*['"`](--[\w-]+)['"`]/g)) names.add(match[1]);
352
+ return names;
353
+ }
346
354
  function parseDeclaredNames(css) {
347
355
  const masked = maskQuotedContent(stripComments(css));
348
356
  const names = /* @__PURE__ */ new Set();
@@ -355,6 +363,62 @@ function parseDeclaredNames(css) {
355
363
  function normalizePatterns(patterns) {
356
364
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
357
365
  }
366
+ function comparePaths(a, b) {
367
+ const as = a.split("/");
368
+ const bs = b.split("/");
369
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
370
+ if (as[i] === bs[i]) continue;
371
+ const aIsFile = i === as.length - 1;
372
+ const bIsFile = i === bs.length - 1;
373
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
374
+ return as[i] < bs[i] ? -1 : 1;
375
+ }
376
+ return as.length - bs.length;
377
+ }
378
+ async function globFiles(pattern, ignore) {
379
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
380
+ return (0, import_tinyglobby.glob)(pattern, { absolute: true, ignore, expandDirectories: false });
381
+ }
382
+ const { base, glob: rest, isGlob } = import_picomatch.default.scan(pattern);
383
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [import_node_path.posix.dirname(pattern), import_node_path.posix.basename(pattern)];
384
+ const matches = await (0, import_tinyglobby.glob)(relativeGlob, { cwd, absolute: true, expandDirectories: false });
385
+ if (ignore.length === 0) return matches;
386
+ const isIgnored = (0, import_picomatch.default)(ignore, { dot: true });
387
+ return matches.filter((file) => !isIgnored(file));
388
+ }
389
+ async function findFiles(patterns, exclude) {
390
+ const normalized = normalizePatterns(patterns);
391
+ const ignore = [
392
+ ...exclude ? normalizePatterns(exclude) : [],
393
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
394
+ ];
395
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
396
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
397
+ return [...new Set(files.reverse())].reverse();
398
+ }
399
+ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
400
+ const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
401
+ const include = compile(patterns);
402
+ const ignore = exclude ? compile(exclude) : () => false;
403
+ return (file) => {
404
+ const absolute = (0, import_node_path.resolve)(cwd, file).replace(/\\/g, "/");
405
+ const fromCwd = (0, import_node_path.relative)(cwd, absolute).replace(/\\/g, "/");
406
+ const matches = (test) => test(fromCwd) || test(absolute);
407
+ return matches(include) && !matches(ignore);
408
+ };
409
+ }
410
+ function globWatchRoots(patterns, cwd = process.cwd()) {
411
+ const roots = /* @__PURE__ */ new Map();
412
+ for (const pattern of normalizePatterns(patterns)) {
413
+ const { base, glob: glob2, isGlob } = import_picomatch.default.scan(pattern);
414
+ const dir = (0, import_node_path.resolve)(cwd, isGlob ? base || "." : (0, import_node_path.dirname)(pattern));
415
+ const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob2) ? void 0 : glob2.split("/").length - 1;
416
+ const previous = roots.get(dir);
417
+ const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
418
+ roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
419
+ }
420
+ return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
421
+ }
358
422
  function collectVarNames(scanned) {
359
423
  const names = new Set(scanned.declarations.keys());
360
424
  for (const values of scanned.themes.values()) {
@@ -363,14 +427,12 @@ function collectVarNames(scanned) {
363
427
  return [...names].sort();
364
428
  }
365
429
  async function scanCss(patterns, exclude, selectors, themes = {}) {
366
- const normalized = normalizePatterns(patterns);
367
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
368
- const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
430
+ const files = await findFiles(patterns, exclude);
369
431
  const perFile = await Promise.all(
370
432
  files.map(async (file) => {
371
433
  let css;
372
434
  try {
373
- css = await (0, import_promises2.readFile)(file, "utf8");
435
+ css = await (0, import_promises.readFile)(file, "utf8");
374
436
  } catch (err) {
375
437
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
376
438
  return null;
@@ -391,7 +453,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
391
453
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
392
454
  }
393
455
  }
394
- return { declarations, properties, themes: themeValues, docs };
456
+ return { declarations, properties, themes: themeValues, docs, files };
395
457
  }
396
458
  var ROOT_RE = /\bcssVars\b/g;
397
459
  var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
@@ -422,14 +484,12 @@ function extractUsage(text, into) {
422
484
  }
423
485
  }
424
486
  async function scanUsage(patterns, exclude) {
425
- const normalized = normalizePatterns(patterns);
426
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
427
- const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
428
- const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
487
+ const files = await findFiles(patterns, exclude);
488
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
429
489
  const texts = await Promise.all(
430
490
  files.map(async (file) => {
431
491
  try {
432
- return await (0, import_promises2.readFile)(file, "utf8");
492
+ return await (0, import_promises.readFile)(file, "utf8");
433
493
  } catch (err) {
434
494
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
435
495
  return "";
@@ -439,14 +499,14 @@ async function scanUsage(patterns, exclude) {
439
499
  for (const text of texts) extractUsage(text, usage);
440
500
  return usage;
441
501
  }
442
- async function scanReferences(patterns, exclude) {
443
- const normalized = normalizePatterns(patterns);
444
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
445
- const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
502
+ async function scanReferences(patterns, exclude, source = false) {
503
+ const parseReferences = source ? parseSourceVarReferences : parseVarReferences;
504
+ const parseDeclared = source ? parseSourceDeclaredNames : parseDeclaredNames;
505
+ const files = (await findFiles(patterns, exclude)).sort();
446
506
  const perFile = await Promise.all(
447
507
  files.map(async (file) => {
448
508
  try {
449
- return { file, css: await (0, import_promises2.readFile)(file, "utf8") };
509
+ return { file, css: await (0, import_promises.readFile)(file, "utf8") };
450
510
  } catch (err) {
451
511
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
452
512
  return null;
@@ -457,12 +517,27 @@ async function scanReferences(patterns, exclude) {
457
517
  const declared = /* @__PURE__ */ new Set();
458
518
  for (const result of perFile) {
459
519
  if (!result) continue;
460
- for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
461
- for (const name of parseDeclaredNames(result.css)) declared.add(name);
520
+ for (const ref of parseReferences(result.css)) references.push({ ...ref, file: result.file });
521
+ for (const name of parseDeclared(result.css)) declared.add(name);
462
522
  }
463
523
  return { references, declared };
464
524
  }
465
525
 
526
+ // src/index.ts
527
+ var import_promises3 = require("fs/promises");
528
+ var import_node_path3 = require("path");
529
+
530
+ // src/write.ts
531
+ var import_promises2 = require("fs/promises");
532
+ var import_node_path2 = require("path");
533
+ async function writeOutput(path, content) {
534
+ const current = await (0, import_promises2.readFile)(path, "utf8").catch(() => null);
535
+ if (current === content) return false;
536
+ await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(path), { recursive: true });
537
+ await (0, import_promises2.writeFile)(path, content, "utf8");
538
+ return true;
539
+ }
540
+
466
541
  // src/generator.ts
467
542
  var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
468
543
  function convertCase(value, naming) {
@@ -846,9 +921,13 @@ function matchesIgnore(name, patterns) {
846
921
  return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
847
922
  }
848
923
  async function findUndefinedRefs(options) {
849
- const { references, declared } = await scanReferences(options.input, options.exclude);
924
+ const [css, source] = await Promise.all([
925
+ scanReferences(options.input, options.exclude),
926
+ options.refsSource ? scanReferences(options.refsSource, void 0, true) : null
927
+ ]);
928
+ const declared = /* @__PURE__ */ new Set([...css.declared, ...source?.declared ?? []]);
850
929
  const ignore = options.refsIgnore ?? [];
851
- return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
930
+ return [...css.references, ...source?.references ?? []].filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
852
931
  }
853
932
  async function computeOutputs(options) {
854
933
  assertPruneCompatible(options);
@@ -909,6 +988,24 @@ async function checkGenerated(options) {
909
988
  return true;
910
989
  }
911
990
 
991
+ // src/config.ts
992
+ var CONFIG_KEYS = [
993
+ "input",
994
+ "output",
995
+ "exclude",
996
+ "prefix",
997
+ "naming",
998
+ "selectors",
999
+ "themes",
1000
+ "group",
1001
+ "prune",
1002
+ "usage",
1003
+ "usageExclude",
1004
+ "helpers",
1005
+ "refsIgnore",
1006
+ "refsSource"
1007
+ ];
1008
+
912
1009
  // src/cli.ts
913
1010
  var args = process.argv.slice(2).flatMap((arg) => {
914
1011
  const match = /^(--[\w-]+)=(.*)$/.exec(arg);
@@ -942,7 +1039,8 @@ var OPTION_FLAGS = [
942
1039
  "--usage",
943
1040
  "--usage-exclude",
944
1041
  "--helpers",
945
- "--refs-ignore"
1042
+ "--refs-ignore",
1043
+ "--refs-source"
946
1044
  ];
947
1045
  var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
948
1046
  var VALUE_FLAGS = [
@@ -956,6 +1054,7 @@ var VALUE_FLAGS = [
956
1054
  "--usage",
957
1055
  "--usage-exclude",
958
1056
  "--refs-ignore",
1057
+ "--refs-source",
959
1058
  "--config"
960
1059
  ];
961
1060
  var BOOLEAN_FLAGS = [
@@ -997,6 +1096,7 @@ Modes:
997
1096
  --prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
998
1097
  --lint-refs Exit 1 on var() references to undeclared variables
999
1098
  --refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
1099
+ --refs-source <glob> Source files whose var() references --lint-refs checks too (repeatable)
1000
1100
  --version, -v Print the version
1001
1101
  --help, -h Print this help
1002
1102
 
@@ -1012,6 +1112,10 @@ function editDistance(a, b) {
1012
1112
  }
1013
1113
  return row[b.length];
1014
1114
  }
1115
+ function suggest(value, candidates) {
1116
+ const closest = candidates.reduce((best, candidate) => editDistance(value, candidate) < editDistance(value, best) ? candidate : best);
1117
+ return editDistance(value, closest) <= 2 ? ` Did you mean ${closest}?` : "";
1118
+ }
1015
1119
  function validateArgs() {
1016
1120
  for (let i = 0; i < args.length; i++) {
1017
1121
  const arg = args[i];
@@ -1023,9 +1127,7 @@ function validateArgs() {
1023
1127
  if (BOOLEAN_FLAGS.includes(arg)) continue;
1024
1128
  if (arg.startsWith("-")) {
1025
1129
  const known = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].filter((flag) => flag.startsWith("--"));
1026
- const closest = known.reduce((best, flag) => editDistance(arg, flag) < editDistance(arg, best) ? flag : best);
1027
- const hint = editDistance(arg, closest) <= 2 ? ` Did you mean ${closest}?` : "";
1028
- throw new CliError(`css-typed-vars: unknown option "${arg}".${hint} Run with --help to see all options.`);
1130
+ throw new CliError(`css-typed-vars: unknown option "${arg}".${suggest(arg, known)} Run with --help to see all options.`);
1029
1131
  }
1030
1132
  throw new CliError(`css-typed-vars: unexpected argument "${arg}". If it's a glob, quote it so the shell doesn't expand it: --input "src/**/*.css".`);
1031
1133
  }
@@ -1068,6 +1170,13 @@ async function loadConfig() {
1068
1170
  return {};
1069
1171
  }
1070
1172
  var exists = (path) => (0, import_promises4.access)(path).then(() => true, () => false);
1173
+ function warnUnknownKeys(config, tag) {
1174
+ if (typeof config !== "object" || config === null) return;
1175
+ for (const key of Object.keys(config)) {
1176
+ if (key === "$schema" || CONFIG_KEYS.includes(key)) continue;
1177
+ console.warn(`${tag}: unknown option "${key}" in the config file.${suggest(key, CONFIG_KEYS)}`);
1178
+ }
1179
+ }
1071
1180
  function applyFlags(config) {
1072
1181
  const inputArgs = getArgs("--input");
1073
1182
  const excludeArgs = getArgs("--exclude");
@@ -1081,6 +1190,7 @@ function applyFlags(config) {
1081
1190
  const usageArgs = getArgs("--usage");
1082
1191
  const usageExcludeArgs = getArgs("--usage-exclude");
1083
1192
  const refsIgnoreArgs = getArgs("--refs-ignore");
1193
+ const refsSourceArgs = getArgs("--refs-source");
1084
1194
  return {
1085
1195
  ...config,
1086
1196
  input: inputArgs.length > 0 ? inputArgs : config.input,
@@ -1095,17 +1205,23 @@ function applyFlags(config) {
1095
1205
  usage: usageArgs.length > 0 ? usageArgs : config.usage,
1096
1206
  usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
1097
1207
  helpers: args.includes("--helpers") || config.helpers,
1098
- refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
1208
+ refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore,
1209
+ refsSource: refsSourceArgs.length > 0 ? refsSourceArgs : config.refsSource
1099
1210
  };
1100
1211
  }
1101
1212
  function loadTargets(config) {
1102
- if (!Array.isArray(config)) return [{ options: applyFlags(config), tag: "css-typed-vars" }];
1213
+ if (!Array.isArray(config)) {
1214
+ warnUnknownKeys(config, "css-typed-vars");
1215
+ return [{ options: applyFlags(config), tag: "css-typed-vars" }];
1216
+ }
1103
1217
  if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
1104
1218
  const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
1105
1219
  if (used.length > 0) {
1106
1220
  throw new CliError(`css-typed-vars: ${used.join(", ")} can't be used with an array config \u2014 set options per target in the config file instead.`);
1107
1221
  }
1108
- return config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
1222
+ const targets = config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
1223
+ for (const { options, tag } of targets) warnUnknownKeys(options, tag);
1224
+ return targets;
1109
1225
  }
1110
1226
  function validateModes() {
1111
1227
  if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
@@ -1137,8 +1253,15 @@ Or add a css-typed-vars.config.js file with input and output fields. Run with --
1137
1253
  throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
1138
1254
  }
1139
1255
  }
1256
+ function outputPaths(output) {
1257
+ if (!output) return /* @__PURE__ */ new Set();
1258
+ const jsExt = /\.(m|c)?js$/i.exec(output);
1259
+ return new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => (0, import_node_path4.resolve)(path)));
1260
+ }
1140
1261
  async function lintRefs({ options, tag }) {
1141
- const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
1262
+ const { input, exclude, refsIgnore, refsSource } = options;
1263
+ const outputs = outputPaths(options.output);
1264
+ const refs = (await findUndefinedRefs({ input, exclude, refsIgnore, refsSource })).filter((ref) => !outputs.has((0, import_node_path4.resolve)(ref.file)));
1142
1265
  const format = (ref) => ` ${(0, import_node_path4.relative)(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
1143
1266
  const errors = refs.filter((ref) => !ref.hasFallback);
1144
1267
  const warnings = refs.filter((ref) => ref.hasFallback);
@@ -1178,8 +1301,7 @@ async function run({ options }) {
1178
1301
  var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
1179
1302
  function watchTarget(target) {
1180
1303
  const { input, exclude, output, prune, usage, usageExclude } = target.options;
1181
- const jsExt = /\.(m|c)?js$/i.exec(output);
1182
- const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => (0, import_node_path4.resolve)(path)));
1304
+ const outputs = outputPaths(output);
1183
1305
  let timer = null;
1184
1306
  let running = false;
1185
1307
  let pending = false;
@@ -1196,20 +1318,27 @@ function watchTarget(target) {
1196
1318
  await regenerate();
1197
1319
  }
1198
1320
  };
1321
+ const isInput = createFileMatcher(input, exclude);
1322
+ const isUsage = prune ? createFileMatcher(usage, usageExclude) : () => false;
1323
+ const isWatched = (file) => !outputs.has((0, import_node_path4.resolve)(file)) && (isInput(file) || isUsage(file));
1199
1324
  const makeHandler = (label) => (file) => {
1200
- if (outputs.has((0, import_node_path4.resolve)(file))) return;
1201
- console.log(`${label}: ${file}`);
1325
+ if (!isWatched(file)) return;
1326
+ console.log(`${label}: ${(0, import_node_path4.relative)(process.cwd(), file).replace(/\\/g, "/")}`);
1202
1327
  if (timer) clearTimeout(timer);
1203
1328
  timer = setTimeout(() => {
1204
1329
  timer = null;
1205
1330
  void regenerate();
1206
1331
  }, 100);
1207
1332
  };
1208
- const subscribe = (patterns, ignored) => {
1209
- (0, import_chokidar.watch)(patterns, { ignoreInitial: true, ...ignored.length > 0 ? { ignored } : {} }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
1210
- };
1211
- subscribe(toArray(input), toArray(exclude));
1212
- if (prune) subscribe(toArray(usage), toArray(usageExclude));
1333
+ const roots = globWatchRoots([...toArray(input), ...prune ? toArray(usage) : []]);
1334
+ for (const { dir, depth } of roots) {
1335
+ (0, import_chokidar.watch)(dir, {
1336
+ ignoreInitial: true,
1337
+ depth,
1338
+ // No need to watch a file that can't match; directories are still traversed.
1339
+ ignored: (path, stats) => stats?.isFile() === true && !isWatched(path)
1340
+ }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
1341
+ }
1213
1342
  }
1214
1343
  async function main() {
1215
1344
  validateArgs();
package/dist/cli.js CHANGED
@@ -4,16 +4,38 @@ import {
4
4
  findUndefinedRefs,
5
5
  findUnusedVars,
6
6
  generate
7
- } from "./chunk-O7MEOCHS.js";
7
+ } from "./chunk-ULIGESN5.js";
8
8
  import {
9
- VALID_NAMINGS
10
- } from "./chunk-XCAFJREQ.js";
9
+ VALID_NAMINGS,
10
+ createFileMatcher,
11
+ globWatchRoots
12
+ } from "./chunk-RZLASYCF.js";
11
13
 
12
14
  // src/cli.ts
13
15
  import { access, readFile } from "fs/promises";
14
16
  import { relative, resolve } from "path";
15
17
  import { pathToFileURL } from "url";
16
18
  import { watch } from "chokidar";
19
+
20
+ // src/config.ts
21
+ var CONFIG_KEYS = [
22
+ "input",
23
+ "output",
24
+ "exclude",
25
+ "prefix",
26
+ "naming",
27
+ "selectors",
28
+ "themes",
29
+ "group",
30
+ "prune",
31
+ "usage",
32
+ "usageExclude",
33
+ "helpers",
34
+ "refsIgnore",
35
+ "refsSource"
36
+ ];
37
+
38
+ // src/cli.ts
17
39
  var args = process.argv.slice(2).flatMap((arg) => {
18
40
  const match = /^(--[\w-]+)=(.*)$/.exec(arg);
19
41
  return match ? [match[1], match[2]] : [arg];
@@ -46,7 +68,8 @@ var OPTION_FLAGS = [
46
68
  "--usage",
47
69
  "--usage-exclude",
48
70
  "--helpers",
49
- "--refs-ignore"
71
+ "--refs-ignore",
72
+ "--refs-source"
50
73
  ];
51
74
  var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
52
75
  var VALUE_FLAGS = [
@@ -60,6 +83,7 @@ var VALUE_FLAGS = [
60
83
  "--usage",
61
84
  "--usage-exclude",
62
85
  "--refs-ignore",
86
+ "--refs-source",
63
87
  "--config"
64
88
  ];
65
89
  var BOOLEAN_FLAGS = [
@@ -101,6 +125,7 @@ Modes:
101
125
  --prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
102
126
  --lint-refs Exit 1 on var() references to undeclared variables
103
127
  --refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
128
+ --refs-source <glob> Source files whose var() references --lint-refs checks too (repeatable)
104
129
  --version, -v Print the version
105
130
  --help, -h Print this help
106
131
 
@@ -116,6 +141,10 @@ function editDistance(a, b) {
116
141
  }
117
142
  return row[b.length];
118
143
  }
144
+ function suggest(value, candidates) {
145
+ const closest = candidates.reduce((best, candidate) => editDistance(value, candidate) < editDistance(value, best) ? candidate : best);
146
+ return editDistance(value, closest) <= 2 ? ` Did you mean ${closest}?` : "";
147
+ }
119
148
  function validateArgs() {
120
149
  for (let i = 0; i < args.length; i++) {
121
150
  const arg = args[i];
@@ -127,9 +156,7 @@ function validateArgs() {
127
156
  if (BOOLEAN_FLAGS.includes(arg)) continue;
128
157
  if (arg.startsWith("-")) {
129
158
  const known = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].filter((flag) => flag.startsWith("--"));
130
- const closest = known.reduce((best, flag) => editDistance(arg, flag) < editDistance(arg, best) ? flag : best);
131
- const hint = editDistance(arg, closest) <= 2 ? ` Did you mean ${closest}?` : "";
132
- throw new CliError(`css-typed-vars: unknown option "${arg}".${hint} Run with --help to see all options.`);
159
+ throw new CliError(`css-typed-vars: unknown option "${arg}".${suggest(arg, known)} Run with --help to see all options.`);
133
160
  }
134
161
  throw new CliError(`css-typed-vars: unexpected argument "${arg}". If it's a glob, quote it so the shell doesn't expand it: --input "src/**/*.css".`);
135
162
  }
@@ -172,6 +199,13 @@ async function loadConfig() {
172
199
  return {};
173
200
  }
174
201
  var exists = (path) => access(path).then(() => true, () => false);
202
+ function warnUnknownKeys(config, tag) {
203
+ if (typeof config !== "object" || config === null) return;
204
+ for (const key of Object.keys(config)) {
205
+ if (key === "$schema" || CONFIG_KEYS.includes(key)) continue;
206
+ console.warn(`${tag}: unknown option "${key}" in the config file.${suggest(key, CONFIG_KEYS)}`);
207
+ }
208
+ }
175
209
  function applyFlags(config) {
176
210
  const inputArgs = getArgs("--input");
177
211
  const excludeArgs = getArgs("--exclude");
@@ -185,6 +219,7 @@ function applyFlags(config) {
185
219
  const usageArgs = getArgs("--usage");
186
220
  const usageExcludeArgs = getArgs("--usage-exclude");
187
221
  const refsIgnoreArgs = getArgs("--refs-ignore");
222
+ const refsSourceArgs = getArgs("--refs-source");
188
223
  return {
189
224
  ...config,
190
225
  input: inputArgs.length > 0 ? inputArgs : config.input,
@@ -199,17 +234,23 @@ function applyFlags(config) {
199
234
  usage: usageArgs.length > 0 ? usageArgs : config.usage,
200
235
  usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
201
236
  helpers: args.includes("--helpers") || config.helpers,
202
- refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
237
+ refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore,
238
+ refsSource: refsSourceArgs.length > 0 ? refsSourceArgs : config.refsSource
203
239
  };
204
240
  }
205
241
  function loadTargets(config) {
206
- if (!Array.isArray(config)) return [{ options: applyFlags(config), tag: "css-typed-vars" }];
242
+ if (!Array.isArray(config)) {
243
+ warnUnknownKeys(config, "css-typed-vars");
244
+ return [{ options: applyFlags(config), tag: "css-typed-vars" }];
245
+ }
207
246
  if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
208
247
  const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
209
248
  if (used.length > 0) {
210
249
  throw new CliError(`css-typed-vars: ${used.join(", ")} can't be used with an array config \u2014 set options per target in the config file instead.`);
211
250
  }
212
- return config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
251
+ const targets = config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
252
+ for (const { options, tag } of targets) warnUnknownKeys(options, tag);
253
+ return targets;
213
254
  }
214
255
  function validateModes() {
215
256
  if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
@@ -241,8 +282,15 @@ Or add a css-typed-vars.config.js file with input and output fields. Run with --
241
282
  throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
242
283
  }
243
284
  }
285
+ function outputPaths(output) {
286
+ if (!output) return /* @__PURE__ */ new Set();
287
+ const jsExt = /\.(m|c)?js$/i.exec(output);
288
+ return new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => resolve(path)));
289
+ }
244
290
  async function lintRefs({ options, tag }) {
245
- const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
291
+ const { input, exclude, refsIgnore, refsSource } = options;
292
+ const outputs = outputPaths(options.output);
293
+ const refs = (await findUndefinedRefs({ input, exclude, refsIgnore, refsSource })).filter((ref) => !outputs.has(resolve(ref.file)));
246
294
  const format = (ref) => ` ${relative(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
247
295
  const errors = refs.filter((ref) => !ref.hasFallback);
248
296
  const warnings = refs.filter((ref) => ref.hasFallback);
@@ -282,8 +330,7 @@ async function run({ options }) {
282
330
  var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
283
331
  function watchTarget(target) {
284
332
  const { input, exclude, output, prune, usage, usageExclude } = target.options;
285
- const jsExt = /\.(m|c)?js$/i.exec(output);
286
- const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => resolve(path)));
333
+ const outputs = outputPaths(output);
287
334
  let timer = null;
288
335
  let running = false;
289
336
  let pending = false;
@@ -300,20 +347,27 @@ function watchTarget(target) {
300
347
  await regenerate();
301
348
  }
302
349
  };
350
+ const isInput = createFileMatcher(input, exclude);
351
+ const isUsage = prune ? createFileMatcher(usage, usageExclude) : () => false;
352
+ const isWatched = (file) => !outputs.has(resolve(file)) && (isInput(file) || isUsage(file));
303
353
  const makeHandler = (label) => (file) => {
304
- if (outputs.has(resolve(file))) return;
305
- console.log(`${label}: ${file}`);
354
+ if (!isWatched(file)) return;
355
+ console.log(`${label}: ${relative(process.cwd(), file).replace(/\\/g, "/")}`);
306
356
  if (timer) clearTimeout(timer);
307
357
  timer = setTimeout(() => {
308
358
  timer = null;
309
359
  void regenerate();
310
360
  }, 100);
311
361
  };
312
- const subscribe = (patterns, ignored) => {
313
- watch(patterns, { ignoreInitial: true, ...ignored.length > 0 ? { ignored } : {} }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
314
- };
315
- subscribe(toArray(input), toArray(exclude));
316
- if (prune) subscribe(toArray(usage), toArray(usageExclude));
362
+ const roots = globWatchRoots([...toArray(input), ...prune ? toArray(usage) : []]);
363
+ for (const { dir, depth } of roots) {
364
+ watch(dir, {
365
+ ignoreInitial: true,
366
+ depth,
367
+ // No need to watch a file that can't match; directories are still traversed.
368
+ ignored: (path, stats) => stats?.isFile() === true && !isWatched(path)
369
+ }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
370
+ }
317
371
  }
318
372
  async function main() {
319
373
  validateArgs();