css-typed-vars 0.5.0 → 0.7.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/webpack.cjs CHANGED
@@ -159,37 +159,119 @@ function extractValue(text, start) {
159
159
  }
160
160
  return text.slice(start, i).trim();
161
161
  }
162
- function scanDeclarations(css, selectors, onProperty) {
163
- const stripped = stripComments(css);
164
- const allSelectors = [":root", ...selectors ?? []];
165
- for (const sel of allSelectors) {
162
+ function forEachProperty(block, onProperty) {
163
+ const masked = maskQuotedContent(block);
164
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
165
+ const name = prop[0];
166
+ const colonIndex = block.indexOf(":", prop.index + name.length);
167
+ onProperty(name, extractValue(block, colonIndex + 1));
168
+ }
169
+ }
170
+ function forEachSelectorBlock(stripped, selectors, onBlock) {
171
+ for (const sel of selectors) {
166
172
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
167
173
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
168
174
  let match;
169
175
  while (match = openRegex.exec(stripped)) {
170
176
  const start = match.index + match[0].length;
171
177
  const block = extractBlock(stripped, start);
172
- const masked = maskQuotedContent(block);
173
- for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
174
- const name = prop[0];
175
- const colonIndex = block.indexOf(":", prop.index + name.length);
176
- onProperty(name, extractValue(block, colonIndex + 1));
177
- }
178
- openRegex.lastIndex = start + block.length + 1;
178
+ const end = start + block.length + 1;
179
+ onBlock(block, [start, end]);
180
+ openRegex.lastIndex = end;
179
181
  }
180
182
  }
181
183
  }
182
- function parseVarDeclarations(css, selectors) {
184
+ var BASE_SELECTORS = [":root", "@theme"];
185
+ function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
186
+ forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
187
+ if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
188
+ forEachProperty(block, onProperty);
189
+ });
190
+ }
191
+ var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
192
+ function forEachMediaBlock(stripped, media, onBlock) {
193
+ const wanted = normalizePrelude(media.replace(/^@media/i, ""));
194
+ const openRegex = /@media([^{;]*)\{/gi;
195
+ let match;
196
+ while (match = openRegex.exec(stripped)) {
197
+ const start = match.index + match[0].length;
198
+ const block = extractBlock(stripped, start);
199
+ const end = start + block.length + 1;
200
+ if (normalizePrelude(match[1]) === wanted) {
201
+ onBlock(block, [start, end]);
202
+ openRegex.lastIndex = end;
203
+ } else {
204
+ openRegex.lastIndex = start;
205
+ }
206
+ }
207
+ }
208
+ function parseThemedDeclarations(css, selectors, themes) {
209
+ const stripped = stripComments(css);
210
+ const themeValues = /* @__PURE__ */ new Map();
211
+ const skip = [];
212
+ for (const [themeName, themeSelector] of Object.entries(themes)) {
213
+ const values = /* @__PURE__ */ new Map();
214
+ themeValues.set(themeName, values);
215
+ const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
216
+ const selector = themeSelector.trim();
217
+ if (/^@media\b/i.test(selector)) {
218
+ forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
219
+ skip.push(range);
220
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
221
+ });
222
+ } else {
223
+ forEachSelectorBlock(stripped, [selector], (block, range) => {
224
+ skip.push(range);
225
+ collect(block);
226
+ });
227
+ }
228
+ }
183
229
  const declarations = /* @__PURE__ */ new Map();
184
- scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
185
- return declarations;
230
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
231
+ return { declarations, themes: themeValues };
232
+ }
233
+ var PROPERTY_DESCRIPTORS = [
234
+ ["syntax", "syntax"],
235
+ ["inherits", "inherits"],
236
+ ["initial-value", "initialValue"]
237
+ ];
238
+ function parsePropertyRules(css) {
239
+ const stripped = stripComments(css);
240
+ const rules = /* @__PURE__ */ new Map();
241
+ const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
242
+ let match;
243
+ while (match = openRegex.exec(stripped)) {
244
+ const name = match[1];
245
+ const start = match.index + match[0].length;
246
+ const block = extractBlock(stripped, start);
247
+ const masked = maskQuotedContent(block);
248
+ const rule = {};
249
+ for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
250
+ const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
251
+ const descMatch = descRegex.exec(masked);
252
+ if (!descMatch) continue;
253
+ const nameEnd = descMatch.index + descMatch[0].length;
254
+ const colonIndex = block.indexOf(":", nameEnd);
255
+ rule[key] = extractValue(block, colonIndex + 1);
256
+ }
257
+ if (Object.keys(rule).length > 0) rules.set(name, rule);
258
+ openRegex.lastIndex = start + block.length + 1;
259
+ }
260
+ return rules;
186
261
  }
187
262
 
188
263
  // src/scanner.ts
189
264
  function normalizePatterns(patterns) {
190
265
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
191
266
  }
192
- async function scanVarDeclarations(patterns, exclude, selectors) {
267
+ function collectVarNames(scanned) {
268
+ const names = new Set(scanned.declarations.keys());
269
+ for (const values of scanned.themes.values()) {
270
+ for (const name of values.keys()) names.add(name);
271
+ }
272
+ return [...names].sort();
273
+ }
274
+ async function scanCss(patterns, exclude, selectors, themes = {}) {
193
275
  const normalized = normalizePatterns(patterns);
194
276
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
195
277
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -200,18 +282,58 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
200
282
  css = await (0, import_promises.readFile)(file, "utf8");
201
283
  } catch (err) {
202
284
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
203
- return /* @__PURE__ */ new Map();
285
+ return null;
204
286
  }
205
- return parseVarDeclarations(css, selectors);
287
+ return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
206
288
  })
207
289
  );
208
- const all = /* @__PURE__ */ new Map();
209
- for (const declarations of perFile) {
210
- for (const [name, value] of declarations) {
211
- all.set(name, value);
290
+ const declarations = /* @__PURE__ */ new Map();
291
+ const properties = /* @__PURE__ */ new Map();
292
+ const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
293
+ for (const result of perFile) {
294
+ if (!result) continue;
295
+ for (const [name, value] of result.declarations) declarations.set(name, value);
296
+ for (const [name, rule] of result.properties) properties.set(name, rule);
297
+ for (const [theme, values] of result.themes) {
298
+ for (const [name, value] of values) themeValues.get(theme).set(name, value);
212
299
  }
213
300
  }
214
- return all;
301
+ return { declarations, properties, themes: themeValues };
302
+ }
303
+ var ROOT_RE = /\bcssVars\b/g;
304
+ var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
305
+ function readAccess(text, from) {
306
+ ACCESS_RE.lastIndex = from;
307
+ const match = ACCESS_RE.exec(text);
308
+ return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
309
+ }
310
+ function extractUsage(text, into) {
311
+ for (const root of text.matchAll(ROOT_RE)) {
312
+ const first = readAccess(text, root.index + root[0].length);
313
+ if (!first) continue;
314
+ into.keys.add(first.key);
315
+ const second = readAccess(text, first.end);
316
+ if (second) into.paths.add(`${first.key}\0${second.key}`);
317
+ else into.wholeKeys.add(first.key);
318
+ }
319
+ }
320
+ async function scanUsage(patterns, exclude) {
321
+ const normalized = normalizePatterns(patterns);
322
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
323
+ const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
324
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
325
+ const texts = await Promise.all(
326
+ files.map(async (file) => {
327
+ try {
328
+ return await (0, import_promises.readFile)(file, "utf8");
329
+ } catch (err) {
330
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
331
+ return "";
332
+ }
333
+ })
334
+ );
335
+ for (const text of texts) extractUsage(text, usage);
336
+ return usage;
215
337
  }
216
338
 
217
339
  // src/generator.ts
@@ -226,10 +348,19 @@ function convertCase(value, naming) {
226
348
  if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
227
349
  return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
228
350
  }
229
- function toKey(cssVarName, naming = "camelCase") {
230
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
351
+ function toKeyFragment(fragment, naming = "camelCase") {
352
+ const key = convertCase(fragment, naming);
231
353
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
232
354
  }
355
+ function toKey(cssVarName, naming = "camelCase") {
356
+ return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
357
+ }
358
+ function splitGroupKey(cssVarName) {
359
+ const stripped = cssVarName.replace(/^--/, "");
360
+ const dashIndex = stripped.indexOf("-");
361
+ if (dashIndex === -1) return null;
362
+ return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
363
+ }
233
364
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
234
365
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
235
366
  var SINGLE_QUOTE_ESCAPES = {};
@@ -262,6 +393,15 @@ function formatKey(key, naming = "camelCase") {
262
393
  if (naming === "kebab") return `'${key}'`;
263
394
  return key;
264
395
  }
396
+ function computeKey(cssVarName, prefix, naming) {
397
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
398
+ }
399
+ function computeKeyPath(cssVarName, prefix, naming, group) {
400
+ if (!group) return [computeKey(cssVarName, prefix, naming)];
401
+ const split = splitGroupKey(cssVarName);
402
+ if (!split) return [toKey(cssVarName, naming)];
403
+ return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
404
+ }
265
405
  function findKeyCollisions(varNames, prefix, naming) {
266
406
  const byKey = /* @__PURE__ */ new Map();
267
407
  for (const name of varNames) {
@@ -280,43 +420,245 @@ function warnOnCollisions(varNames, prefix, naming) {
280
420
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
281
421
  }
282
422
  }
283
- function buildEntries(varNames, prefix, naming, declarations) {
423
+ function entryMeta(name, options) {
424
+ const themes = [];
425
+ for (const [theme, values] of options.themes ?? []) {
426
+ const value = values.get(name);
427
+ if (value !== void 0) themes.push([theme, value]);
428
+ }
429
+ return {
430
+ name,
431
+ value: options.declarations?.get(name),
432
+ syntax: options.properties?.get(name)?.syntax,
433
+ ...themes.length > 0 ? { themes } : {}
434
+ };
435
+ }
436
+ function buildEntries(varNames, options) {
437
+ const { prefix, naming } = options;
284
438
  const byKey = /* @__PURE__ */ new Map();
285
439
  for (const name of varNames) {
286
440
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
287
- byKey.set(key, { name, value: declarations?.get(name) });
441
+ byKey.set(key, entryMeta(name, options));
288
442
  }
289
443
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
290
444
  }
291
- function formatDefaultComment(value) {
292
- return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
445
+ function buildGroupedEntries(varNames, options) {
446
+ const { naming } = options;
447
+ const groupMap = /* @__PURE__ */ new Map();
448
+ const ungroupedMap = /* @__PURE__ */ new Map();
449
+ for (const name of varNames) {
450
+ const meta = entryMeta(name, options);
451
+ const split = splitGroupKey(name);
452
+ if (!split) {
453
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
454
+ continue;
455
+ }
456
+ const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
457
+ const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
458
+ let leafMap = groupMap.get(groupKey);
459
+ if (!leafMap) {
460
+ leafMap = /* @__PURE__ */ new Map();
461
+ groupMap.set(groupKey, leafMap);
462
+ }
463
+ leafMap.set(leafKey, meta);
464
+ }
465
+ for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
466
+ const groups = [...groupMap].map(([key, leafMap]) => ({
467
+ key,
468
+ entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
469
+ }));
470
+ const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
471
+ return { groups, ungrouped };
472
+ }
473
+ function formatDefaultComment(value, indent = " ") {
474
+ return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
475
+ }
476
+ function unquoteCssString(value) {
477
+ const quote = value[0];
478
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
479
+ return value.slice(1, -1);
480
+ }
481
+ return value;
482
+ }
483
+ function formatSyntaxComment(syntax, indent = " ") {
484
+ return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
485
+ }
486
+ function formatThemeComment(theme, value, indent = " ") {
487
+ return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
488
+ }
489
+ var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
490
+ function parseEnumSyntax(syntax) {
491
+ const unquoted = unquoteCssString(syntax).trim();
492
+ if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
493
+ return unquoted.split("|").map((v) => v.trim());
494
+ }
495
+ function syntaxTypeName(cssVarName) {
496
+ const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
497
+ return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
498
+ }
499
+ function buildSyntaxTypes(varNames, properties) {
500
+ if (!properties) return [];
501
+ const byName = /* @__PURE__ */ new Map();
502
+ for (const name of varNames) {
503
+ const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
504
+ if (values) byName.set(syntaxTypeName(name), values);
505
+ }
506
+ return [...byName].map(([name, values]) => ({ name, values }));
507
+ }
508
+ function renderSyntaxTypeLines(types) {
509
+ return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
293
510
  }
294
- function generateJs(varNames, prefix, naming, declarations) {
295
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
296
- ...value ? [formatDefaultComment(value)] : [],
297
- ` ${key}: 'var(${name})',`
511
+ function buildTailBlocks(varNames, group, properties) {
512
+ const blocks = [];
513
+ if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
514
+ const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
515
+ if (syntaxLines.length > 0) blocks.push(syntaxLines);
516
+ return blocks;
517
+ }
518
+ function renderEntryLines(entries, indent, lineFor) {
519
+ return entries.flatMap(({ key, name, value, syntax, themes }) => [
520
+ ...value ? [formatDefaultComment(value, indent)] : [],
521
+ ...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
522
+ ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
523
+ `${indent}${lineFor(key, name)}`
298
524
  ]);
525
+ }
526
+ function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
527
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
528
+ const lines = [];
529
+ for (const group of groups) {
530
+ lines.push(`${indent}${group.key}: {`);
531
+ lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
532
+ lines.push(`${indent}}${closeSuffix}`);
533
+ }
534
+ lines.push(...renderEntryLines(ungrouped, indent, lineFor));
535
+ return lines;
536
+ }
537
+ function assertGroupPrefixCompatible(prefix, group) {
538
+ if (group && prefix) {
539
+ throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
540
+ }
541
+ }
542
+ var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
543
+ var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
544
+ function normalizeOptions(args) {
545
+ const [first] = args;
546
+ if (first !== null && typeof first === "object") return first;
547
+ const [prefix, naming, declarations, group, properties] = args;
548
+ return { prefix, naming, declarations, group, properties };
549
+ }
550
+ function renderEntries(varNames, options, closeSuffix, lineFor) {
551
+ assertGroupPrefixCompatible(options.prefix, options.group);
552
+ return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
553
+ }
554
+ function emittedNames(varNames, options) {
555
+ if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
556
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
557
+ return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
558
+ }
559
+ function renderRefType(varNames, options) {
560
+ const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
561
+ return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
562
+ }
563
+ var HELPERS_JS = [
564
+ "export function getCssVar(ref, el = document.documentElement) {",
565
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
566
+ "}",
567
+ "",
568
+ "export function setCssVar(ref, value, el = document.documentElement) {",
569
+ " el.style.setProperty(ref.slice(4, -1), value);",
570
+ "}"
571
+ ];
572
+ var HELPERS_DTS = [
573
+ "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
574
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
575
+ ];
576
+ function generateJs(varNames, ...args) {
577
+ const options = normalizeOptions(args);
578
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
299
579
  return [
300
580
  "// generated \u2014 do not edit",
301
581
  "export const cssVars = {",
302
582
  ...entries,
303
583
  "};",
584
+ ...options.helpers ? ["", ...HELPERS_JS] : [],
304
585
  ""
305
586
  ].join("\n");
306
587
  }
307
- function generateDeclaration(varNames, prefix, naming, declarations) {
308
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
309
- ...value ? [formatDefaultComment(value)] : [],
310
- ` ${key}: 'var(${name})';`
311
- ]);
588
+ function generateDeclaration(varNames, ...args) {
589
+ const options = normalizeOptions(args);
590
+ const entries = renderEntries(varNames, options, ";", declarationLineFor);
591
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
592
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
593
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
312
594
  return [
313
595
  "export declare const cssVars: {",
314
596
  ...entries,
315
597
  "};",
316
- "export type CssVarName = keyof typeof cssVars;",
598
+ ...tailBody,
317
599
  ""
318
600
  ].join("\n");
319
601
  }
602
+ var TOKEN_TYPES = {
603
+ "<color>": "color",
604
+ "<length>": "dimension",
605
+ "<length-percentage>": "dimension",
606
+ "<number>": "number",
607
+ "<integer>": "number",
608
+ "<time>": "duration"
609
+ };
610
+ var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
611
+ function generateTokens(varNames, options = {}) {
612
+ assertGroupPrefixCompatible(options.prefix, options.group);
613
+ const tokens = emittedNames(varNames, options).flatMap((name) => {
614
+ const meta = entryMeta(name, options);
615
+ const value = meta.value ?? options.properties?.get(name)?.initialValue;
616
+ return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
617
+ });
618
+ const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
619
+ const resolve2 = (value) => {
620
+ const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
621
+ return target ? `{${target.join(".")}}` : value;
622
+ };
623
+ const root = {};
624
+ for (const { meta, value, path } of tokens) {
625
+ const token = { $value: resolve2(value) };
626
+ const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
627
+ if (type) token.$type = type;
628
+ if (meta.themes) {
629
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
630
+ token.$extensions = { "css-typed-vars": { themes } };
631
+ }
632
+ const [key, leaf] = path;
633
+ if (leaf === void 0) {
634
+ root[key] = token;
635
+ } else {
636
+ const group = root[key] ?? (root[key] = {});
637
+ group[leaf] = token;
638
+ }
639
+ }
640
+ return JSON.stringify(root, null, 2) + "\n";
641
+ }
642
+
643
+ // src/prune.ts
644
+ function assertPruneCompatible(options) {
645
+ if (options.prune && !options.usage) {
646
+ throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
647
+ }
648
+ }
649
+ function isUsed(name, usage, options) {
650
+ const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
651
+ if (leaf === void 0) return usage.keys.has(key);
652
+ return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
653
+ }
654
+ function partitionUnused(names, usage, options) {
655
+ const used = [];
656
+ const unused = [];
657
+ for (const name of names) {
658
+ (isUsed(name, usage, options) ? used : unused).push(name);
659
+ }
660
+ return { used, unused };
661
+ }
320
662
 
321
663
  // src/unplugin.ts
322
664
  var VIRTUAL_ID = "css-typed-vars/vars";
@@ -325,9 +667,40 @@ function getDtsPath(options) {
325
667
  if (options.dts === false) return null;
326
668
  return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
327
669
  }
670
+ function outputFiles(options, names, generatorOptions) {
671
+ const files = [];
672
+ const dtsPath = getDtsPath(options);
673
+ if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
674
+ if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
675
+ return files;
676
+ }
328
677
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
329
- let cachedDeclarations = null;
330
- const scan = () => scanVarDeclarations(options.input, options.exclude, options.selectors);
678
+ assertPruneCompatible(options);
679
+ let cachedScan = null;
680
+ const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
681
+ const applyPrune = async (names) => {
682
+ if (!options.prune) return names;
683
+ const usage = await scanUsage(options.usage, options.usageExclude);
684
+ const { used, unused } = partitionUnused(names, usage, options);
685
+ if (unused.length > 0) {
686
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
687
+ }
688
+ return used;
689
+ };
690
+ const generatorOptions = ({ declarations, properties, themes }) => ({
691
+ prefix: options.prefix,
692
+ naming: options.naming,
693
+ declarations,
694
+ group: options.group,
695
+ properties,
696
+ helpers: options.helpers,
697
+ themes
698
+ });
699
+ const resolveNames = async (scanned) => {
700
+ const names = collectVarNames(scanned);
701
+ warnOnCollisions(names, options.prefix, options.naming);
702
+ return applyPrune(names);
703
+ };
331
704
  return {
332
705
  name: "css-typed-vars",
333
706
  vite: {
@@ -338,18 +711,19 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
338
711
  let writeQueue = Promise.resolve();
339
712
  const rescan = async () => {
340
713
  const myGeneration = ++generation;
341
- const declarationsPromise = scan();
342
- cachedDeclarations = declarationsPromise;
343
- const declarations = await declarationsPromise;
714
+ const scanPromise = scan();
715
+ cachedScan = scanPromise;
716
+ const scanned = await scanPromise;
344
717
  if (myGeneration !== generation) return;
345
- const names = [...declarations.keys()].sort();
346
- warnOnCollisions(names, options.prefix, options.naming);
347
- const dtsPath = getDtsPath(options);
348
- if (dtsPath) {
349
- const content = generateDeclaration(names, options.prefix, options.naming, declarations);
718
+ const names = await resolveNames(scanned);
719
+ if (myGeneration !== generation) return;
720
+ const files = outputFiles(options, names, generatorOptions(scanned));
721
+ if (files.length > 0) {
350
722
  writeQueue = writeQueue.then(async () => {
351
- if (myGeneration !== generation) return;
352
- await (0, import_promises2.writeFile)(dtsPath, content, "utf8");
723
+ for (const [path, content] of files) {
724
+ if (myGeneration !== generation) return;
725
+ await (0, import_promises2.writeFile)(path, content, "utf8");
726
+ }
353
727
  }).catch(console.error);
354
728
  await writeQueue;
355
729
  }
@@ -374,22 +748,21 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
374
748
  }
375
749
  },
376
750
  async buildStart() {
377
- cachedDeclarations = scan();
378
- const declarations = await cachedDeclarations;
379
- const names = [...declarations.keys()].sort();
380
- warnOnCollisions(names, options.prefix, options.naming);
381
- const dtsPath = getDtsPath(options);
382
- if (!dtsPath) return;
383
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations), "utf8");
751
+ cachedScan = scan();
752
+ const scanned = await cachedScan;
753
+ const names = await resolveNames(scanned);
754
+ for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
755
+ await (0, import_promises2.writeFile)(path, content, "utf8");
756
+ }
384
757
  },
385
758
  resolveId(id) {
386
759
  if (id === VIRTUAL_ID) return RESOLVED_ID;
387
760
  },
388
761
  async load(id) {
389
762
  if (id === RESOLVED_ID) {
390
- const declarations = await (cachedDeclarations ?? scan());
391
- const names = [...declarations.keys()].sort();
392
- return generateJs(names, options.prefix, options.naming, declarations);
763
+ const scanned = await (cachedScan ?? scan());
764
+ const names = await applyPrune(collectVarNames(scanned));
765
+ return generateJs(names, generatorOptions(scanned));
393
766
  }
394
767
  }
395
768
  };
@@ -1,6 +1,6 @@
1
1
  import { Options } from './unplugin.cjs';
2
2
  import 'unplugin';
3
- import './generator-t6h8Ic7V.cjs';
3
+ import './generator-C1iVNsry.cjs';
4
4
 
5
5
  declare const _default: (options: Options) => WebpackPluginInstance;
6
6
 
package/dist/webpack.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Options } from './unplugin.js';
2
2
  import 'unplugin';
3
- import './generator-t6h8Ic7V.js';
3
+ import './generator-C1iVNsry.js';
4
4
 
5
5
  declare const _default: (options: Options) => WebpackPluginInstance;
6
6
 
package/dist/webpack.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-YBZGHG2G.js";
4
- import "./chunk-JDZAH2YQ.js";
3
+ } from "./chunk-HBUSLYYB.js";
4
+ import "./chunk-6YWE4A6S.js";
5
5
 
6
6
  // src/webpack.ts
7
7
  var webpack_default = unplugin_default.webpack;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "css-typed-vars",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Generate TypeScript typed constants from CSS custom properties",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -62,7 +62,10 @@
62
62
  "scripts": {
63
63
  "build": "tsup && node scripts/postbuild.mjs",
64
64
  "test": "vitest run --passWithNoTests",
65
- "typecheck": "tsc --noEmit"
65
+ "typecheck": "tsc --noEmit",
66
+ "docs:dev": "vitepress dev docs",
67
+ "docs:build": "vitepress build docs",
68
+ "docs:preview": "vitepress preview docs"
66
69
  },
67
70
  "dependencies": {
68
71
  "chokidar": "^3.6.0",
@@ -73,6 +76,7 @@
73
76
  "@types/node": "^25.5.2",
74
77
  "tsup": "^8.0.0",
75
78
  "typescript": "^5.4.0",
79
+ "vitepress": "^1.6.4",
76
80
  "vitest": "^3.0.0"
77
81
  }
78
82
  }