css-typed-vars 0.4.17 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,11 +30,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
+ checkGenerated: () => checkGenerated,
34
+ findUnusedVars: () => findUnusedVars,
33
35
  generate: () => generate,
34
36
  generateCode: () => generateCode,
35
37
  generateDeclaration: () => generateDeclaration,
36
38
  generateJs: () => generateJs,
39
+ parsePropertyRules: () => parsePropertyRules,
40
+ parseVarDeclarations: () => parseVarDeclarations,
37
41
  parseVarNames: () => parseVarNames,
42
+ scanCss: () => scanCss,
43
+ scanUsedKeys: () => scanUsedKeys,
44
+ scanVarDeclarations: () => scanVarDeclarations,
38
45
  scanVarNames: () => scanVarNames
39
46
  });
40
47
  module.exports = __toCommonJS(src_exports);
@@ -142,10 +149,28 @@ function maskQuotedContent(text) {
142
149
  }
143
150
  return result;
144
151
  }
145
- function parseVarNames(css, selectors) {
152
+ function extractValue(text, start) {
153
+ let i = start;
154
+ let quote = null;
155
+ for (; i < text.length; i++) {
156
+ const char = text[i];
157
+ if (quote) {
158
+ const step = stepQuote(text, i, quote);
159
+ if (step.closed) quote = null;
160
+ i += step.consumed - 1;
161
+ continue;
162
+ }
163
+ if (char === '"' || char === "'") {
164
+ quote = char;
165
+ continue;
166
+ }
167
+ if (char === ";" || char === "}") break;
168
+ }
169
+ return text.slice(start, i).trim();
170
+ }
171
+ function scanDeclarations(css, selectors, onProperty) {
146
172
  const stripped = stripComments(css);
147
- const names = /* @__PURE__ */ new Set();
148
- const allSelectors = [":root", ...selectors ?? []];
173
+ const allSelectors = [":root", "@theme", ...selectors ?? []];
149
174
  for (const sel of allSelectors) {
150
175
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151
176
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
@@ -153,53 +178,147 @@ function parseVarNames(css, selectors) {
153
178
  while (match = openRegex.exec(stripped)) {
154
179
  const start = match.index + match[0].length;
155
180
  const block = extractBlock(stripped, start);
156
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
157
- names.add(prop[0]);
181
+ const masked = maskQuotedContent(block);
182
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
183
+ const name = prop[0];
184
+ const colonIndex = block.indexOf(":", prop.index + name.length);
185
+ onProperty(name, extractValue(block, colonIndex + 1));
158
186
  }
159
187
  openRegex.lastIndex = start + block.length + 1;
160
188
  }
161
189
  }
190
+ }
191
+ function parseVarNames(css, selectors) {
192
+ const names = /* @__PURE__ */ new Set();
193
+ scanDeclarations(css, selectors, (name) => names.add(name));
162
194
  return [...names];
163
195
  }
196
+ function parseVarDeclarations(css, selectors) {
197
+ const declarations = /* @__PURE__ */ new Map();
198
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
199
+ return declarations;
200
+ }
201
+ var PROPERTY_DESCRIPTORS = [
202
+ ["syntax", "syntax"],
203
+ ["inherits", "inherits"],
204
+ ["initial-value", "initialValue"]
205
+ ];
206
+ function parsePropertyRules(css) {
207
+ const stripped = stripComments(css);
208
+ const rules = /* @__PURE__ */ new Map();
209
+ const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
210
+ let match;
211
+ while (match = openRegex.exec(stripped)) {
212
+ const name = match[1];
213
+ const start = match.index + match[0].length;
214
+ const block = extractBlock(stripped, start);
215
+ const masked = maskQuotedContent(block);
216
+ const rule = {};
217
+ for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
218
+ const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
219
+ const descMatch = descRegex.exec(masked);
220
+ if (!descMatch) continue;
221
+ const nameEnd = descMatch.index + descMatch[0].length;
222
+ const colonIndex = block.indexOf(":", nameEnd);
223
+ rule[key] = extractValue(block, colonIndex + 1);
224
+ }
225
+ if (Object.keys(rule).length > 0) rules.set(name, rule);
226
+ openRegex.lastIndex = start + block.length + 1;
227
+ }
228
+ return rules;
229
+ }
164
230
 
165
231
  // src/scanner.ts
166
- async function scanVarNames(patterns, exclude, selectors) {
167
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
168
- (p) => p.replace(/\\/g, "/")
169
- );
170
- const normalizedExclude = exclude ? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => p.replace(/\\/g, "/")) : [];
232
+ function normalizePatterns(patterns) {
233
+ return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
234
+ }
235
+ async function scanCss(patterns, exclude, selectors) {
236
+ const normalized = normalizePatterns(patterns);
237
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
171
238
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
172
- const all = /* @__PURE__ */ new Set();
173
- await Promise.all(
239
+ const perFile = await Promise.all(
174
240
  files.map(async (file) => {
175
241
  let css;
176
242
  try {
177
243
  css = await (0, import_promises.readFile)(file, "utf8");
178
244
  } catch (err) {
179
245
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
180
- return;
246
+ return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
181
247
  }
182
- for (const name of parseVarNames(css, selectors)) {
183
- all.add(name);
248
+ return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
249
+ })
250
+ );
251
+ const declarations = /* @__PURE__ */ new Map();
252
+ const properties = /* @__PURE__ */ new Map();
253
+ for (const result of perFile) {
254
+ for (const [name, value] of result.declarations) declarations.set(name, value);
255
+ for (const [name, rule] of result.properties) properties.set(name, rule);
256
+ }
257
+ return { declarations, properties };
258
+ }
259
+ async function scanVarDeclarations(patterns, exclude, selectors) {
260
+ return (await scanCss(patterns, exclude, selectors)).declarations;
261
+ }
262
+ async function scanVarNames(patterns, exclude, selectors) {
263
+ const declarations = await scanVarDeclarations(patterns, exclude, selectors);
264
+ return [...declarations.keys()].sort();
265
+ }
266
+ var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
267
+ function extractUsedKeys(text, into) {
268
+ for (const match of text.matchAll(USAGE_RE)) {
269
+ into.add(match[1] ?? match[3]);
270
+ }
271
+ }
272
+ async function scanUsedKeys(patterns, exclude) {
273
+ const normalized = normalizePatterns(patterns);
274
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
275
+ const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
276
+ const perFile = await Promise.all(
277
+ files.map(async (file) => {
278
+ const used = /* @__PURE__ */ new Set();
279
+ let text;
280
+ try {
281
+ text = await (0, import_promises.readFile)(file, "utf8");
282
+ } catch (err) {
283
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
284
+ return used;
184
285
  }
286
+ extractUsedKeys(text, used);
287
+ return used;
185
288
  })
186
289
  );
187
- return [...all].sort();
290
+ const all = /* @__PURE__ */ new Set();
291
+ for (const used of perFile) {
292
+ for (const key of used) all.add(key);
293
+ }
294
+ return all;
188
295
  }
189
296
 
190
297
  // src/generator.ts
191
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
298
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
192
299
  function convertCase(value, naming) {
193
300
  if (!VALID_NAMINGS.includes(naming)) {
194
301
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
195
302
  }
196
303
  if (naming === "kebab") return value;
197
- return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
304
+ if (naming === "snake") return value.replace(/-+/g, "_");
305
+ if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
306
+ if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
307
+ return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
198
308
  }
199
- function toKey(cssVarName, naming = "camelCase") {
200
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
309
+ function toKeyFragment(fragment, naming = "camelCase") {
310
+ const key = convertCase(fragment, naming);
201
311
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
202
312
  }
313
+ function toKey(cssVarName, naming = "camelCase") {
314
+ return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
315
+ }
316
+ function splitGroupKey(cssVarName) {
317
+ const stripped = cssVarName.replace(/^--/, "");
318
+ const dashIndex = stripped.indexOf("-");
319
+ if (dashIndex === -1) return null;
320
+ return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
321
+ }
203
322
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
204
323
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
205
324
  var SINGLE_QUOTE_ESCAPES = {};
@@ -225,13 +344,16 @@ function applyPrefix(key, prefix, naming = "camelCase") {
225
344
  }
226
345
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
227
346
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
228
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
347
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
229
348
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
230
349
  }
231
350
  function formatKey(key, naming = "camelCase") {
232
351
  if (naming === "kebab") return `'${key}'`;
233
352
  return key;
234
353
  }
354
+ function computeKey(cssVarName, prefix, naming) {
355
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
356
+ }
235
357
  function findKeyCollisions(varNames, prefix, naming) {
236
358
  const byKey = /* @__PURE__ */ new Map();
237
359
  for (const name of varNames) {
@@ -250,28 +372,126 @@ function warnOnCollisions(varNames, prefix, naming) {
250
372
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
251
373
  }
252
374
  }
253
- function buildEntries(varNames, prefix, naming) {
375
+ function buildEntries(varNames, prefix, naming, declarations, properties) {
254
376
  const byKey = /* @__PURE__ */ new Map();
255
377
  for (const name of varNames) {
256
378
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
257
- byKey.set(key, name);
379
+ byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
380
+ }
381
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
382
+ }
383
+ function buildGroupedEntries(varNames, naming, declarations, properties) {
384
+ const groupMap = /* @__PURE__ */ new Map();
385
+ const ungroupedMap = /* @__PURE__ */ new Map();
386
+ for (const name of varNames) {
387
+ const value = declarations?.get(name);
388
+ const syntax = properties?.get(name)?.syntax;
389
+ const split = splitGroupKey(name);
390
+ if (!split) {
391
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
392
+ continue;
393
+ }
394
+ const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
395
+ const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
396
+ let leafMap = groupMap.get(groupKey);
397
+ if (!leafMap) {
398
+ leafMap = /* @__PURE__ */ new Map();
399
+ groupMap.set(groupKey, leafMap);
400
+ }
401
+ leafMap.set(leafKey, { name, value, syntax });
402
+ }
403
+ for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
404
+ const groups = [...groupMap].map(([key, leafMap]) => ({
405
+ key,
406
+ entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
407
+ }));
408
+ const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
409
+ return { groups, ungrouped };
410
+ }
411
+ function formatDefaultComment(value, indent = " ") {
412
+ return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
413
+ }
414
+ function unquoteCssString(value) {
415
+ const quote = value[0];
416
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
417
+ return value.slice(1, -1);
418
+ }
419
+ return value;
420
+ }
421
+ function formatSyntaxComment(syntax, indent = " ") {
422
+ return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
423
+ }
424
+ var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
425
+ function parseEnumSyntax(syntax) {
426
+ const unquoted = unquoteCssString(syntax).trim();
427
+ if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
428
+ return unquoted.split("|").map((v) => v.trim());
429
+ }
430
+ function syntaxTypeName(cssVarName) {
431
+ const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
432
+ return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
433
+ }
434
+ function buildSyntaxTypes(varNames, properties) {
435
+ if (!properties) return [];
436
+ const byName = /* @__PURE__ */ new Map();
437
+ for (const name of varNames) {
438
+ const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
439
+ if (values) byName.set(syntaxTypeName(name), values);
258
440
  }
259
- return [...byKey].map(([key, name]) => ({ key, name }));
441
+ return [...byName].map(([name, values]) => ({ name, values }));
260
442
  }
261
- function generateCode(varNames, prefix, naming) {
262
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
443
+ function renderSyntaxTypeLines(types) {
444
+ return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
445
+ }
446
+ function buildTailBlocks(varNames, group, properties) {
447
+ const blocks = [];
448
+ if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
449
+ const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
450
+ if (syntaxLines.length > 0) blocks.push(syntaxLines);
451
+ return blocks;
452
+ }
453
+ function renderEntryLines(entries, indent, lineFor) {
454
+ return entries.flatMap(({ key, name, value, syntax }) => [
455
+ ...value ? [formatDefaultComment(value, indent)] : [],
456
+ ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
457
+ `${indent}${lineFor(key, name)}`
458
+ ]);
459
+ }
460
+ function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
461
+ const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
462
+ const lines = [];
463
+ for (const group of groups) {
464
+ lines.push(`${indent}${group.key}: {`);
465
+ lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
466
+ lines.push(`${indent}}${closeSuffix}`);
467
+ }
468
+ lines.push(...renderEntryLines(ungrouped, indent, lineFor));
469
+ return lines;
470
+ }
471
+ function assertGroupPrefixCompatible(prefix, group) {
472
+ if (group && prefix) {
473
+ throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
474
+ }
475
+ }
476
+ var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
477
+ var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
478
+ function generateCode(varNames, prefix, naming, declarations, group, properties) {
479
+ assertGroupPrefixCompatible(prefix, group);
480
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
481
+ const blocks = buildTailBlocks(varNames, group, properties);
482
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
263
483
  return [
264
484
  "// generated \u2014 do not edit",
265
485
  "export const cssVars = {",
266
486
  ...entries,
267
487
  "} as const;",
268
- "",
269
- "export type CssVarName = keyof typeof cssVars;",
488
+ ...tailBody.length > 0 ? ["", ...tailBody] : [],
270
489
  ""
271
490
  ].join("\n");
272
491
  }
273
- function generateJs(varNames, prefix, naming) {
274
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
492
+ function generateJs(varNames, prefix, naming, declarations, group, properties) {
493
+ assertGroupPrefixCompatible(prefix, group);
494
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
275
495
  return [
276
496
  "// generated \u2014 do not edit",
277
497
  "export const cssVars = {",
@@ -280,41 +500,100 @@ function generateJs(varNames, prefix, naming) {
280
500
  ""
281
501
  ].join("\n");
282
502
  }
283
- function generateDeclaration(varNames, prefix, naming) {
284
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
503
+ function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
504
+ assertGroupPrefixCompatible(prefix, group);
505
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
506
+ const blocks = buildTailBlocks(varNames, group, properties);
507
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
285
508
  return [
286
509
  "export declare const cssVars: {",
287
510
  ...entries,
288
511
  "};",
289
- "export type CssVarName = keyof typeof cssVars;",
512
+ ...tailBody,
290
513
  ""
291
514
  ].join("\n");
292
515
  }
293
516
 
294
517
  // src/index.ts
295
- async function generate(options) {
296
- const names = await scanVarNames(options.input, options.exclude, options.selectors);
518
+ function assertPruneCompatible(options) {
519
+ if (!options.prune) return;
520
+ if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
521
+ if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
522
+ }
523
+ function partitionUnused(names, usedKeys, prefix, naming) {
524
+ const used = [];
525
+ const unused = [];
526
+ for (const name of names) {
527
+ (usedKeys.has(computeKey(name, prefix, naming)) ? used : unused).push(name);
528
+ }
529
+ return { used, unused };
530
+ }
531
+ async function findUnusedVars(options) {
532
+ if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
533
+ const [declarations, usedKeys] = await Promise.all([
534
+ scanVarDeclarations(options.input, options.exclude, options.selectors),
535
+ scanUsedKeys(options.usage, options.usageExclude)
536
+ ]);
537
+ const names = [...declarations.keys()].sort();
538
+ return partitionUnused(names, usedKeys, options.prefix, options.naming).unused;
539
+ }
540
+ async function computeOutputs(options) {
541
+ assertPruneCompatible(options);
542
+ const { declarations, properties } = await scanCss(options.input, options.exclude, options.selectors);
543
+ let names = [...declarations.keys()].sort();
297
544
  if (names.length === 0) {
298
545
  console.warn("css-typed-vars: no CSS custom properties found.");
299
546
  }
300
547
  warnOnCollisions(names, options.prefix, options.naming);
548
+ if (options.prune) {
549
+ const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
550
+ const { used, unused } = partitionUnused(names, usedKeys, options.prefix, options.naming);
551
+ if (unused.length > 0) {
552
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
553
+ }
554
+ names = used;
555
+ }
301
556
  const outPath = (0, import_node_path.resolve)(options.output);
302
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
303
557
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
304
558
  if (jsExtMatch) {
305
- await (0, import_promises2.writeFile)(outPath, generateJs(names, options.prefix, options.naming), "utf8");
559
+ const content = generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
306
560
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
307
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
308
- } else {
309
- await (0, import_promises2.writeFile)(outPath, generateCode(names, options.prefix, options.naming), "utf8");
561
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
562
+ return { outPath, content, dtsPath, dtsContent };
563
+ }
564
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations, options.group, properties) };
565
+ }
566
+ async function generate(options) {
567
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
568
+ await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
569
+ await (0, import_promises2.writeFile)(outPath, content, "utf8");
570
+ if (dtsPath && dtsContent !== void 0) {
571
+ await (0, import_promises2.writeFile)(dtsPath, dtsContent, "utf8");
572
+ }
573
+ }
574
+ async function checkGenerated(options) {
575
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
576
+ const current = await (0, import_promises2.readFile)(outPath, "utf8").catch(() => null);
577
+ if (current !== content) return false;
578
+ if (dtsPath && dtsContent !== void 0) {
579
+ const currentDts = await (0, import_promises2.readFile)(dtsPath, "utf8").catch(() => null);
580
+ if (currentDts !== dtsContent) return false;
310
581
  }
582
+ return true;
311
583
  }
312
584
  // Annotate the CommonJS export names for ESM import in node:
313
585
  0 && (module.exports = {
586
+ checkGenerated,
587
+ findUnusedVars,
314
588
  generate,
315
589
  generateCode,
316
590
  generateDeclaration,
317
591
  generateJs,
592
+ parsePropertyRules,
593
+ parseVarDeclarations,
318
594
  parseVarNames,
595
+ scanCss,
596
+ scanUsedKeys,
597
+ scanVarDeclarations,
319
598
  scanVarNames
320
599
  });
package/dist/index.d.cts CHANGED
@@ -1,9 +1,14 @@
1
- import { N as NamingConvention } from './generator-Ba8XeISD.cjs';
2
- export { g as generateCode, a as generateDeclaration, b as generateJs } from './generator-Ba8XeISD.cjs';
3
-
4
- declare function parseVarNames(css: string, selectors?: string[]): string[];
1
+ import { P as PropertyRule, N as NamingConvention } from './generator-C2AppeJL.cjs';
2
+ export { g as generateCode, a as generateDeclaration, b as generateJs, p as parsePropertyRules, c as parseVarDeclarations, d as parseVarNames } from './generator-C2AppeJL.cjs';
5
3
 
4
+ interface ScannedCss {
5
+ declarations: Map<string, string>;
6
+ properties: Map<string, PropertyRule>;
7
+ }
8
+ declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<ScannedCss>;
9
+ declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
6
10
  declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
11
+ declare function scanUsedKeys(patterns: string | string[], exclude?: string | string[]): Promise<Set<string>>;
7
12
 
8
13
  interface GenerateOptions {
9
14
  input: string | string[];
@@ -12,7 +17,15 @@ interface GenerateOptions {
12
17
  prefix?: string;
13
18
  naming?: NamingConvention;
14
19
  selectors?: string[];
20
+ group?: boolean;
21
+ /** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage`, and can't be combined with `group`. */
22
+ prune?: boolean;
23
+ /** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true, or when calling `findUnusedVars`. */
24
+ usage?: string | string[];
25
+ usageExclude?: string | string[];
15
26
  }
27
+ declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'prefix' | 'naming' | 'usage' | 'usageExclude'>): Promise<string[]>;
16
28
  declare function generate(options: GenerateOptions): Promise<void>;
29
+ declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
17
30
 
18
- export { type GenerateOptions, NamingConvention, generate, parseVarNames, scanVarNames };
31
+ export { type GenerateOptions, NamingConvention, PropertyRule, checkGenerated, findUnusedVars, generate, scanCss, scanUsedKeys, scanVarDeclarations, scanVarNames };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,14 @@
1
- import { N as NamingConvention } from './generator-Ba8XeISD.js';
2
- export { g as generateCode, a as generateDeclaration, b as generateJs } from './generator-Ba8XeISD.js';
3
-
4
- declare function parseVarNames(css: string, selectors?: string[]): string[];
1
+ import { P as PropertyRule, N as NamingConvention } from './generator-C2AppeJL.js';
2
+ export { g as generateCode, a as generateDeclaration, b as generateJs, p as parsePropertyRules, c as parseVarDeclarations, d as parseVarNames } from './generator-C2AppeJL.js';
5
3
 
4
+ interface ScannedCss {
5
+ declarations: Map<string, string>;
6
+ properties: Map<string, PropertyRule>;
7
+ }
8
+ declare function scanCss(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<ScannedCss>;
9
+ declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
6
10
  declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
11
+ declare function scanUsedKeys(patterns: string | string[], exclude?: string | string[]): Promise<Set<string>>;
7
12
 
8
13
  interface GenerateOptions {
9
14
  input: string | string[];
@@ -12,7 +17,15 @@ interface GenerateOptions {
12
17
  prefix?: string;
13
18
  naming?: NamingConvention;
14
19
  selectors?: string[];
20
+ group?: boolean;
21
+ /** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage`, and can't be combined with `group`. */
22
+ prune?: boolean;
23
+ /** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true, or when calling `findUnusedVars`. */
24
+ usage?: string | string[];
25
+ usageExclude?: string | string[];
15
26
  }
27
+ declare function findUnusedVars(options: Pick<GenerateOptions, 'input' | 'exclude' | 'selectors' | 'prefix' | 'naming' | 'usage' | 'usageExclude'>): Promise<string[]>;
16
28
  declare function generate(options: GenerateOptions): Promise<void>;
29
+ declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
17
30
 
18
- export { type GenerateOptions, NamingConvention, generate, parseVarNames, scanVarNames };
31
+ export { type GenerateOptions, NamingConvention, PropertyRule, checkGenerated, findUnusedVars, generate, scanCss, scanUsedKeys, scanVarDeclarations, scanVarNames };
package/dist/index.js CHANGED
@@ -1,18 +1,32 @@
1
1
  import {
2
+ checkGenerated,
3
+ findUnusedVars,
2
4
  generate
3
- } from "./chunk-EHRNYU34.js";
5
+ } from "./chunk-VZ2BHHXD.js";
4
6
  import {
5
7
  generateCode,
6
8
  generateDeclaration,
7
9
  generateJs,
10
+ parsePropertyRules,
11
+ parseVarDeclarations,
8
12
  parseVarNames,
13
+ scanCss,
14
+ scanUsedKeys,
15
+ scanVarDeclarations,
9
16
  scanVarNames
10
- } from "./chunk-WYLYZXQJ.js";
17
+ } from "./chunk-LH53WYFF.js";
11
18
  export {
19
+ checkGenerated,
20
+ findUnusedVars,
12
21
  generate,
13
22
  generateCode,
14
23
  generateDeclaration,
15
24
  generateJs,
25
+ parsePropertyRules,
26
+ parseVarDeclarations,
16
27
  parseVarNames,
28
+ scanCss,
29
+ scanUsedKeys,
30
+ scanVarDeclarations,
17
31
  scanVarNames
18
32
  };