css-typed-vars 0.6.0 → 0.8.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
@@ -51,6 +51,11 @@ function stepQuote(text, i, quote) {
51
51
  return { consumed: 1, closed: false };
52
52
  }
53
53
  function stripComments(text) {
54
+ return stripCommentsWithMap(text).text;
55
+ }
56
+ function stripCommentsWithMap(text) {
57
+ const removed = [];
58
+ const comments = [];
54
59
  let result = "";
55
60
  let quote = null;
56
61
  let urlDepth = 0;
@@ -85,17 +90,20 @@ function stripComments(text) {
85
90
  result += char;
86
91
  continue;
87
92
  }
93
+ comments.push([i, end + 2]);
94
+ removed.push({ at: result.length, length: end + 2 - i });
88
95
  i = end + 1;
89
96
  continue;
90
97
  }
91
98
  if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
92
99
  const nl = text.indexOf("\n", i);
100
+ removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
93
101
  i = nl === -1 ? text.length - 1 : nl - 1;
94
102
  continue;
95
103
  }
96
104
  result += char;
97
105
  }
98
- return result;
106
+ return { text: result, removed, comments };
99
107
  }
100
108
  function extractBlock(text, start) {
101
109
  let depth = 1;
@@ -159,30 +167,119 @@ function extractValue(text, start) {
159
167
  }
160
168
  return text.slice(start, i).trim();
161
169
  }
162
- function scanDeclarations(css, selectors, onProperty) {
163
- const stripped = stripComments(css);
164
- const allSelectors = [":root", "@theme", ...selectors ?? []];
165
- for (const sel of allSelectors) {
170
+ function forEachProperty(block, onProperty, offset = 0) {
171
+ const masked = maskQuotedContent(block);
172
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
173
+ const name = prop[0];
174
+ const colonIndex = block.indexOf(":", prop.index + name.length);
175
+ onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
176
+ }
177
+ }
178
+ function forEachSelectorBlock(stripped, selectors, onBlock) {
179
+ for (const sel of selectors) {
166
180
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
167
181
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
168
182
  let match;
169
183
  while (match = openRegex.exec(stripped)) {
170
184
  const start = match.index + match[0].length;
171
185
  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;
186
+ const end = start + block.length + 1;
187
+ onBlock(block, [start, end]);
188
+ openRegex.lastIndex = end;
189
+ }
190
+ }
191
+ }
192
+ var BASE_SELECTORS = [":root", "@theme"];
193
+ function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
194
+ forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
195
+ if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
196
+ forEachProperty(block, onProperty, bodyStart);
197
+ });
198
+ }
199
+ var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
200
+ function forEachMediaBlock(stripped, media, onBlock) {
201
+ const wanted = normalizePrelude(media.replace(/^@media/i, ""));
202
+ const openRegex = /@media([^{;]*)\{/gi;
203
+ let match;
204
+ while (match = openRegex.exec(stripped)) {
205
+ const start = match.index + match[0].length;
206
+ const block = extractBlock(stripped, start);
207
+ const end = start + block.length + 1;
208
+ if (normalizePrelude(match[1]) === wanted) {
209
+ onBlock(block, [start, end]);
210
+ openRegex.lastIndex = end;
211
+ } else {
212
+ openRegex.lastIndex = start;
179
213
  }
180
214
  }
181
215
  }
182
- function parseVarDeclarations(css, selectors) {
216
+ function parseDocComment(body) {
217
+ const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
218
+ const doc = {};
219
+ const description = [];
220
+ let inTags = false;
221
+ for (const line of lines) {
222
+ const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
223
+ if (tag) {
224
+ inTags = true;
225
+ if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
226
+ } else if (!inTags) {
227
+ description.push(line);
228
+ }
229
+ }
230
+ const text = description.join("\n").trim();
231
+ if (text) doc.description = text;
232
+ return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
233
+ }
234
+ function makeDocReader(css, stripped) {
235
+ const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
236
+ return (strippedPos) => {
237
+ let end = toRawPosition(stripped, strippedPos);
238
+ while (end > 0 && /\s/.test(css[end - 1])) end--;
239
+ const start = commentStartByEnd.get(end);
240
+ if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
241
+ return parseDocComment(css.slice(start + 3, end - 2));
242
+ };
243
+ }
244
+ function parseThemedDeclarations(css, selectors, themes) {
245
+ const strippedCss = stripCommentsWithMap(css);
246
+ const stripped = strippedCss.text;
247
+ const docAt = makeDocReader(css, strippedCss);
248
+ const themeDocs = /* @__PURE__ */ new Map();
249
+ const themeValues = /* @__PURE__ */ new Map();
250
+ const skip = [];
251
+ for (const [themeName, themeSelector] of Object.entries(themes)) {
252
+ const values = /* @__PURE__ */ new Map();
253
+ themeValues.set(themeName, values);
254
+ const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
255
+ values.set(name, value);
256
+ const doc = docAt(position);
257
+ if (doc) themeDocs.set(name, doc);
258
+ }, offset);
259
+ const selector = themeSelector.trim();
260
+ if (/^@media\b/i.test(selector)) {
261
+ forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
262
+ skip.push(range);
263
+ forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
264
+ });
265
+ } else {
266
+ forEachSelectorBlock(stripped, [selector], (block, range) => {
267
+ skip.push(range);
268
+ collect(block, range[0]);
269
+ });
270
+ }
271
+ }
183
272
  const declarations = /* @__PURE__ */ new Map();
184
- scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
185
- return declarations;
273
+ const docs = /* @__PURE__ */ new Map();
274
+ scanDeclarations(css, selectors, (name, value, position) => {
275
+ declarations.set(name, value);
276
+ const doc = docAt(position);
277
+ if (doc) docs.set(name, doc);
278
+ }, skip, stripped);
279
+ for (const [name, doc] of themeDocs) {
280
+ if (!docs.has(name)) docs.set(name, doc);
281
+ }
282
+ return { declarations, themes: themeValues, docs };
186
283
  }
187
284
  var PROPERTY_DESCRIPTORS = [
188
285
  ["syntax", "syntax"],
@@ -213,12 +310,27 @@ function parsePropertyRules(css) {
213
310
  }
214
311
  return rules;
215
312
  }
313
+ function toRawPosition(stripped, strippedPos) {
314
+ let rawPos = strippedPos;
315
+ for (const { at, length } of stripped.removed) {
316
+ if (at > strippedPos) break;
317
+ rawPos += length;
318
+ }
319
+ return rawPos;
320
+ }
216
321
 
217
322
  // src/scanner.ts
218
323
  function normalizePatterns(patterns) {
219
324
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
220
325
  }
221
- async function scanCss(patterns, exclude, selectors) {
326
+ function collectVarNames(scanned) {
327
+ const names = new Set(scanned.declarations.keys());
328
+ for (const values of scanned.themes.values()) {
329
+ for (const name of values.keys()) names.add(name);
330
+ }
331
+ return [...names].sort();
332
+ }
333
+ async function scanCss(patterns, exclude, selectors, themes = {}) {
222
334
  const normalized = normalizePatterns(patterns);
223
335
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
224
336
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -229,48 +341,60 @@ async function scanCss(patterns, exclude, selectors) {
229
341
  css = await (0, import_promises.readFile)(file, "utf8");
230
342
  } catch (err) {
231
343
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
232
- return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
344
+ return null;
233
345
  }
234
- return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
346
+ return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
235
347
  })
236
348
  );
237
349
  const declarations = /* @__PURE__ */ new Map();
238
350
  const properties = /* @__PURE__ */ new Map();
351
+ const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
352
+ const docs = /* @__PURE__ */ new Map();
239
353
  for (const result of perFile) {
354
+ if (!result) continue;
240
355
  for (const [name, value] of result.declarations) declarations.set(name, value);
241
356
  for (const [name, rule] of result.properties) properties.set(name, rule);
357
+ for (const [name, doc] of result.docs) docs.set(name, doc);
358
+ for (const [theme, values] of result.themes) {
359
+ for (const [name, value] of values) themeValues.get(theme).set(name, value);
360
+ }
242
361
  }
243
- return { declarations, properties };
244
- }
245
- var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
246
- function extractUsedKeys(text, into) {
247
- for (const match of text.matchAll(USAGE_RE)) {
248
- into.add(match[1] ?? match[3]);
362
+ return { declarations, properties, themes: themeValues, docs };
363
+ }
364
+ var ROOT_RE = /\bcssVars\b/g;
365
+ var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
366
+ function readAccess(text, from) {
367
+ ACCESS_RE.lastIndex = from;
368
+ const match = ACCESS_RE.exec(text);
369
+ return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
370
+ }
371
+ function extractUsage(text, into) {
372
+ for (const root of text.matchAll(ROOT_RE)) {
373
+ const first = readAccess(text, root.index + root[0].length);
374
+ if (!first) continue;
375
+ into.keys.add(first.key);
376
+ const second = readAccess(text, first.end);
377
+ if (second) into.paths.add(`${first.key}\0${second.key}`);
378
+ else into.wholeKeys.add(first.key);
249
379
  }
250
380
  }
251
- async function scanUsedKeys(patterns, exclude) {
381
+ async function scanUsage(patterns, exclude) {
252
382
  const normalized = normalizePatterns(patterns);
253
383
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
254
384
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
255
- const perFile = await Promise.all(
385
+ const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
386
+ const texts = await Promise.all(
256
387
  files.map(async (file) => {
257
- const used = /* @__PURE__ */ new Set();
258
- let text;
259
388
  try {
260
- text = await (0, import_promises.readFile)(file, "utf8");
389
+ return await (0, import_promises.readFile)(file, "utf8");
261
390
  } catch (err) {
262
391
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
263
- return used;
392
+ return "";
264
393
  }
265
- extractUsedKeys(text, used);
266
- return used;
267
394
  })
268
395
  );
269
- const all = /* @__PURE__ */ new Set();
270
- for (const used of perFile) {
271
- for (const key of used) all.add(key);
272
- }
273
- return all;
396
+ for (const text of texts) extractUsage(text, usage);
397
+ return usage;
274
398
  }
275
399
 
276
400
  // src/generator.ts
@@ -333,6 +457,12 @@ function formatKey(key, naming = "camelCase") {
333
457
  function computeKey(cssVarName, prefix, naming) {
334
458
  return applyPrefix(toKey(cssVarName, naming), prefix, naming);
335
459
  }
460
+ function computeKeyPath(cssVarName, prefix, naming, group) {
461
+ if (!group) return [computeKey(cssVarName, prefix, naming)];
462
+ const split = splitGroupKey(cssVarName);
463
+ if (!split) return [toKey(cssVarName, naming)];
464
+ return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
465
+ }
336
466
  function findKeyCollisions(varNames, prefix, naming) {
337
467
  const byKey = /* @__PURE__ */ new Map();
338
468
  for (const name of varNames) {
@@ -351,23 +481,38 @@ function warnOnCollisions(varNames, prefix, naming) {
351
481
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
352
482
  }
353
483
  }
354
- function buildEntries(varNames, prefix, naming, declarations, properties) {
484
+ function entryMeta(name, options) {
485
+ const themes = [];
486
+ for (const [theme, values] of options.themes ?? []) {
487
+ const value = values.get(name);
488
+ if (value !== void 0) themes.push([theme, value]);
489
+ }
490
+ return {
491
+ name,
492
+ value: options.declarations?.get(name),
493
+ syntax: options.properties?.get(name)?.syntax,
494
+ ...themes.length > 0 ? { themes } : {},
495
+ ...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
496
+ };
497
+ }
498
+ function buildEntries(varNames, options) {
499
+ const { prefix, naming } = options;
355
500
  const byKey = /* @__PURE__ */ new Map();
356
501
  for (const name of varNames) {
357
502
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
358
- byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
503
+ byKey.set(key, entryMeta(name, options));
359
504
  }
360
505
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
361
506
  }
362
- function buildGroupedEntries(varNames, naming, declarations, properties) {
507
+ function buildGroupedEntries(varNames, options) {
508
+ const { naming } = options;
363
509
  const groupMap = /* @__PURE__ */ new Map();
364
510
  const ungroupedMap = /* @__PURE__ */ new Map();
365
511
  for (const name of varNames) {
366
- const value = declarations?.get(name);
367
- const syntax = properties?.get(name)?.syntax;
512
+ const meta = entryMeta(name, options);
368
513
  const split = splitGroupKey(name);
369
514
  if (!split) {
370
- ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
515
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
371
516
  continue;
372
517
  }
373
518
  const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
@@ -377,7 +522,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
377
522
  leafMap = /* @__PURE__ */ new Map();
378
523
  groupMap.set(groupKey, leafMap);
379
524
  }
380
- leafMap.set(leafKey, { name, value, syntax });
525
+ leafMap.set(leafKey, meta);
381
526
  }
382
527
  for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
383
528
  const groups = [...groupMap].map(([key, leafMap]) => ({
@@ -387,8 +532,12 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
387
532
  const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
388
533
  return { groups, ungrouped };
389
534
  }
390
- function formatDefaultComment(value, indent = " ") {
391
- return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
535
+ var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
536
+ function renderJsDoc(tags, indent) {
537
+ if (tags.length === 0) return [];
538
+ if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
539
+ const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
540
+ return [`${indent}/**`, ...body, `${indent} */`];
392
541
  }
393
542
  function unquoteCssString(value) {
394
543
  const quote = value[0];
@@ -397,8 +546,15 @@ function unquoteCssString(value) {
397
546
  }
398
547
  return value;
399
548
  }
400
- function formatSyntaxComment(syntax, indent = " ") {
401
- return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
549
+ function entryTags({ value, syntax, themes, doc }) {
550
+ const deprecated = doc?.deprecated;
551
+ return [
552
+ ...doc?.description ? [doc.description] : [],
553
+ ...value ? [`@default ${value}`] : [],
554
+ ...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
555
+ ...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
556
+ ...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
557
+ ];
402
558
  }
403
559
  var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
404
560
  function parseEnumSyntax(syntax) {
@@ -430,14 +586,13 @@ function buildTailBlocks(varNames, group, properties) {
430
586
  return blocks;
431
587
  }
432
588
  function renderEntryLines(entries, indent, lineFor) {
433
- return entries.flatMap(({ key, name, value, syntax }) => [
434
- ...value ? [formatDefaultComment(value, indent)] : [],
435
- ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
436
- `${indent}${lineFor(key, name)}`
589
+ return entries.flatMap((entry) => [
590
+ ...renderJsDoc(entryTags(entry), indent),
591
+ `${indent}${lineFor(entry.key, entry.name)}`
437
592
  ]);
438
593
  }
439
- function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
440
- const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
594
+ function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
595
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
441
596
  const lines = [];
442
597
  for (const group of groups) {
443
598
  lines.push(`${indent}${group.key}: {`);
@@ -454,21 +609,61 @@ function assertGroupPrefixCompatible(prefix, group) {
454
609
  }
455
610
  var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
456
611
  var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
457
- function generateJs(varNames, prefix, naming, declarations, group, properties) {
458
- assertGroupPrefixCompatible(prefix, group);
459
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
612
+ function normalizeOptions(args) {
613
+ const [first] = args;
614
+ if (first !== null && typeof first === "object") return first;
615
+ const [prefix, naming, declarations, group, properties] = args;
616
+ return { prefix, naming, declarations, group, properties };
617
+ }
618
+ function renderEntries(varNames, options, closeSuffix, lineFor) {
619
+ assertGroupPrefixCompatible(options.prefix, options.group);
620
+ return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
621
+ }
622
+ function emittedNames(varNames, options) {
623
+ if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
624
+ const { groups, ungrouped } = buildGroupedEntries(varNames, options);
625
+ return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
626
+ }
627
+ function renderRefType(varNames, options) {
628
+ const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
629
+ return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
630
+ }
631
+ var HELPERS_JS = [
632
+ "export function getCssVar(ref, el = document.documentElement) {",
633
+ " return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
634
+ "}",
635
+ "",
636
+ "export function setCssVar(ref, value, el = document.documentElement) {",
637
+ " el.style.setProperty(ref.slice(4, -1), value);",
638
+ "}",
639
+ "",
640
+ "export function withFallback(ref, fallback) {",
641
+ " return `${ref.slice(0, -1)}, ${fallback})`;",
642
+ "}"
643
+ ];
644
+ var HELPERS_DTS = [
645
+ "export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
646
+ "export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
647
+ "export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
648
+ "export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
649
+ ];
650
+ function generateJs(varNames, ...args) {
651
+ const options = normalizeOptions(args);
652
+ const entries = renderEntries(varNames, options, ",", codeLineFor);
460
653
  return [
461
654
  "// generated \u2014 do not edit",
462
655
  "export const cssVars = {",
463
656
  ...entries,
464
657
  "};",
658
+ ...options.helpers ? ["", ...HELPERS_JS] : [],
465
659
  ""
466
660
  ].join("\n");
467
661
  }
468
- function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
469
- assertGroupPrefixCompatible(prefix, group);
470
- const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
471
- const blocks = buildTailBlocks(varNames, group, properties);
662
+ function generateDeclaration(varNames, ...args) {
663
+ const options = normalizeOptions(args);
664
+ const entries = renderEntries(varNames, options, ";", declarationLineFor);
665
+ const blocks = buildTailBlocks(varNames, options.group, options.properties);
666
+ if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
472
667
  const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
473
668
  return [
474
669
  "export declare const cssVars: {",
@@ -478,6 +673,68 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
478
673
  ""
479
674
  ].join("\n");
480
675
  }
676
+ var TOKEN_TYPES = {
677
+ "<color>": "color",
678
+ "<length>": "dimension",
679
+ "<length-percentage>": "dimension",
680
+ "<number>": "number",
681
+ "<integer>": "number",
682
+ "<time>": "duration"
683
+ };
684
+ var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
685
+ function generateTokens(varNames, options = {}) {
686
+ assertGroupPrefixCompatible(options.prefix, options.group);
687
+ const tokens = emittedNames(varNames, options).flatMap((name) => {
688
+ const meta = entryMeta(name, options);
689
+ const value = meta.value ?? options.properties?.get(name)?.initialValue;
690
+ return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
691
+ });
692
+ const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
693
+ const resolve2 = (value) => {
694
+ const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
695
+ return target ? `{${target.join(".")}}` : value;
696
+ };
697
+ const root = {};
698
+ for (const { meta, value, path } of tokens) {
699
+ const token = { $value: resolve2(value) };
700
+ const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
701
+ if (type) token.$type = type;
702
+ if (meta.doc?.description) token.$description = meta.doc.description;
703
+ if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
704
+ if (meta.themes) {
705
+ const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
706
+ token.$extensions = { "css-typed-vars": { themes } };
707
+ }
708
+ const [key, leaf] = path;
709
+ if (leaf === void 0) {
710
+ root[key] = token;
711
+ } else {
712
+ const group = root[key] ?? (root[key] = {});
713
+ group[leaf] = token;
714
+ }
715
+ }
716
+ return JSON.stringify(root, null, 2) + "\n";
717
+ }
718
+
719
+ // src/prune.ts
720
+ function assertPruneCompatible(options) {
721
+ if (options.prune && !options.usage) {
722
+ throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
723
+ }
724
+ }
725
+ function isUsed(name, usage, options) {
726
+ const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
727
+ if (leaf === void 0) return usage.keys.has(key);
728
+ return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
729
+ }
730
+ function partitionUnused(names, usage, options) {
731
+ const used = [];
732
+ const unused = [];
733
+ for (const name of names) {
734
+ (isUsed(name, usage, options) ? used : unused).push(name);
735
+ }
736
+ return { used, unused };
737
+ }
481
738
 
482
739
  // src/unplugin.ts
483
740
  var VIRTUAL_ID = "css-typed-vars/vars";
@@ -486,25 +743,38 @@ function getDtsPath(options) {
486
743
  if (options.dts === false) return null;
487
744
  return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
488
745
  }
746
+ function outputFiles(options, names, generatorOptions) {
747
+ const files = [];
748
+ const dtsPath = getDtsPath(options);
749
+ 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)]);
751
+ return files;
752
+ }
489
753
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
490
- if (options.prune) {
491
- if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
492
- if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
493
- }
754
+ assertPruneCompatible(options);
494
755
  let cachedScan = null;
495
- const scan = () => scanCss(options.input, options.exclude, options.selectors);
756
+ const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
496
757
  const applyPrune = async (names) => {
497
758
  if (!options.prune) return names;
498
- const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
499
- const isUsed = (name) => usedKeys.has(computeKey(name, options.prefix, options.naming));
500
- const unused = names.filter((name) => !isUsed(name));
759
+ const usage = await scanUsage(options.usage, options.usageExclude);
760
+ const { used, unused } = partitionUnused(names, usage, options);
501
761
  if (unused.length > 0) {
502
762
  console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
503
763
  }
504
- return names.filter(isUsed);
764
+ return used;
505
765
  };
506
- const resolveNames = async (declarations) => {
507
- const names = [...declarations.keys()].sort();
766
+ const generatorOptions = ({ declarations, properties, themes, docs }) => ({
767
+ prefix: options.prefix,
768
+ naming: options.naming,
769
+ declarations,
770
+ group: options.group,
771
+ properties,
772
+ helpers: options.helpers,
773
+ themes,
774
+ docs
775
+ });
776
+ const resolveNames = async (scanned) => {
777
+ const names = collectVarNames(scanned);
508
778
  warnOnCollisions(names, options.prefix, options.naming);
509
779
  return applyPrune(names);
510
780
  };
@@ -520,16 +790,17 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
520
790
  const myGeneration = ++generation;
521
791
  const scanPromise = scan();
522
792
  cachedScan = scanPromise;
523
- const { declarations, properties } = await scanPromise;
793
+ const scanned = await scanPromise;
524
794
  if (myGeneration !== generation) return;
525
- const names = await resolveNames(declarations);
795
+ const names = await resolveNames(scanned);
526
796
  if (myGeneration !== generation) return;
527
- const dtsPath = getDtsPath(options);
528
- if (dtsPath) {
529
- const content = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
797
+ const files = outputFiles(options, names, generatorOptions(scanned));
798
+ if (files.length > 0) {
530
799
  writeQueue = writeQueue.then(async () => {
531
- if (myGeneration !== generation) return;
532
- await (0, import_promises2.writeFile)(dtsPath, content, "utf8");
800
+ for (const [path, content] of files) {
801
+ if (myGeneration !== generation) return;
802
+ await (0, import_promises2.writeFile)(path, content, "utf8");
803
+ }
533
804
  }).catch(console.error);
534
805
  await writeQueue;
535
806
  }
@@ -555,20 +826,20 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
555
826
  },
556
827
  async buildStart() {
557
828
  cachedScan = scan();
558
- const { declarations, properties } = await cachedScan;
559
- const names = await resolveNames(declarations);
560
- const dtsPath = getDtsPath(options);
561
- if (!dtsPath) return;
562
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties), "utf8");
829
+ const scanned = await cachedScan;
830
+ const names = await resolveNames(scanned);
831
+ for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
832
+ await (0, import_promises2.writeFile)(path, content, "utf8");
833
+ }
563
834
  },
564
835
  resolveId(id) {
565
836
  if (id === VIRTUAL_ID) return RESOLVED_ID;
566
837
  },
567
838
  async load(id) {
568
839
  if (id === RESOLVED_ID) {
569
- const { declarations, properties } = await (cachedScan ?? scan());
570
- const names = await applyPrune([...declarations.keys()].sort());
571
- return generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
840
+ const scanned = await (cachedScan ?? scan());
841
+ const names = await applyPrune(collectVarNames(scanned));
842
+ return generateJs(names, generatorOptions(scanned));
572
843
  }
573
844
  }
574
845
  };
@@ -1,7 +1,7 @@
1
1
  import * as esbuild from 'esbuild';
2
2
  import { Options } from './unplugin.cjs';
3
3
  import 'unplugin';
4
- import './generator-C2AppeJL.cjs';
4
+ import './generator-DJ9uOYBP.cjs';
5
5
 
6
6
  declare const _default: (options: Options) => esbuild.Plugin;
7
7
 
package/dist/esbuild.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as esbuild from 'esbuild';
2
2
  import { Options } from './unplugin.js';
3
3
  import 'unplugin';
4
- import './generator-C2AppeJL.js';
4
+ import './generator-DJ9uOYBP.js';
5
5
 
6
6
  declare const _default: (options: Options) => esbuild.Plugin;
7
7
 
package/dist/esbuild.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-TD7SYMDA.js";
4
- import "./chunk-LH53WYFF.js";
3
+ } from "./chunk-32V3V6WT.js";
4
+ import "./chunk-5HPTHW7S.js";
5
5
 
6
6
  // src/esbuild.ts
7
7
  var esbuild_default = unplugin_default.esbuild;