css-typed-vars 0.8.0 → 0.10.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
@@ -28,18 +28,31 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
28
28
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
29
 
30
30
  // src/cli.ts
31
- var import_promises3 = require("fs/promises");
32
- var import_node_path2 = require("path");
31
+ var import_promises4 = require("fs/promises");
32
+ var import_node_path4 = require("path");
33
33
  var import_node_url = require("url");
34
34
  var import_chokidar = require("chokidar");
35
35
 
36
36
  // src/index.ts
37
- var import_promises2 = require("fs/promises");
37
+ var import_promises3 = require("fs/promises");
38
+ var import_node_path3 = require("path");
39
+
40
+ // src/write.ts
41
+ var import_promises = require("fs/promises");
38
42
  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
+ }
39
50
 
40
51
  // src/scanner.ts
41
- var import_promises = require("fs/promises");
52
+ var import_promises2 = require("fs/promises");
53
+ var import_node_path2 = require("path");
42
54
  var import_fast_glob = __toESM(require("fast-glob"), 1);
55
+ var import_picomatch = __toESM(require("picomatch"), 1);
43
56
 
44
57
  // src/parser.ts
45
58
  function stepQuote(text, i, quote) {
@@ -357,7 +370,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
357
370
  files.map(async (file) => {
358
371
  let css;
359
372
  try {
360
- css = await (0, import_promises.readFile)(file, "utf8");
373
+ css = await (0, import_promises2.readFile)(file, "utf8");
361
374
  } catch (err) {
362
375
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
363
376
  return null;
@@ -381,6 +394,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
381
394
  return { declarations, properties, themes: themeValues, docs };
382
395
  }
383
396
  var ROOT_RE = /\bcssVars\b/g;
397
+ var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
398
+ var ALIAS_RE = /(?:^|,)\s*(?:type\s+)?cssVars\s+as\s+([A-Za-z_$][\w$]*)\s*(?=,|$)/g;
399
+ function rootPattern(text) {
400
+ const aliases = /* @__PURE__ */ new Set();
401
+ for (const [, specifiers] of text.matchAll(IMPORT_RE)) {
402
+ for (const [, alias] of specifiers.matchAll(ALIAS_RE)) aliases.add(alias);
403
+ }
404
+ if (aliases.size === 0) return ROOT_RE;
405
+ const names = [...aliases].map((alias) => alias.replace(/\$/g, "\\$")).join("|");
406
+ return new RegExp(`${ROOT_RE.source}|(?<![\\w$.])(?:${names})(?![\\w$])`, "g");
407
+ }
384
408
  var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
385
409
  function readAccess(text, from) {
386
410
  ACCESS_RE.lastIndex = from;
@@ -388,7 +412,7 @@ function readAccess(text, from) {
388
412
  return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
389
413
  }
390
414
  function extractUsage(text, into) {
391
- for (const root of text.matchAll(ROOT_RE)) {
415
+ for (const root of text.matchAll(rootPattern(text))) {
392
416
  const first = readAccess(text, root.index + root[0].length);
393
417
  if (!first) continue;
394
418
  into.keys.add(first.key);
@@ -405,7 +429,7 @@ async function scanUsage(patterns, exclude) {
405
429
  const texts = await Promise.all(
406
430
  files.map(async (file) => {
407
431
  try {
408
- return await (0, import_promises.readFile)(file, "utf8");
432
+ return await (0, import_promises2.readFile)(file, "utf8");
409
433
  } catch (err) {
410
434
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
411
435
  return "";
@@ -422,7 +446,7 @@ async function scanReferences(patterns, exclude) {
422
446
  const perFile = await Promise.all(
423
447
  files.map(async (file) => {
424
448
  try {
425
- return { file, css: await (0, import_promises.readFile)(file, "utf8") };
449
+ return { file, css: await (0, import_promises2.readFile)(file, "utf8") };
426
450
  } catch (err) {
427
451
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
428
452
  return null;
@@ -762,19 +786,19 @@ function generateTokens(varNames, options = {}) {
762
786
  return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
763
787
  });
764
788
  const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
765
- const resolve3 = (value) => {
789
+ const resolve4 = (value) => {
766
790
  const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
767
791
  return target ? `{${target.join(".")}}` : value;
768
792
  };
769
793
  const root = {};
770
794
  for (const { meta, value, path } of tokens) {
771
- const token = { $value: resolve3(value) };
795
+ const token = { $value: resolve4(value) };
772
796
  const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
773
797
  if (type) token.$type = type;
774
798
  if (meta.doc?.description) token.$description = meta.doc.description;
775
799
  if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
776
800
  if (meta.themes) {
777
- const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
801
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve4(themeValue)]));
778
802
  token.$extensions = { "css-typed-vars": { themes } };
779
803
  }
780
804
  const [key, leaf] = path;
@@ -843,7 +867,7 @@ async function computeOutputs(options) {
843
867
  }
844
868
  names = used;
845
869
  }
846
- const outPath = (0, import_node_path.resolve)(options.output);
870
+ const outPath = (0, import_node_path3.resolve)(options.output);
847
871
  const generatorOptions = {
848
872
  prefix: options.prefix,
849
873
  naming: options.naming,
@@ -868,18 +892,18 @@ async function computeOutputs(options) {
868
892
  }
869
893
  async function generate(options) {
870
894
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
871
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
872
- await (0, import_promises2.writeFile)(outPath, content, "utf8");
895
+ let written = await writeOutput(outPath, content);
873
896
  if (dtsPath && dtsContent !== void 0) {
874
- await (0, import_promises2.writeFile)(dtsPath, dtsContent, "utf8");
897
+ if (await writeOutput(dtsPath, dtsContent)) written = true;
875
898
  }
899
+ return written;
876
900
  }
877
901
  async function checkGenerated(options) {
878
902
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
879
- const current = await (0, import_promises2.readFile)(outPath, "utf8").catch(() => null);
903
+ const current = await (0, import_promises3.readFile)(outPath, "utf8").catch(() => null);
880
904
  if (current !== content) return false;
881
905
  if (dtsPath && dtsContent !== void 0) {
882
- const currentDts = await (0, import_promises2.readFile)(dtsPath, "utf8").catch(() => null);
906
+ const currentDts = await (0, import_promises3.readFile)(dtsPath, "utf8").catch(() => null);
883
907
  if (currentDts !== dtsContent) return false;
884
908
  }
885
909
  return true;
@@ -920,33 +944,130 @@ var OPTION_FLAGS = [
920
944
  "--helpers",
921
945
  "--refs-ignore"
922
946
  ];
923
- var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>] [--lint-refs]";
947
+ var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
948
+ var VALUE_FLAGS = [
949
+ "--input",
950
+ "--output",
951
+ "--exclude",
952
+ "--prefix",
953
+ "--naming",
954
+ "--selector",
955
+ "--theme",
956
+ "--usage",
957
+ "--usage-exclude",
958
+ "--refs-ignore",
959
+ "--config"
960
+ ];
961
+ var BOOLEAN_FLAGS = [
962
+ "--group",
963
+ "--prune",
964
+ "--helpers",
965
+ "--watch",
966
+ "--check",
967
+ "--prune-check",
968
+ "--lint-refs",
969
+ "--version",
970
+ "-v",
971
+ "--help",
972
+ "-h"
973
+ ];
974
+ var HELP = `${USAGE}
975
+
976
+ Generates typed constants for the CSS custom properties found in <glob>.
977
+ Options can also be set in css-typed-vars.config.{js,mjs,cjs,ts,mts,json}; flags take precedence.
978
+
979
+ Options:
980
+ --config <file> Config file to use instead of looking one up
981
+ --input <glob> CSS files to scan (repeatable)
982
+ --output <file> .ts, .js/.mjs/.cjs (plus a .d.ts), or .json (design tokens)
983
+ --exclude <glob> Files to skip (repeatable)
984
+ --prefix <prefix> Prefix every generated key
985
+ --naming <convention> camelCase (default), snake, kebab, constant or pascal
986
+ --selector <selector> Also scan this selector's blocks, not just :root/@theme (repeatable)
987
+ --theme <name>=<sel> Theme block, emitted as @theme JSDoc tags (repeatable)
988
+ --group Nest keys by the first hyphen segment (cssVars.color.primary)
989
+ --helpers Also emit CssVarRef and getCssVar/setCssVar/withFallback
990
+ --prune Drop vars with no cssVars.<key> usage (needs --usage)
991
+ --usage <glob> Source files to scan for cssVars usage (repeatable)
992
+ --usage-exclude <glob> Source files to skip in the usage scan (repeatable)
993
+
994
+ Modes:
995
+ --watch Regenerate when input (or, with --prune, usage) files change
996
+ --check Exit 1 if the output is out of date, without writing
997
+ --prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
998
+ --lint-refs Exit 1 on var() references to undeclared variables
999
+ --refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
1000
+ --version, -v Print the version
1001
+ --help, -h Print this help
1002
+
1003
+ Docs: https://stanislavkozachenko.github.io/css-typed-vars/`;
1004
+ function editDistance(a, b) {
1005
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
1006
+ for (let i = 1; i <= a.length; i++) {
1007
+ const next = [i];
1008
+ for (let j = 1; j <= b.length; j++) {
1009
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
1010
+ }
1011
+ row = next;
1012
+ }
1013
+ return row[b.length];
1014
+ }
1015
+ function validateArgs() {
1016
+ for (let i = 0; i < args.length; i++) {
1017
+ const arg = args[i];
1018
+ if (VALUE_FLAGS.includes(arg)) {
1019
+ if (i + 1 >= args.length) throw new CliError(`css-typed-vars: ${arg} requires a value.`);
1020
+ i++;
1021
+ continue;
1022
+ }
1023
+ if (BOOLEAN_FLAGS.includes(arg)) continue;
1024
+ if (arg.startsWith("-")) {
1025
+ 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.`);
1029
+ }
1030
+ 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
+ }
1032
+ }
924
1033
  var CliError = class extends Error {
925
1034
  };
1035
+ var CONFIG_FILES = [
1036
+ "css-typed-vars.config.js",
1037
+ "css-typed-vars.config.mjs",
1038
+ "css-typed-vars.config.cjs",
1039
+ "css-typed-vars.config.ts",
1040
+ "css-typed-vars.config.mts",
1041
+ "css-typed-vars.config.json"
1042
+ ];
1043
+ async function importConfig(path) {
1044
+ if (/\.json$/i.test(path)) return JSON.parse(await (0, import_promises4.readFile)(path, "utf8"));
1045
+ const mod = await import((0, import_node_url.pathToFileURL)(path).href);
1046
+ return mod.default ?? {};
1047
+ }
926
1048
  async function loadConfig() {
927
- const candidates = [
928
- "css-typed-vars.config.js",
929
- "css-typed-vars.config.mjs",
930
- "css-typed-vars.config.json"
931
- ];
932
- for (const file of candidates) {
933
- const path = (0, import_node_path2.resolve)(process.cwd(), file);
1049
+ const explicit = getArg("--config");
1050
+ if (explicit !== void 0) {
1051
+ const path = (0, import_node_path4.resolve)(process.cwd(), explicit);
1052
+ if (!await exists(path)) throw new CliError(`css-typed-vars: config file "${explicit}" not found.`);
934
1053
  try {
935
- if (file.endsWith(".json")) {
936
- const content = await (0, import_promises3.readFile)(path, "utf8");
937
- return JSON.parse(content);
938
- } else {
939
- const mod = await import((0, import_node_url.pathToFileURL)(path).href);
940
- return mod.default ?? {};
941
- }
1054
+ return await importConfig(path);
1055
+ } catch (err) {
1056
+ throw new CliError(`css-typed-vars: failed to load config "${explicit}": ${err.message}`);
1057
+ }
1058
+ }
1059
+ for (const file of CONFIG_FILES) {
1060
+ const path = (0, import_node_path4.resolve)(process.cwd(), file);
1061
+ if (!await exists(path)) continue;
1062
+ try {
1063
+ return await importConfig(path);
942
1064
  } catch (err) {
943
- const code = err.code;
944
- if (code === "ENOENT" || code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") continue;
945
1065
  console.warn(`css-typed-vars: failed to load config "${file}": ${err.message}`);
946
1066
  }
947
1067
  }
948
1068
  return {};
949
1069
  }
1070
+ var exists = (path) => (0, import_promises4.access)(path).then(() => true, () => false);
950
1071
  function applyFlags(config) {
951
1072
  const inputArgs = getArgs("--input");
952
1073
  const excludeArgs = getArgs("--exclude");
@@ -1006,7 +1127,7 @@ function validateTarget({ options, tag }, single) {
1006
1127
  }
1007
1128
  if (!input || !output) {
1008
1129
  throw new CliError(single ? `${USAGE}
1009
- Or add a css-typed-vars.config.js file with input and output fields.` : `${tag}: every target needs "input" and "output".`);
1130
+ Or add a css-typed-vars.config.js file with input and output fields. Run with --help to see all options.` : `${tag}: every target needs "input" and "output".`);
1010
1131
  }
1011
1132
  if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
1012
1133
  if ((prune || pruneCheckMode) && !usage) {
@@ -1015,7 +1136,7 @@ Or add a css-typed-vars.config.js file with input and output fields.` : `${tag}:
1015
1136
  }
1016
1137
  async function lintRefs({ options, tag }) {
1017
1138
  const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
1018
- const format = (ref) => ` ${(0, import_node_path2.relative)(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
1139
+ const format = (ref) => ` ${(0, import_node_path4.relative)(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
1019
1140
  const errors = refs.filter((ref) => !ref.hasFallback);
1020
1141
  const warnings = refs.filter((ref) => ref.hasFallback);
1021
1142
  if (warnings.length > 0) {
@@ -1048,22 +1169,53 @@ async function check({ options, tag }) {
1048
1169
  return true;
1049
1170
  }
1050
1171
  async function run({ options }) {
1051
- await generate({ ...options, input: options.input, output: options.output });
1052
- console.log(`Generated \u2192 ${options.output}`);
1172
+ const written = await generate({ ...options, input: options.input, output: options.output });
1173
+ console.log(`${written ? "Generated" : "Up to date"} \u2192 ${options.output}`);
1053
1174
  }
1175
+ var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
1054
1176
  function watchTarget(target) {
1055
- const { input, exclude } = target.options;
1056
- const patterns = Array.isArray(input) ? input : [input];
1177
+ const { input, exclude, output, prune, usage, usageExclude } = target.options;
1178
+ const jsExt = /\.(m|c)?js$/i.exec(output);
1179
+ const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => (0, import_node_path4.resolve)(path)));
1180
+ let timer = null;
1181
+ let running = false;
1182
+ let pending = false;
1183
+ const regenerate = async () => {
1184
+ if (running) {
1185
+ pending = true;
1186
+ return;
1187
+ }
1188
+ running = true;
1189
+ await run(target).catch(console.error);
1190
+ running = false;
1191
+ if (pending) {
1192
+ pending = false;
1193
+ await regenerate();
1194
+ }
1195
+ };
1057
1196
  const makeHandler = (label) => (file) => {
1197
+ if (outputs.has((0, import_node_path4.resolve)(file))) return;
1058
1198
  console.log(`${label}: ${file}`);
1059
- run(target).catch(console.error);
1199
+ if (timer) clearTimeout(timer);
1200
+ timer = setTimeout(() => {
1201
+ timer = null;
1202
+ void regenerate();
1203
+ }, 100);
1060
1204
  };
1061
- const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
1062
- (0, import_chokidar.watch)(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
1205
+ const subscribe = (patterns, ignored) => {
1206
+ (0, import_chokidar.watch)(patterns, { ignoreInitial: true, ...ignored.length > 0 ? { ignored } : {} }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
1207
+ };
1208
+ subscribe(toArray(input), toArray(exclude));
1209
+ if (prune) subscribe(toArray(usage), toArray(usageExclude));
1063
1210
  }
1064
1211
  async function main() {
1212
+ validateArgs();
1213
+ if (args.includes("--help") || args.includes("-h")) {
1214
+ console.log(HELP);
1215
+ return;
1216
+ }
1065
1217
  if (args.includes("--version") || args.includes("-v")) {
1066
- const pkg = JSON.parse(await (0, import_promises3.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
1218
+ const pkg = JSON.parse(await (0, import_promises4.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
1067
1219
  console.log(pkg.version);
1068
1220
  process.exit(0);
1069
1221
  }
package/dist/cli.js CHANGED
@@ -4,13 +4,13 @@ import {
4
4
  findUndefinedRefs,
5
5
  findUnusedVars,
6
6
  generate
7
- } from "./chunk-YDXCJQPL.js";
7
+ } from "./chunk-O7MEOCHS.js";
8
8
  import {
9
9
  VALID_NAMINGS
10
- } from "./chunk-5HPTHW7S.js";
10
+ } from "./chunk-XCAFJREQ.js";
11
11
 
12
12
  // src/cli.ts
13
- import { readFile } from "fs/promises";
13
+ import { access, readFile } from "fs/promises";
14
14
  import { relative, resolve } from "path";
15
15
  import { pathToFileURL } from "url";
16
16
  import { watch } from "chokidar";
@@ -48,33 +48,130 @@ var OPTION_FLAGS = [
48
48
  "--helpers",
49
49
  "--refs-ignore"
50
50
  ];
51
- var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>] [--lint-refs]";
51
+ var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
52
+ var VALUE_FLAGS = [
53
+ "--input",
54
+ "--output",
55
+ "--exclude",
56
+ "--prefix",
57
+ "--naming",
58
+ "--selector",
59
+ "--theme",
60
+ "--usage",
61
+ "--usage-exclude",
62
+ "--refs-ignore",
63
+ "--config"
64
+ ];
65
+ var BOOLEAN_FLAGS = [
66
+ "--group",
67
+ "--prune",
68
+ "--helpers",
69
+ "--watch",
70
+ "--check",
71
+ "--prune-check",
72
+ "--lint-refs",
73
+ "--version",
74
+ "-v",
75
+ "--help",
76
+ "-h"
77
+ ];
78
+ var HELP = `${USAGE}
79
+
80
+ Generates typed constants for the CSS custom properties found in <glob>.
81
+ Options can also be set in css-typed-vars.config.{js,mjs,cjs,ts,mts,json}; flags take precedence.
82
+
83
+ Options:
84
+ --config <file> Config file to use instead of looking one up
85
+ --input <glob> CSS files to scan (repeatable)
86
+ --output <file> .ts, .js/.mjs/.cjs (plus a .d.ts), or .json (design tokens)
87
+ --exclude <glob> Files to skip (repeatable)
88
+ --prefix <prefix> Prefix every generated key
89
+ --naming <convention> camelCase (default), snake, kebab, constant or pascal
90
+ --selector <selector> Also scan this selector's blocks, not just :root/@theme (repeatable)
91
+ --theme <name>=<sel> Theme block, emitted as @theme JSDoc tags (repeatable)
92
+ --group Nest keys by the first hyphen segment (cssVars.color.primary)
93
+ --helpers Also emit CssVarRef and getCssVar/setCssVar/withFallback
94
+ --prune Drop vars with no cssVars.<key> usage (needs --usage)
95
+ --usage <glob> Source files to scan for cssVars usage (repeatable)
96
+ --usage-exclude <glob> Source files to skip in the usage scan (repeatable)
97
+
98
+ Modes:
99
+ --watch Regenerate when input (or, with --prune, usage) files change
100
+ --check Exit 1 if the output is out of date, without writing
101
+ --prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
102
+ --lint-refs Exit 1 on var() references to undeclared variables
103
+ --refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
104
+ --version, -v Print the version
105
+ --help, -h Print this help
106
+
107
+ Docs: https://stanislavkozachenko.github.io/css-typed-vars/`;
108
+ function editDistance(a, b) {
109
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
110
+ for (let i = 1; i <= a.length; i++) {
111
+ const next = [i];
112
+ for (let j = 1; j <= b.length; j++) {
113
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
114
+ }
115
+ row = next;
116
+ }
117
+ return row[b.length];
118
+ }
119
+ function validateArgs() {
120
+ for (let i = 0; i < args.length; i++) {
121
+ const arg = args[i];
122
+ if (VALUE_FLAGS.includes(arg)) {
123
+ if (i + 1 >= args.length) throw new CliError(`css-typed-vars: ${arg} requires a value.`);
124
+ i++;
125
+ continue;
126
+ }
127
+ if (BOOLEAN_FLAGS.includes(arg)) continue;
128
+ if (arg.startsWith("-")) {
129
+ 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.`);
133
+ }
134
+ 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
+ }
136
+ }
52
137
  var CliError = class extends Error {
53
138
  };
139
+ var CONFIG_FILES = [
140
+ "css-typed-vars.config.js",
141
+ "css-typed-vars.config.mjs",
142
+ "css-typed-vars.config.cjs",
143
+ "css-typed-vars.config.ts",
144
+ "css-typed-vars.config.mts",
145
+ "css-typed-vars.config.json"
146
+ ];
147
+ async function importConfig(path) {
148
+ if (/\.json$/i.test(path)) return JSON.parse(await readFile(path, "utf8"));
149
+ const mod = await import(pathToFileURL(path).href);
150
+ return mod.default ?? {};
151
+ }
54
152
  async function loadConfig() {
55
- const candidates = [
56
- "css-typed-vars.config.js",
57
- "css-typed-vars.config.mjs",
58
- "css-typed-vars.config.json"
59
- ];
60
- for (const file of candidates) {
153
+ const explicit = getArg("--config");
154
+ if (explicit !== void 0) {
155
+ const path = resolve(process.cwd(), explicit);
156
+ if (!await exists(path)) throw new CliError(`css-typed-vars: config file "${explicit}" not found.`);
157
+ try {
158
+ return await importConfig(path);
159
+ } catch (err) {
160
+ throw new CliError(`css-typed-vars: failed to load config "${explicit}": ${err.message}`);
161
+ }
162
+ }
163
+ for (const file of CONFIG_FILES) {
61
164
  const path = resolve(process.cwd(), file);
165
+ if (!await exists(path)) continue;
62
166
  try {
63
- if (file.endsWith(".json")) {
64
- const content = await readFile(path, "utf8");
65
- return JSON.parse(content);
66
- } else {
67
- const mod = await import(pathToFileURL(path).href);
68
- return mod.default ?? {};
69
- }
167
+ return await importConfig(path);
70
168
  } catch (err) {
71
- const code = err.code;
72
- if (code === "ENOENT" || code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") continue;
73
169
  console.warn(`css-typed-vars: failed to load config "${file}": ${err.message}`);
74
170
  }
75
171
  }
76
172
  return {};
77
173
  }
174
+ var exists = (path) => access(path).then(() => true, () => false);
78
175
  function applyFlags(config) {
79
176
  const inputArgs = getArgs("--input");
80
177
  const excludeArgs = getArgs("--exclude");
@@ -134,7 +231,7 @@ function validateTarget({ options, tag }, single) {
134
231
  }
135
232
  if (!input || !output) {
136
233
  throw new CliError(single ? `${USAGE}
137
- Or add a css-typed-vars.config.js file with input and output fields.` : `${tag}: every target needs "input" and "output".`);
234
+ Or add a css-typed-vars.config.js file with input and output fields. Run with --help to see all options.` : `${tag}: every target needs "input" and "output".`);
138
235
  }
139
236
  if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
140
237
  if ((prune || pruneCheckMode) && !usage) {
@@ -176,20 +273,51 @@ async function check({ options, tag }) {
176
273
  return true;
177
274
  }
178
275
  async function run({ options }) {
179
- await generate({ ...options, input: options.input, output: options.output });
180
- console.log(`Generated \u2192 ${options.output}`);
276
+ const written = await generate({ ...options, input: options.input, output: options.output });
277
+ console.log(`${written ? "Generated" : "Up to date"} \u2192 ${options.output}`);
181
278
  }
279
+ var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
182
280
  function watchTarget(target) {
183
- const { input, exclude } = target.options;
184
- const patterns = Array.isArray(input) ? input : [input];
281
+ const { input, exclude, output, prune, usage, usageExclude } = target.options;
282
+ const jsExt = /\.(m|c)?js$/i.exec(output);
283
+ const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => resolve(path)));
284
+ let timer = null;
285
+ let running = false;
286
+ let pending = false;
287
+ const regenerate = async () => {
288
+ if (running) {
289
+ pending = true;
290
+ return;
291
+ }
292
+ running = true;
293
+ await run(target).catch(console.error);
294
+ running = false;
295
+ if (pending) {
296
+ pending = false;
297
+ await regenerate();
298
+ }
299
+ };
185
300
  const makeHandler = (label) => (file) => {
301
+ if (outputs.has(resolve(file))) return;
186
302
  console.log(`${label}: ${file}`);
187
- run(target).catch(console.error);
303
+ if (timer) clearTimeout(timer);
304
+ timer = setTimeout(() => {
305
+ timer = null;
306
+ void regenerate();
307
+ }, 100);
308
+ };
309
+ const subscribe = (patterns, ignored) => {
310
+ watch(patterns, { ignoreInitial: true, ...ignored.length > 0 ? { ignored } : {} }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
188
311
  };
189
- const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
190
- watch(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
312
+ subscribe(toArray(input), toArray(exclude));
313
+ if (prune) subscribe(toArray(usage), toArray(usageExclude));
191
314
  }
192
315
  async function main() {
316
+ validateArgs();
317
+ if (args.includes("--help") || args.includes("-h")) {
318
+ console.log(HELP);
319
+ return;
320
+ }
193
321
  if (args.includes("--version") || args.includes("-v")) {
194
322
  const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
195
323
  console.log(pkg.version);