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/esbuild.cjs CHANGED
@@ -36,12 +36,26 @@ module.exports = __toCommonJS(esbuild_exports);
36
36
 
37
37
  // src/unplugin.ts
38
38
  var import_unplugin = require("unplugin");
39
- var import_promises2 = require("fs/promises");
39
+
40
+ // src/write.ts
41
+ var import_promises = require("fs/promises");
40
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
+ }
50
+
51
+ // src/unplugin.ts
52
+ var import_node_path3 = require("path");
41
53
 
42
54
  // src/scanner.ts
43
- var import_promises = require("fs/promises");
55
+ var import_promises2 = require("fs/promises");
56
+ var import_node_path2 = require("path");
44
57
  var import_fast_glob = __toESM(require("fast-glob"), 1);
58
+ var import_picomatch = __toESM(require("picomatch"), 1);
45
59
 
46
60
  // src/parser.ts
47
61
  function stepQuote(text, i, quote) {
@@ -323,6 +337,24 @@ function toRawPosition(stripped, strippedPos) {
323
337
  function normalizePatterns(patterns) {
324
338
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
325
339
  }
340
+ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
341
+ const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
342
+ const include = compile(patterns);
343
+ const ignore = exclude ? compile(exclude) : () => false;
344
+ return (file) => {
345
+ const absolute = (0, import_node_path2.resolve)(cwd, file).replace(/\\/g, "/");
346
+ const fromCwd = (0, import_node_path2.relative)(cwd, absolute).replace(/\\/g, "/");
347
+ const matches = (test) => test(fromCwd) || test(absolute);
348
+ return matches(include) && !matches(ignore);
349
+ };
350
+ }
351
+ 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)];
357
+ }
326
358
  function collectVarNames(scanned) {
327
359
  const names = new Set(scanned.declarations.keys());
328
360
  for (const values of scanned.themes.values()) {
@@ -338,7 +370,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
338
370
  files.map(async (file) => {
339
371
  let css;
340
372
  try {
341
- css = await (0, import_promises.readFile)(file, "utf8");
373
+ css = await (0, import_promises2.readFile)(file, "utf8");
342
374
  } catch (err) {
343
375
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
344
376
  return null;
@@ -362,6 +394,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
362
394
  return { declarations, properties, themes: themeValues, docs };
363
395
  }
364
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
+ }
365
408
  var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
366
409
  function readAccess(text, from) {
367
410
  ACCESS_RE.lastIndex = from;
@@ -369,7 +412,7 @@ function readAccess(text, from) {
369
412
  return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
370
413
  }
371
414
  function extractUsage(text, into) {
372
- for (const root of text.matchAll(ROOT_RE)) {
415
+ for (const root of text.matchAll(rootPattern(text))) {
373
416
  const first = readAccess(text, root.index + root[0].length);
374
417
  if (!first) continue;
375
418
  into.keys.add(first.key);
@@ -386,7 +429,7 @@ async function scanUsage(patterns, exclude) {
386
429
  const texts = await Promise.all(
387
430
  files.map(async (file) => {
388
431
  try {
389
- return await (0, import_promises.readFile)(file, "utf8");
432
+ return await (0, import_promises2.readFile)(file, "utf8");
390
433
  } catch (err) {
391
434
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
392
435
  return "";
@@ -690,19 +733,19 @@ function generateTokens(varNames, options = {}) {
690
733
  return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
691
734
  });
692
735
  const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
693
- const resolve2 = (value) => {
736
+ const resolve3 = (value) => {
694
737
  const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
695
738
  return target ? `{${target.join(".")}}` : value;
696
739
  };
697
740
  const root = {};
698
741
  for (const { meta, value, path } of tokens) {
699
- const token = { $value: resolve2(value) };
742
+ const token = { $value: resolve3(value) };
700
743
  const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
701
744
  if (type) token.$type = type;
702
745
  if (meta.doc?.description) token.$description = meta.doc.description;
703
746
  if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
704
747
  if (meta.themes) {
705
- const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
748
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
706
749
  token.$extensions = { "css-typed-vars": { themes } };
707
750
  }
708
751
  const [key, leaf] = path;
@@ -737,17 +780,18 @@ function partitionUnused(names, usage, options) {
737
780
  }
738
781
 
739
782
  // src/unplugin.ts
783
+ var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
740
784
  var VIRTUAL_ID = "css-typed-vars/vars";
741
785
  var RESOLVED_ID = "\0css-typed-vars/vars";
742
786
  function getDtsPath(options) {
743
787
  if (options.dts === false) return null;
744
- return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
788
+ return options.dts ? (0, import_node_path3.resolve)(process.cwd(), options.dts) : (0, import_node_path3.join)(__dirname, "generated.d.ts");
745
789
  }
746
790
  function outputFiles(options, names, generatorOptions) {
747
791
  const files = [];
748
792
  const dtsPath = getDtsPath(options);
749
793
  if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
750
- if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
794
+ if (options.tokens) files.push([(0, import_node_path3.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
751
795
  return files;
752
796
  }
753
797
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
@@ -799,7 +843,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
799
843
  writeQueue = writeQueue.then(async () => {
800
844
  for (const [path, content] of files) {
801
845
  if (myGeneration !== generation) return;
802
- await (0, import_promises2.writeFile)(path, content, "utf8");
846
+ await writeOutput(path, content);
803
847
  }
804
848
  }).catch(console.error);
805
849
  await writeQueue;
@@ -811,8 +855,12 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
811
855
  server.ws.send({ type: "full-reload" });
812
856
  }
813
857
  };
858
+ const isInput = createFileMatcher(options.input, options.exclude);
859
+ const isUsage = options.prune ? createFileMatcher(options.usage, options.usageExclude) : () => false;
860
+ const outputs = new Set([getDtsPath(options), options.tokens && (0, import_node_path3.resolve)(process.cwd(), options.tokens)].filter((path) => !!path).map((path) => (0, import_node_path3.resolve)(path)));
814
861
  const handle = (file) => {
815
- if (!/\.(css|scss|less)$/i.test(file)) return;
862
+ if (outputs.has((0, import_node_path3.resolve)(file))) return;
863
+ if (!isInput(file) && !isUsage(file)) return;
816
864
  if (debounceTimer) clearTimeout(debounceTimer);
817
865
  debounceTimer = setTimeout(() => {
818
866
  debounceTimer = null;
@@ -822,6 +870,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
822
870
  server.watcher.on("change", handle);
823
871
  server.watcher.on("add", handle);
824
872
  server.watcher.on("unlink", handle);
873
+ server.watcher.add(globBaseDirs([...toArray(options.input), ...options.prune ? toArray(options.usage) : []]));
825
874
  }
826
875
  },
827
876
  async buildStart() {
@@ -829,7 +878,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
829
878
  const scanned = await cachedScan;
830
879
  const names = await resolveNames(scanned);
831
880
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
832
- await (0, import_promises2.writeFile)(path, content, "utf8");
881
+ await writeOutput(path, content);
833
882
  }
834
883
  },
835
884
  resolveId(id) {
package/dist/esbuild.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-32V3V6WT.js";
4
- import "./chunk-5HPTHW7S.js";
3
+ } from "./chunk-NZUQZYNM.js";
4
+ import "./chunk-XCAFJREQ.js";
5
5
 
6
6
  // src/esbuild.ts
7
7
  var esbuild_default = unplugin_default.esbuild;
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  checkGenerated: () => checkGenerated,
34
+ defineConfig: () => defineConfig,
34
35
  findUndefinedRefs: () => findUndefinedRefs,
35
36
  findUnusedVars: () => findUnusedVars,
36
37
  generate: () => generate,
@@ -51,12 +52,25 @@ __export(src_exports, {
51
52
  scanVarNames: () => scanVarNames
52
53
  });
53
54
  module.exports = __toCommonJS(src_exports);
54
- var import_promises2 = require("fs/promises");
55
+ var import_promises3 = require("fs/promises");
56
+ var import_node_path3 = require("path");
57
+
58
+ // src/write.ts
59
+ var import_promises = require("fs/promises");
55
60
  var import_node_path = require("path");
61
+ async function writeOutput(path, content) {
62
+ const current = await (0, import_promises.readFile)(path, "utf8").catch(() => null);
63
+ if (current === content) return false;
64
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
65
+ await (0, import_promises.writeFile)(path, content, "utf8");
66
+ return true;
67
+ }
56
68
 
57
69
  // src/scanner.ts
58
- var import_promises = require("fs/promises");
70
+ var import_promises2 = require("fs/promises");
71
+ var import_node_path2 = require("path");
59
72
  var import_fast_glob = __toESM(require("fast-glob"), 1);
73
+ var import_picomatch = __toESM(require("picomatch"), 1);
60
74
 
61
75
  // src/parser.ts
62
76
  function stepQuote(text, i, quote) {
@@ -384,7 +398,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
384
398
  files.map(async (file) => {
385
399
  let css;
386
400
  try {
387
- css = await (0, import_promises.readFile)(file, "utf8");
401
+ css = await (0, import_promises2.readFile)(file, "utf8");
388
402
  } catch (err) {
389
403
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
390
404
  return null;
@@ -415,6 +429,17 @@ async function scanVarNames(patterns, exclude, selectors) {
415
429
  return [...declarations.keys()].sort();
416
430
  }
417
431
  var ROOT_RE = /\bcssVars\b/g;
432
+ var IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\b/g;
433
+ var ALIAS_RE = /(?:^|,)\s*(?:type\s+)?cssVars\s+as\s+([A-Za-z_$][\w$]*)\s*(?=,|$)/g;
434
+ function rootPattern(text) {
435
+ const aliases = /* @__PURE__ */ new Set();
436
+ for (const [, specifiers] of text.matchAll(IMPORT_RE)) {
437
+ for (const [, alias] of specifiers.matchAll(ALIAS_RE)) aliases.add(alias);
438
+ }
439
+ if (aliases.size === 0) return ROOT_RE;
440
+ const names = [...aliases].map((alias) => alias.replace(/\$/g, "\\$")).join("|");
441
+ return new RegExp(`${ROOT_RE.source}|(?<![\\w$.])(?:${names})(?![\\w$])`, "g");
442
+ }
418
443
  var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
419
444
  function readAccess(text, from) {
420
445
  ACCESS_RE.lastIndex = from;
@@ -422,7 +447,7 @@ function readAccess(text, from) {
422
447
  return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
423
448
  }
424
449
  function extractUsage(text, into) {
425
- for (const root of text.matchAll(ROOT_RE)) {
450
+ for (const root of text.matchAll(rootPattern(text))) {
426
451
  const first = readAccess(text, root.index + root[0].length);
427
452
  if (!first) continue;
428
453
  into.keys.add(first.key);
@@ -439,7 +464,7 @@ async function scanUsage(patterns, exclude) {
439
464
  const texts = await Promise.all(
440
465
  files.map(async (file) => {
441
466
  try {
442
- return await (0, import_promises.readFile)(file, "utf8");
467
+ return await (0, import_promises2.readFile)(file, "utf8");
443
468
  } catch (err) {
444
469
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
445
470
  return "";
@@ -456,7 +481,7 @@ async function scanReferences(patterns, exclude) {
456
481
  const perFile = await Promise.all(
457
482
  files.map(async (file) => {
458
483
  try {
459
- return { file, css: await (0, import_promises.readFile)(file, "utf8") };
484
+ return { file, css: await (0, import_promises2.readFile)(file, "utf8") };
460
485
  } catch (err) {
461
486
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
462
487
  return null;
@@ -799,19 +824,19 @@ function generateTokens(varNames, options = {}) {
799
824
  return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
800
825
  });
801
826
  const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
802
- const resolve2 = (value) => {
827
+ const resolve3 = (value) => {
803
828
  const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
804
829
  return target ? `{${target.join(".")}}` : value;
805
830
  };
806
831
  const root = {};
807
832
  for (const { meta, value, path } of tokens) {
808
- const token = { $value: resolve2(value) };
833
+ const token = { $value: resolve3(value) };
809
834
  const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
810
835
  if (type) token.$type = type;
811
836
  if (meta.doc?.description) token.$description = meta.doc.description;
812
837
  if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
813
838
  if (meta.themes) {
814
- const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
839
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
815
840
  token.$extensions = { "css-typed-vars": { themes } };
816
841
  }
817
842
  const [key, leaf] = path;
@@ -846,6 +871,9 @@ function partitionUnused(names, usage, options) {
846
871
  }
847
872
 
848
873
  // src/index.ts
874
+ function defineConfig(config) {
875
+ return config;
876
+ }
849
877
  async function findUnusedVars(options) {
850
878
  if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
851
879
  const [scanned, usage] = await Promise.all([
@@ -880,7 +908,7 @@ async function computeOutputs(options) {
880
908
  }
881
909
  names = used;
882
910
  }
883
- const outPath = (0, import_node_path.resolve)(options.output);
911
+ const outPath = (0, import_node_path3.resolve)(options.output);
884
912
  const generatorOptions = {
885
913
  prefix: options.prefix,
886
914
  naming: options.naming,
@@ -905,18 +933,18 @@ async function computeOutputs(options) {
905
933
  }
906
934
  async function generate(options) {
907
935
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
908
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
909
- await (0, import_promises2.writeFile)(outPath, content, "utf8");
936
+ let written = await writeOutput(outPath, content);
910
937
  if (dtsPath && dtsContent !== void 0) {
911
- await (0, import_promises2.writeFile)(dtsPath, dtsContent, "utf8");
938
+ if (await writeOutput(dtsPath, dtsContent)) written = true;
912
939
  }
940
+ return written;
913
941
  }
914
942
  async function checkGenerated(options) {
915
943
  const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
916
- const current = await (0, import_promises2.readFile)(outPath, "utf8").catch(() => null);
944
+ const current = await (0, import_promises3.readFile)(outPath, "utf8").catch(() => null);
917
945
  if (current !== content) return false;
918
946
  if (dtsPath && dtsContent !== void 0) {
919
- const currentDts = await (0, import_promises2.readFile)(dtsPath, "utf8").catch(() => null);
947
+ const currentDts = await (0, import_promises3.readFile)(dtsPath, "utf8").catch(() => null);
920
948
  if (currentDts !== dtsContent) return false;
921
949
  }
922
950
  return true;
@@ -924,6 +952,7 @@ async function checkGenerated(options) {
924
952
  // Annotate the CommonJS export names for ESM import in node:
925
953
  0 && (module.exports = {
926
954
  checkGenerated,
955
+ defineConfig,
927
956
  findUndefinedRefs,
928
957
  findUnusedVars,
929
958
  generate,
package/dist/index.d.cts CHANGED
@@ -46,9 +46,17 @@ interface GenerateOptions {
46
46
  /** Names (or `--prefix-*` patterns) that `findUndefinedRefs` shouldn't report, e.g. vars set from JS. */
47
47
  refsIgnore?: string[];
48
48
  }
49
+ /** A CLI config file's options — like `GenerateOptions`, but anything may come from CLI flags instead. */
50
+ type Config = Partial<GenerateOptions>;
51
+ /**
52
+ * Types a config file's export (one target, or an array of targets):
53
+ * `export default defineConfig({ input: 'src/styles/*.css', output: 'src/cssVars.ts' })`.
54
+ */
55
+ declare function defineConfig(config: Config): Config;
56
+ declare function defineConfig(config: Config[]): Config[];
49
57
  declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
50
58
  declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore'>): Promise<FileReference[]>;
51
- declare function generate(options: GenerateOptions): Promise<void>;
59
+ declare function generate(options: GenerateOptions): Promise<boolean>;
52
60
  declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
53
61
 
54
- export { type FileReference, type GenerateOptions, NamingConvention, PropertyRule, VarDoc, VarReference, checkGenerated, findUndefinedRefs, findUnusedVars, generate, scanCss, scanReferences, scanUsedKeys, scanVarDeclarations, scanVarNames };
62
+ export { type Config, type FileReference, type GenerateOptions, NamingConvention, PropertyRule, VarDoc, VarReference, checkGenerated, defineConfig, findUndefinedRefs, findUnusedVars, generate, scanCss, scanReferences, scanUsedKeys, scanVarDeclarations, scanVarNames };
package/dist/index.d.ts CHANGED
@@ -46,9 +46,17 @@ interface GenerateOptions {
46
46
  /** Names (or `--prefix-*` patterns) that `findUndefinedRefs` shouldn't report, e.g. vars set from JS. */
47
47
  refsIgnore?: string[];
48
48
  }
49
+ /** A CLI config file's options — like `GenerateOptions`, but anything may come from CLI flags instead. */
50
+ type Config = Partial<GenerateOptions>;
51
+ /**
52
+ * Types a config file's export (one target, or an array of targets):
53
+ * `export default defineConfig({ input: 'src/styles/*.css', output: 'src/cssVars.ts' })`.
54
+ */
55
+ declare function defineConfig(config: Config): Config;
56
+ declare function defineConfig(config: Config[]): Config[];
49
57
  declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'themes' | 'prefix' | 'naming' | 'group' | 'usage' | 'usageExclude'>): Promise<string[]>;
50
58
  declare function findUndefinedRefs(options: Pick<GenerateOptions, 'input' | 'exclude' | 'refsIgnore'>): Promise<FileReference[]>;
51
- declare function generate(options: GenerateOptions): Promise<void>;
59
+ declare function generate(options: GenerateOptions): Promise<boolean>;
52
60
  declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
53
61
 
54
- export { type FileReference, type GenerateOptions, NamingConvention, PropertyRule, VarDoc, VarReference, checkGenerated, findUndefinedRefs, findUnusedVars, generate, scanCss, scanReferences, scanUsedKeys, scanVarDeclarations, scanVarNames };
62
+ export { type Config, type FileReference, type GenerateOptions, NamingConvention, PropertyRule, VarDoc, VarReference, checkGenerated, defineConfig, findUndefinedRefs, findUnusedVars, generate, scanCss, scanReferences, scanUsedKeys, scanVarDeclarations, scanVarNames };
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  checkGenerated,
3
+ defineConfig,
3
4
  findUndefinedRefs,
4
5
  findUnusedVars,
5
6
  generate
6
- } from "./chunk-YDXCJQPL.js";
7
+ } from "./chunk-O7MEOCHS.js";
7
8
  import {
8
9
  generateCode,
9
10
  generateDeclaration,
@@ -20,9 +21,10 @@ import {
20
21
  scanUsedKeys,
21
22
  scanVarDeclarations,
22
23
  scanVarNames
23
- } from "./chunk-5HPTHW7S.js";
24
+ } from "./chunk-XCAFJREQ.js";
24
25
  export {
25
26
  checkGenerated,
27
+ defineConfig,
26
28
  findUndefinedRefs,
27
29
  findUnusedVars,
28
30
  generate,
package/dist/rollup.cjs CHANGED
@@ -36,12 +36,26 @@ module.exports = __toCommonJS(rollup_exports);
36
36
 
37
37
  // src/unplugin.ts
38
38
  var import_unplugin = require("unplugin");
39
- var import_promises2 = require("fs/promises");
39
+
40
+ // src/write.ts
41
+ var import_promises = require("fs/promises");
40
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
+ }
50
+
51
+ // src/unplugin.ts
52
+ var import_node_path3 = require("path");
41
53
 
42
54
  // src/scanner.ts
43
- var import_promises = require("fs/promises");
55
+ var import_promises2 = require("fs/promises");
56
+ var import_node_path2 = require("path");
44
57
  var import_fast_glob = __toESM(require("fast-glob"), 1);
58
+ var import_picomatch = __toESM(require("picomatch"), 1);
45
59
 
46
60
  // src/parser.ts
47
61
  function stepQuote(text, i, quote) {
@@ -323,6 +337,24 @@ function toRawPosition(stripped, strippedPos) {
323
337
  function normalizePatterns(patterns) {
324
338
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
325
339
  }
340
+ function createFileMatcher(patterns, exclude, cwd = process.cwd()) {
341
+ const compile = (globs) => (0, import_picomatch.default)(normalizePatterns(globs).map((p) => p.replace(/^\.\//, "")));
342
+ const include = compile(patterns);
343
+ const ignore = exclude ? compile(exclude) : () => false;
344
+ return (file) => {
345
+ const absolute = (0, import_node_path2.resolve)(cwd, file).replace(/\\/g, "/");
346
+ const fromCwd = (0, import_node_path2.relative)(cwd, absolute).replace(/\\/g, "/");
347
+ const matches = (test) => test(fromCwd) || test(absolute);
348
+ return matches(include) && !matches(ignore);
349
+ };
350
+ }
351
+ 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)];
357
+ }
326
358
  function collectVarNames(scanned) {
327
359
  const names = new Set(scanned.declarations.keys());
328
360
  for (const values of scanned.themes.values()) {
@@ -338,7 +370,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
338
370
  files.map(async (file) => {
339
371
  let css;
340
372
  try {
341
- css = await (0, import_promises.readFile)(file, "utf8");
373
+ css = await (0, import_promises2.readFile)(file, "utf8");
342
374
  } catch (err) {
343
375
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
344
376
  return null;
@@ -362,6 +394,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
362
394
  return { declarations, properties, themes: themeValues, docs };
363
395
  }
364
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
+ }
365
408
  var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
366
409
  function readAccess(text, from) {
367
410
  ACCESS_RE.lastIndex = from;
@@ -369,7 +412,7 @@ function readAccess(text, from) {
369
412
  return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
370
413
  }
371
414
  function extractUsage(text, into) {
372
- for (const root of text.matchAll(ROOT_RE)) {
415
+ for (const root of text.matchAll(rootPattern(text))) {
373
416
  const first = readAccess(text, root.index + root[0].length);
374
417
  if (!first) continue;
375
418
  into.keys.add(first.key);
@@ -386,7 +429,7 @@ async function scanUsage(patterns, exclude) {
386
429
  const texts = await Promise.all(
387
430
  files.map(async (file) => {
388
431
  try {
389
- return await (0, import_promises.readFile)(file, "utf8");
432
+ return await (0, import_promises2.readFile)(file, "utf8");
390
433
  } catch (err) {
391
434
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
392
435
  return "";
@@ -690,19 +733,19 @@ function generateTokens(varNames, options = {}) {
690
733
  return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
691
734
  });
692
735
  const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
693
- const resolve2 = (value) => {
736
+ const resolve3 = (value) => {
694
737
  const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
695
738
  return target ? `{${target.join(".")}}` : value;
696
739
  };
697
740
  const root = {};
698
741
  for (const { meta, value, path } of tokens) {
699
- const token = { $value: resolve2(value) };
742
+ const token = { $value: resolve3(value) };
700
743
  const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
701
744
  if (type) token.$type = type;
702
745
  if (meta.doc?.description) token.$description = meta.doc.description;
703
746
  if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
704
747
  if (meta.themes) {
705
- const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
748
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
706
749
  token.$extensions = { "css-typed-vars": { themes } };
707
750
  }
708
751
  const [key, leaf] = path;
@@ -737,17 +780,18 @@ function partitionUnused(names, usage, options) {
737
780
  }
738
781
 
739
782
  // src/unplugin.ts
783
+ var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
740
784
  var VIRTUAL_ID = "css-typed-vars/vars";
741
785
  var RESOLVED_ID = "\0css-typed-vars/vars";
742
786
  function getDtsPath(options) {
743
787
  if (options.dts === false) return null;
744
- return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
788
+ return options.dts ? (0, import_node_path3.resolve)(process.cwd(), options.dts) : (0, import_node_path3.join)(__dirname, "generated.d.ts");
745
789
  }
746
790
  function outputFiles(options, names, generatorOptions) {
747
791
  const files = [];
748
792
  const dtsPath = getDtsPath(options);
749
793
  if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
750
- if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
794
+ if (options.tokens) files.push([(0, import_node_path3.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
751
795
  return files;
752
796
  }
753
797
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
@@ -799,7 +843,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
799
843
  writeQueue = writeQueue.then(async () => {
800
844
  for (const [path, content] of files) {
801
845
  if (myGeneration !== generation) return;
802
- await (0, import_promises2.writeFile)(path, content, "utf8");
846
+ await writeOutput(path, content);
803
847
  }
804
848
  }).catch(console.error);
805
849
  await writeQueue;
@@ -811,8 +855,12 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
811
855
  server.ws.send({ type: "full-reload" });
812
856
  }
813
857
  };
858
+ const isInput = createFileMatcher(options.input, options.exclude);
859
+ const isUsage = options.prune ? createFileMatcher(options.usage, options.usageExclude) : () => false;
860
+ const outputs = new Set([getDtsPath(options), options.tokens && (0, import_node_path3.resolve)(process.cwd(), options.tokens)].filter((path) => !!path).map((path) => (0, import_node_path3.resolve)(path)));
814
861
  const handle = (file) => {
815
- if (!/\.(css|scss|less)$/i.test(file)) return;
862
+ if (outputs.has((0, import_node_path3.resolve)(file))) return;
863
+ if (!isInput(file) && !isUsage(file)) return;
816
864
  if (debounceTimer) clearTimeout(debounceTimer);
817
865
  debounceTimer = setTimeout(() => {
818
866
  debounceTimer = null;
@@ -822,6 +870,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
822
870
  server.watcher.on("change", handle);
823
871
  server.watcher.on("add", handle);
824
872
  server.watcher.on("unlink", handle);
873
+ server.watcher.add(globBaseDirs([...toArray(options.input), ...options.prune ? toArray(options.usage) : []]));
825
874
  }
826
875
  },
827
876
  async buildStart() {
@@ -829,7 +878,7 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
829
878
  const scanned = await cachedScan;
830
879
  const names = await resolveNames(scanned);
831
880
  for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
832
- await (0, import_promises2.writeFile)(path, content, "utf8");
881
+ await writeOutput(path, content);
833
882
  }
834
883
  },
835
884
  resolveId(id) {
package/dist/rollup.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-32V3V6WT.js";
4
- import "./chunk-5HPTHW7S.js";
3
+ } from "./chunk-NZUQZYNM.js";
4
+ import "./chunk-XCAFJREQ.js";
5
5
 
6
6
  // src/rollup.ts
7
7
  var rollup_default = unplugin_default.rollup;