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/esbuild.cjs CHANGED
@@ -54,8 +54,8 @@ var import_node_path3 = require("path");
54
54
  // src/scanner.ts
55
55
  var import_promises2 = require("fs/promises");
56
56
  var import_node_path2 = require("path");
57
- var import_fast_glob = __toESM(require("fast-glob"), 1);
58
57
  var import_picomatch = __toESM(require("picomatch"), 1);
58
+ var import_tinyglobby = require("tinyglobby");
59
59
 
60
60
  // src/parser.ts
61
61
  function stepQuote(text, i, quote) {
@@ -337,6 +337,39 @@ function toRawPosition(stripped, strippedPos) {
337
337
  function normalizePatterns(patterns) {
338
338
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
339
339
  }
340
+ function comparePaths(a, b) {
341
+ const as = a.split("/");
342
+ const bs = b.split("/");
343
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
344
+ if (as[i] === bs[i]) continue;
345
+ const aIsFile = i === as.length - 1;
346
+ const bIsFile = i === bs.length - 1;
347
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
348
+ return as[i] < bs[i] ? -1 : 1;
349
+ }
350
+ return as.length - bs.length;
351
+ }
352
+ async function globFiles(pattern, ignore) {
353
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
354
+ return (0, import_tinyglobby.glob)(pattern, { absolute: true, ignore, expandDirectories: false });
355
+ }
356
+ const { base, glob: rest, isGlob } = import_picomatch.default.scan(pattern);
357
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [import_node_path2.posix.dirname(pattern), import_node_path2.posix.basename(pattern)];
358
+ const matches = await (0, import_tinyglobby.glob)(relativeGlob, { cwd, absolute: true, expandDirectories: false });
359
+ if (ignore.length === 0) return matches;
360
+ const isIgnored = (0, import_picomatch.default)(ignore, { dot: true });
361
+ return matches.filter((file) => !isIgnored(file));
362
+ }
363
+ async function findFiles(patterns, exclude) {
364
+ const normalized = normalizePatterns(patterns);
365
+ const ignore = [
366
+ ...exclude ? normalizePatterns(exclude) : [],
367
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
368
+ ];
369
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
370
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
371
+ return [...new Set(files.reverse())].reverse();
372
+ }
340
373
  function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
341
374
  const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
342
375
  const include = compile(patterns);
@@ -348,12 +381,20 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
348
381
  return matches(include) && !matches(ignore);
349
382
  };
350
383
  }
384
+ function globWatchRoots(patterns, cwd = process.cwd()) {
385
+ const roots = /* @__PURE__ */ new Map();
386
+ for (const pattern of normalizePatterns(patterns)) {
387
+ const { base, glob: glob2, isGlob } = import_picomatch.default.scan(pattern);
388
+ const dir = (0, import_node_path2.resolve)(cwd, isGlob ? base || "." : (0, import_node_path2.dirname)(pattern));
389
+ const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob2) ? void 0 : glob2.split("/").length - 1;
390
+ const previous = roots.get(dir);
391
+ const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
392
+ roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
393
+ }
394
+ return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
395
+ }
351
396
  function globBaseDirs(patterns, cwd = process.cwd()) {
352
- const dirs = normalizePatterns(patterns).map((pattern) => {
353
- const { base, isGlob } = import_picomatch.default.scan(pattern);
354
- return (0, import_node_path2.resolve)(cwd, isGlob ? base || "." : (0, import_node_path2.dirname)(pattern));
355
- });
356
- return [...new Set(dirs)];
397
+ return globWatchRoots(patterns, cwd).map((root) => root.dir);
357
398
  }
358
399
  function collectVarNames(scanned) {
359
400
  const names = new Set(scanned.declarations.keys());
@@ -363,9 +404,7 @@ function collectVarNames(scanned) {
363
404
  return [...names].sort();
364
405
  }
365
406
  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 });
407
+ const files = await findFiles(patterns, exclude);
369
408
  const perFile = await Promise.all(
370
409
  files.map(async (file) => {
371
410
  let css;
@@ -391,7 +430,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
391
430
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
392
431
  }
393
432
  }
394
- return { declarations, properties, themes: themeValues, docs };
433
+ return { declarations, properties, themes: themeValues, docs, files };
395
434
  }
396
435
  var ROOT_RE = /\bcssVars\b/g;
397
436
  var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
@@ -422,10 +461,8 @@ function extractUsage(text, into) {
422
461
  }
423
462
  }
424
463
  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() };
464
+ const files = await findFiles(patterns, exclude);
465
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
429
466
  const texts = await Promise.all(
430
467
  files.map(async (file) => {
431
468
  try {
@@ -794,18 +831,23 @@ function outputFiles(options, names, generatorOptions) {
794
831
  if (options.tokens) files.push([(0, import_node_path3.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
795
832
  return files;
796
833
  }
797
- var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
834
+ var unplugin_default = (0, import_unplugin.createUnplugin)((options, meta) => {
798
835
  assertPruneCompatible(options);
799
836
  let cachedScan = null;
837
+ let devServer = false;
800
838
  const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
801
839
  const applyPrune = async (names) => {
802
- if (!options.prune) return names;
840
+ if (!options.prune) return { names, usageFiles: [] };
803
841
  const usage = await scanUsage(options.usage, options.usageExclude);
804
842
  const { used, unused } = partitionUnused(names, usage, options);
805
843
  if (unused.length > 0) {
806
844
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
807
845
  }
808
- return used;
846
+ return { names: used, usageFiles: usage.files };
847
+ };
848
+ const watchFiles = (context, scanned, usageFiles) => {
849
+ if (devServer) return;
850
+ for (const file of [...scanned.files, ...usageFiles]) context.addWatchFile((0, import_node_path3.resolve)(file));
809
851
  };
810
852
  const generatorOptions = ({ declarations, properties, themes, docs }) => ({
811
853
  prefix: options.prefix,
@@ -826,6 +868,9 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
826
868
  name: "css-typed-vars",
827
869
  vite: {
828
870
  enforce: "pre",
871
+ configResolved(config) {
872
+ devServer = config.command === "serve";
873
+ },
829
874
  configureServer(server) {
830
875
  let generation = 0;
831
876
  let debounceTimer = null;
@@ -836,7 +881,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
836
881
  cachedScan = scanPromise;
837
882
  const scanned = await scanPromise;
838
883
  if (myGeneration !== generation) return;
839
- const names = await resolveNames(scanned);
884
+ const { names } = await resolveNames(scanned);
840
885
  if (myGeneration !== generation) return;
841
886
  const files = outputFiles(options, names, generatorOptions(scanned));
842
887
  if (files.length > 0) {
@@ -876,7 +921,8 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
876
921
  async buildStart() {
877
922
  cachedScan = scan();
878
923
  const scanned = await cachedScan;
879
- const names = await resolveNames(scanned);
924
+ const { names, usageFiles } = await resolveNames(scanned);
925
+ if (meta.framework !== "esbuild") watchFiles(this, scanned, usageFiles);
880
926
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
881
927
  await writeOutput(path, content);
882
928
  }
@@ -887,7 +933,8 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
887
933
  async load(id) {
888
934
  if (id === RESOLVED_ID) {
889
935
  const scanned = await (cachedScan ?? scan());
890
- const names = await applyPrune(collectVarNames(scanned));
936
+ const { names, usageFiles } = await applyPrune(collectVarNames(scanned));
937
+ watchFiles(this, scanned, usageFiles);
891
938
  return generateJs(names, generatorOptions(scanned));
892
939
  }
893
940
  }
package/dist/esbuild.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-NZUQZYNM.js";
4
- import "./chunk-XCAFJREQ.js";
3
+ } from "./chunk-XWMRTHOE.js";
4
+ import "./chunk-RZLASYCF.js";
5
5
 
6
6
  // src/esbuild.ts
7
7
  var esbuild_default = unplugin_default.esbuild;
package/dist/index.cjs CHANGED
@@ -69,8 +69,8 @@ async function writeOutput(path, content) {
69
69
  // src/scanner.ts
70
70
  var import_promises2 = require("fs/promises");
71
71
  var import_node_path2 = require("path");
72
- var import_fast_glob = __toESM(require("fast-glob"), 1);
73
72
  var import_picomatch = __toESM(require("picomatch"), 1);
73
+ var import_tinyglobby = require("tinyglobby");
74
74
 
75
75
  // src/parser.ts
76
76
  function stepQuote(text, i, quote) {
@@ -371,6 +371,29 @@ function parseVarReferences(css) {
371
371
  }
372
372
  return refs;
373
373
  }
374
+ var SOURCE_REF_RE = /\bvar\(\s*(--[\w-]+)\s*(,)?|(?<=[\w-]-)\((?:[\w-]+:)?(--[\w-]+)\)/g;
375
+ function parseSourceVarReferences(text) {
376
+ const lineStarts = [0];
377
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") lineStarts.push(i + 1);
378
+ const refs = [];
379
+ for (const match of text.matchAll(SOURCE_REF_RE)) {
380
+ let line = lineStarts.length - 1;
381
+ while (lineStarts[line] > match.index) line--;
382
+ refs.push({
383
+ name: match[1] ?? match[3],
384
+ hasFallback: match[2] === ",",
385
+ line: line + 1,
386
+ column: match.index - lineStarts[line] + 1
387
+ });
388
+ }
389
+ return refs;
390
+ }
391
+ function parseSourceDeclaredNames(text) {
392
+ const names = /* @__PURE__ */ new Set();
393
+ for (const match of text.matchAll(/(?<![\w-])(--[\w-]+)['"`]?\s*:/g)) names.add(match[1]);
394
+ for (const match of text.matchAll(/\bsetProperty\(\s*['"`](--[\w-]+)['"`]/g)) names.add(match[1]);
395
+ return names;
396
+ }
374
397
  function parseDeclaredNames(css) {
375
398
  const masked = maskQuotedContent(stripComments(css));
376
399
  const names = /* @__PURE__ */ new Set();
@@ -383,6 +406,39 @@ function parseDeclaredNames(css) {
383
406
  function normalizePatterns(patterns) {
384
407
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
385
408
  }
409
+ function comparePaths(a, b) {
410
+ const as = a.split("/");
411
+ const bs = b.split("/");
412
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
413
+ if (as[i] === bs[i]) continue;
414
+ const aIsFile = i === as.length - 1;
415
+ const bIsFile = i === bs.length - 1;
416
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
417
+ return as[i] < bs[i] ? -1 : 1;
418
+ }
419
+ return as.length - bs.length;
420
+ }
421
+ async function globFiles(pattern, ignore) {
422
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
423
+ return (0, import_tinyglobby.glob)(pattern, { absolute: true, ignore, expandDirectories: false });
424
+ }
425
+ const { base, glob: rest, isGlob } = import_picomatch.default.scan(pattern);
426
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [import_node_path2.posix.dirname(pattern), import_node_path2.posix.basename(pattern)];
427
+ const matches = await (0, import_tinyglobby.glob)(relativeGlob, { cwd, absolute: true, expandDirectories: false });
428
+ if (ignore.length === 0) return matches;
429
+ const isIgnored = (0, import_picomatch.default)(ignore, { dot: true });
430
+ return matches.filter((file) => !isIgnored(file));
431
+ }
432
+ async function findFiles(patterns, exclude) {
433
+ const normalized = normalizePatterns(patterns);
434
+ const ignore = [
435
+ ...exclude ? normalizePatterns(exclude) : [],
436
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
437
+ ];
438
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
439
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
440
+ return [...new Set(files.reverse())].reverse();
441
+ }
386
442
  function collectVarNames(scanned) {
387
443
  const names = new Set(scanned.declarations.keys());
388
444
  for (const values of scanned.themes.values()) {
@@ -391,9 +447,7 @@ function collectVarNames(scanned) {
391
447
  return [...names].sort();
392
448
  }
393
449
  async function scanCss(patterns, exclude, selectors, themes = {}) {
394
- const normalized = normalizePatterns(patterns);
395
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
396
- const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
450
+ const files = await findFiles(patterns, exclude);
397
451
  const perFile = await Promise.all(
398
452
  files.map(async (file) => {
399
453
  let css;
@@ -419,7 +473,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
419
473
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
420
474
  }
421
475
  }
422
- return { declarations, properties, themes: themeValues, docs };
476
+ return { declarations, properties, themes: themeValues, docs, files };
423
477
  }
424
478
  async function scanVarDeclarations(patterns, exclude, selectors) {
425
479
  return (await scanCss(patterns, exclude, selectors)).declarations;
@@ -457,10 +511,8 @@ function extractUsage(text, into) {
457
511
  }
458
512
  }
459
513
  async function scanUsage(patterns, exclude) {
460
- const normalized = normalizePatterns(patterns);
461
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
462
- const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
463
- const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
514
+ const files = await findFiles(patterns, exclude);
515
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
464
516
  const texts = await Promise.all(
465
517
  files.map(async (file) => {
466
518
  try {
@@ -474,10 +526,10 @@ async function scanUsage(patterns, exclude) {
474
526
  for (const text of texts) extractUsage(text, usage);
475
527
  return usage;
476
528
  }
477
- async function scanReferences(patterns, exclude) {
478
- const normalized = normalizePatterns(patterns);
479
- const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
480
- const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
529
+ async function scanReferences(patterns, exclude, source = false) {
530
+ const parseReferences = source ? parseSourceVarReferences : parseVarReferences;
531
+ const parseDeclared = source ? parseSourceDeclaredNames : parseDeclaredNames;
532
+ const files = (await findFiles(patterns, exclude)).sort();
481
533
  const perFile = await Promise.all(
482
534
  files.map(async (file) => {
483
535
  try {
@@ -492,8 +544,8 @@ async function scanReferences(patterns, exclude) {
492
544
  const declared = /* @__PURE__ */ new Set();
493
545
  for (const result of perFile) {
494
546
  if (!result) continue;
495
- for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
496
- for (const name of parseDeclaredNames(result.css)) declared.add(name);
547
+ for (const ref of parseReferences(result.css)) references.push({ ...ref, file: result.file });
548
+ for (const name of parseDeclared(result.css)) declared.add(name);
497
549
  }
498
550
  return { references, declared };
499
551
  }
@@ -887,9 +939,13 @@ function matchesIgnore(name, patterns) {
887
939
  return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
888
940
  }
889
941
  async function findUndefinedRefs(options) {
890
- const { references, declared } = await scanReferences(options.input, options.exclude);
942
+ const [css, source] = await Promise.all([
943
+ scanReferences(options.input, options.exclude),
944
+ options.refsSource ? scanReferences(options.refsSource, void 0, true) : null
945
+ ]);
946
+ const declared = /* @__PURE__ */ new Set([...css.declared, ...source?.declared ?? []]);
891
947
  const ignore = options.refsIgnore ?? [];
892
- return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
948
+ return [...css.references, ...source?.references ?? []].filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
893
949
  }
894
950
  async function computeOutputs(options) {
895
951
  assertPruneCompatible(options);
package/dist/index.d.cts CHANGED
@@ -8,6 +8,8 @@ interface ScannedCss {
8
8
  themes: Map<string, Map<string, string>>;
9
9
  /** `/** ... *\/` doc comments placed directly before a declaration. */
10
10
  docs: Map<string, VarDoc>;
11
+ /** Every file the globs matched, absolute — what the scan's result depends on. */
12
+ files: string[];
11
13
  }
12
14
  declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[], themes?: Record<string, string>): Promise<ScannedCss>;
13
15
  declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
@@ -15,7 +17,7 @@ declare function scanVarNames(patterns: string | string[], exclude?: string | st
15
17
  interface FileReference extends VarReference {
16
18
  file: string;
17
19
  }
18
- declare function scanReferences(patterns: string | string[], exclude?: string | string[]): Promise<{
20
+ declare function scanReferences(patterns: string | string[], exclude?: string | string[], source?: boolean): Promise<{
19
21
  references: FileReference[];
20
22
  declared: Set<string>;
21
23
  }>;
@@ -45,6 +47,11 @@ interface GenerateOptions {
45
47
  helpers?: boolean;
46
48
  /** Names (or `--prefix-*` patterns) that `findUndefinedRefs` shouldn't report, e.g. vars set from JS. */
47
49
  refsIgnore?: string[];
50
+ /**
51
+ * Glob(s) of source files (TS/JSX, Vue, HTML, ...) whose `var(--name)` references
52
+ * (and Tailwind `bg-(--name)` shorthands) `findUndefinedRefs` also checks.
53
+ */
54
+ refsSource?: string | string[];
48
55
  }
49
56
  /** A CLI config file's options — like `GenerateOptions`, but anything may come from CLI flags instead. */
50
57
  type Config = Partial<GenerateOptions>;
@@ -55,7 +62,7 @@ type Config = Partial<GenerateOptions>;
55
62
  declare function defineConfig(config: Config): Config;
56
63
  declare function defineConfig(config: Config[]): Config[];
57
64
  declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
58
- declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore'>): Promise<FileReference[]>;
65
+ declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore' | 'refsSource'>): Promise<FileReference[]>;
59
66
  declare function generate(options: GenerateOptions): Promise<boolean>;
60
67
  declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
61
68
 
package/dist/index.d.ts CHANGED
@@ -8,6 +8,8 @@ interface ScannedCss {
8
8
  themes: Map<string, Map<string, string>>;
9
9
  /** `/** ... *\/` doc comments placed directly before a declaration. */
10
10
  docs: Map<string, VarDoc>;
11
+ /** Every file the globs matched, absolute — what the scan's result depends on. */
12
+ files: string[];
11
13
  }
12
14
  declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[], themes?: Record<string, string>): Promise<ScannedCss>;
13
15
  declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
@@ -15,7 +17,7 @@ declare function scanVarNames(patterns: string | string[], exclude?: string | st
15
17
  interface FileReference extends VarReference {
16
18
  file: string;
17
19
  }
18
- declare function scanReferences(patterns: string | string[], exclude?: string | string[]): Promise<{
20
+ declare function scanReferences(patterns: string | string[], exclude?: string | string[], source?: boolean): Promise<{
19
21
  references: FileReference[];
20
22
  declared: Set<string>;
21
23
  }>;
@@ -45,6 +47,11 @@ interface GenerateOptions {
45
47
  helpers?: boolean;
46
48
  /** Names (or `--prefix-*` patterns) that `findUndefinedRefs` shouldn't report, e.g. vars set from JS. */
47
49
  refsIgnore?: string[];
50
+ /**
51
+ * Glob(s) of source files (TS/JSX, Vue, HTML, ...) whose `var(--name)` references
52
+ * (and Tailwind `bg-(--name)` shorthands) `findUndefinedRefs` also checks.
53
+ */
54
+ refsSource?: string | string[];
48
55
  }
49
56
  /** A CLI config file's options — like `GenerateOptions`, but anything may come from CLI flags instead. */
50
57
  type Config = Partial<GenerateOptions>;
@@ -55,7 +62,7 @@ type Config = Partial<GenerateOptions>;
55
62
  declare function defineConfig(config: Config): Config;
56
63
  declare function defineConfig(config: Config[]): Config[];
57
64
  declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
58
- declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore'>): Promise<FileReference[]>;
65
+ declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore' | 'refsSource'>): Promise<FileReference[]>;
59
66
  declare function generate(options: GenerateOptions): Promise<boolean>;
60
67
  declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
61
68
 
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  findUndefinedRefs,
5
5
  findUnusedVars,
6
6
  generate
7
- } from "./chunk-O7MEOCHS.js";
7
+ } from "./chunk-ULIGESN5.js";
8
8
  import {
9
9
  generateCode,
10
10
  generateDeclaration,
@@ -21,7 +21,7 @@ import {
21
21
  scanUsedKeys,
22
22
  scanVarDeclarations,
23
23
  scanVarNames
24
- } from "./chunk-XCAFJREQ.js";
24
+ } from "./chunk-RZLASYCF.js";
25
25
  export {
26
26
  checkGenerated,
27
27
  defineConfig,
package/dist/rollup.cjs CHANGED
@@ -54,8 +54,8 @@ var import_node_path3 = require("path");
54
54
  // src/scanner.ts
55
55
  var import_promises2 = require("fs/promises");
56
56
  var import_node_path2 = require("path");
57
- var import_fast_glob = __toESM(require("fast-glob"), 1);
58
57
  var import_picomatch = __toESM(require("picomatch"), 1);
58
+ var import_tinyglobby = require("tinyglobby");
59
59
 
60
60
  // src/parser.ts
61
61
  function stepQuote(text, i, quote) {
@@ -337,6 +337,39 @@ function toRawPosition(stripped, strippedPos) {
337
337
  function normalizePatterns(patterns) {
338
338
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
339
339
  }
340
+ function comparePaths(a, b) {
341
+ const as = a.split("/");
342
+ const bs = b.split("/");
343
+ for (let i = 0; i < Math.min(as.length, bs.length); i++) {
344
+ if (as[i] === bs[i]) continue;
345
+ const aIsFile = i === as.length - 1;
346
+ const bIsFile = i === bs.length - 1;
347
+ if (aIsFile !== bIsFile) return aIsFile ? -1 : 1;
348
+ return as[i] < bs[i] ? -1 : 1;
349
+ }
350
+ return as.length - bs.length;
351
+ }
352
+ async function globFiles(pattern, ignore) {
353
+ if (!/^(?:[A-Za-z]:)?\//.test(pattern)) {
354
+ return (0, import_tinyglobby.glob)(pattern, { absolute: true, ignore, expandDirectories: false });
355
+ }
356
+ const { base, glob: rest, isGlob } = import_picomatch.default.scan(pattern);
357
+ const [cwd, relativeGlob] = isGlob ? [base, rest] : [import_node_path2.posix.dirname(pattern), import_node_path2.posix.basename(pattern)];
358
+ const matches = await (0, import_tinyglobby.glob)(relativeGlob, { cwd, absolute: true, expandDirectories: false });
359
+ if (ignore.length === 0) return matches;
360
+ const isIgnored = (0, import_picomatch.default)(ignore, { dot: true });
361
+ return matches.filter((file) => !isIgnored(file));
362
+ }
363
+ async function findFiles(patterns, exclude) {
364
+ const normalized = normalizePatterns(patterns);
365
+ const ignore = [
366
+ ...exclude ? normalizePatterns(exclude) : [],
367
+ ...normalized.filter((p) => p.startsWith("!")).map((p) => p.slice(1))
368
+ ];
369
+ const perGlob = await Promise.all(normalized.filter((p) => !p.startsWith("!")).map((p) => globFiles(p, ignore)));
370
+ const files = perGlob.flatMap((matches) => matches.sort(comparePaths));
371
+ return [...new Set(files.reverse())].reverse();
372
+ }
340
373
  function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
341
374
  const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
342
375
  const include = compile(patterns);
@@ -348,12 +381,20 @@ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
348
381
  return matches(include) && !matches(ignore);
349
382
  };
350
383
  }
384
+ function globWatchRoots(patterns, cwd = process.cwd()) {
385
+ const roots = /* @__PURE__ */ new Map();
386
+ for (const pattern of normalizePatterns(patterns)) {
387
+ const { base, glob: glob2, isGlob } = import_picomatch.default.scan(pattern);
388
+ const dir = (0, import_node_path2.resolve)(cwd, isGlob ? base || "." : (0, import_node_path2.dirname)(pattern));
389
+ const depth = !isGlob ? 0 : /\*\*|\{[^}]*\//.test(glob2) ? void 0 : glob2.split("/").length - 1;
390
+ const previous = roots.get(dir);
391
+ const unlimited = roots.has(dir) && previous === void 0 || depth === void 0;
392
+ roots.set(dir, unlimited ? void 0 : Math.max(previous ?? 0, depth));
393
+ }
394
+ return [...roots].map(([dir, depth]) => depth === void 0 ? { dir } : { dir, depth });
395
+ }
351
396
  function globBaseDirs(patterns, cwd = process.cwd()) {
352
- const dirs = normalizePatterns(patterns).map((pattern) => {
353
- const { base, isGlob } = import_picomatch.default.scan(pattern);
354
- return (0, import_node_path2.resolve)(cwd, isGlob ? base || "." : (0, import_node_path2.dirname)(pattern));
355
- });
356
- return [...new Set(dirs)];
397
+ return globWatchRoots(patterns, cwd).map((root) => root.dir);
357
398
  }
358
399
  function collectVarNames(scanned) {
359
400
  const names = new Set(scanned.declarations.keys());
@@ -363,9 +404,7 @@ function collectVarNames(scanned) {
363
404
  return [...names].sort();
364
405
  }
365
406
  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 });
407
+ const files = await findFiles(patterns, exclude);
369
408
  const perFile = await Promise.all(
370
409
  files.map(async (file) => {
371
410
  let css;
@@ -391,7 +430,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
391
430
  for (const [name, value] of values) themeValues.get(theme).set(name, value);
392
431
  }
393
432
  }
394
- return { declarations, properties, themes: themeValues, docs };
433
+ return { declarations, properties, themes: themeValues, docs, files };
395
434
  }
396
435
  var ROOT_RE = /\bcssVars\b/g;
397
436
  var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
@@ -422,10 +461,8 @@ function extractUsage(text, into) {
422
461
  }
423
462
  }
424
463
  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() };
464
+ const files = await findFiles(patterns, exclude);
465
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set(), files };
429
466
  const texts = await Promise.all(
430
467
  files.map(async (file) => {
431
468
  try {
@@ -794,18 +831,23 @@ function outputFiles(options, names, generatorOptions) {
794
831
  if (options.tokens) files.push([(0, import_node_path3.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
795
832
  return files;
796
833
  }
797
- var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
834
+ var unplugin_default = (0, import_unplugin.createUnplugin)((options, meta) => {
798
835
  assertPruneCompatible(options);
799
836
  let cachedScan = null;
837
+ let devServer = false;
800
838
  const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
801
839
  const applyPrune = async (names) => {
802
- if (!options.prune) return names;
840
+ if (!options.prune) return { names, usageFiles: [] };
803
841
  const usage = await scanUsage(options.usage, options.usageExclude);
804
842
  const { used, unused } = partitionUnused(names, usage, options);
805
843
  if (unused.length > 0) {
806
844
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
807
845
  }
808
- return used;
846
+ return { names: used, usageFiles: usage.files };
847
+ };
848
+ const watchFiles = (context, scanned, usageFiles) => {
849
+ if (devServer) return;
850
+ for (const file of [...scanned.files, ...usageFiles]) context.addWatchFile((0, import_node_path3.resolve)(file));
809
851
  };
810
852
  const generatorOptions = ({ declarations, properties, themes, docs }) => ({
811
853
  prefix: options.prefix,
@@ -826,6 +868,9 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
826
868
  name: "css-typed-vars",
827
869
  vite: {
828
870
  enforce: "pre",
871
+ configResolved(config) {
872
+ devServer = config.command === "serve";
873
+ },
829
874
  configureServer(server) {
830
875
  let generation = 0;
831
876
  let debounceTimer = null;
@@ -836,7 +881,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
836
881
  cachedScan = scanPromise;
837
882
  const scanned = await scanPromise;
838
883
  if (myGeneration !== generation) return;
839
- const names = await resolveNames(scanned);
884
+ const { names } = await resolveNames(scanned);
840
885
  if (myGeneration !== generation) return;
841
886
  const files = outputFiles(options, names, generatorOptions(scanned));
842
887
  if (files.length > 0) {
@@ -876,7 +921,8 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
876
921
  async buildStart() {
877
922
  cachedScan = scan();
878
923
  const scanned = await cachedScan;
879
- const names = await resolveNames(scanned);
924
+ const { names, usageFiles } = await resolveNames(scanned);
925
+ if (meta.framework !== "esbuild") watchFiles(this, scanned, usageFiles);
880
926
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
881
927
  await writeOutput(path, content);
882
928
  }
@@ -887,7 +933,8 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
887
933
  async load(id) {
888
934
  if (id === RESOLVED_ID) {
889
935
  const scanned = await (cachedScan ?? scan());
890
- const names = await applyPrune(collectVarNames(scanned));
936
+ const { names, usageFiles } = await applyPrune(collectVarNames(scanned));
937
+ watchFiles(this, scanned, usageFiles);
891
938
  return generateJs(names, generatorOptions(scanned));
892
939
  }
893
940
  }
package/dist/rollup.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-NZUQZYNM.js";
4
- import "./chunk-XCAFJREQ.js";
3
+ } from "./chunk-XWMRTHOE.js";
4
+ import "./chunk-RZLASYCF.js";
5
5
 
6
6
  // src/rollup.ts
7
7
  var rollup_default = unplugin_default.rollup;