css-typed-vars 0.5.0 → 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/unplugin.cjs CHANGED
@@ -159,7 +159,7 @@ function extractValue(text, start) {
159
159
  }
160
160
  function scanDeclarations(css, selectors, onProperty) {
161
161
  const stripped = stripComments(css);
162
- const allSelectors = [":root", ...selectors ?? []];
162
+ const allSelectors = [":root", "@theme", ...selectors ?? []];
163
163
  for (const sel of allSelectors) {
164
164
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
165
165
  const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
@@ -182,12 +182,41 @@ function parseVarDeclarations(css, selectors) {
182
182
  scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
183
183
  return declarations;
184
184
  }
185
+ var PROPERTY_DESCRIPTORS = [
186
+ ["syntax", "syntax"],
187
+ ["inherits", "inherits"],
188
+ ["initial-value", "initialValue"]
189
+ ];
190
+ function parsePropertyRules(css) {
191
+ const stripped = stripComments(css);
192
+ const rules = /* @__PURE__ */ new Map();
193
+ const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
194
+ let match;
195
+ while (match = openRegex.exec(stripped)) {
196
+ const name = match[1];
197
+ const start = match.index + match[0].length;
198
+ const block = extractBlock(stripped, start);
199
+ const masked = maskQuotedContent(block);
200
+ const rule = {};
201
+ for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
202
+ const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
203
+ const descMatch = descRegex.exec(masked);
204
+ if (!descMatch) continue;
205
+ const nameEnd = descMatch.index + descMatch[0].length;
206
+ const colonIndex = block.indexOf(":", nameEnd);
207
+ rule[key] = extractValue(block, colonIndex + 1);
208
+ }
209
+ if (Object.keys(rule).length > 0) rules.set(name, rule);
210
+ openRegex.lastIndex = start + block.length + 1;
211
+ }
212
+ return rules;
213
+ }
185
214
 
186
215
  // src/scanner.ts
187
216
  function normalizePatterns(patterns) {
188
217
  return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
189
218
  }
190
- async function scanVarDeclarations(patterns, exclude, selectors) {
219
+ async function scanCss(patterns, exclude, selectors) {
191
220
  const normalized = normalizePatterns(patterns);
192
221
  const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
193
222
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
@@ -198,16 +227,46 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
198
227
  css = await (0, import_promises.readFile)(file, "utf8");
199
228
  } catch (err) {
200
229
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
201
- return /* @__PURE__ */ new Map();
230
+ return { declarations: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
202
231
  }
203
- return parseVarDeclarations(css, selectors);
232
+ return { declarations: parseVarDeclarations(css, selectors), properties: parsePropertyRules(css) };
204
233
  })
205
234
  );
206
- const all = /* @__PURE__ */ new Map();
207
- for (const declarations of perFile) {
208
- for (const [name, value] of declarations) {
209
- all.set(name, value);
210
- }
235
+ const declarations = /* @__PURE__ */ new Map();
236
+ const properties = /* @__PURE__ */ new Map();
237
+ for (const result of perFile) {
238
+ for (const [name, value] of result.declarations) declarations.set(name, value);
239
+ for (const [name, rule] of result.properties) properties.set(name, rule);
240
+ }
241
+ return { declarations, properties };
242
+ }
243
+ var USAGE_RE = /\bcssVars\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/g;
244
+ function extractUsedKeys(text, into) {
245
+ for (const match of text.matchAll(USAGE_RE)) {
246
+ into.add(match[1] ?? match[3]);
247
+ }
248
+ }
249
+ async function scanUsedKeys(patterns, exclude) {
250
+ const normalized = normalizePatterns(patterns);
251
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
252
+ const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
253
+ const perFile = await Promise.all(
254
+ files.map(async (file) => {
255
+ const used = /* @__PURE__ */ new Set();
256
+ let text;
257
+ try {
258
+ text = await (0, import_promises.readFile)(file, "utf8");
259
+ } catch (err) {
260
+ console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
261
+ return used;
262
+ }
263
+ extractUsedKeys(text, used);
264
+ return used;
265
+ })
266
+ );
267
+ const all = /* @__PURE__ */ new Set();
268
+ for (const used of perFile) {
269
+ for (const key of used) all.add(key);
211
270
  }
212
271
  return all;
213
272
  }
@@ -224,10 +283,19 @@ function convertCase(value, naming) {
224
283
  if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
225
284
  return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
226
285
  }
227
- function toKey(cssVarName, naming = "camelCase") {
228
- const key = convertCase(cssVarName.replace(/^--/, ""), naming);
286
+ function toKeyFragment(fragment, naming = "camelCase") {
287
+ const key = convertCase(fragment, naming);
229
288
  return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
230
289
  }
290
+ function toKey(cssVarName, naming = "camelCase") {
291
+ return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
292
+ }
293
+ function splitGroupKey(cssVarName) {
294
+ const stripped = cssVarName.replace(/^--/, "");
295
+ const dashIndex = stripped.indexOf("-");
296
+ if (dashIndex === -1) return null;
297
+ return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
298
+ }
231
299
  var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
232
300
  var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
233
301
  var SINGLE_QUOTE_ESCAPES = {};
@@ -260,6 +328,9 @@ function formatKey(key, naming = "camelCase") {
260
328
  if (naming === "kebab") return `'${key}'`;
261
329
  return key;
262
330
  }
331
+ function computeKey(cssVarName, prefix, naming) {
332
+ return applyPrefix(toKey(cssVarName, naming), prefix, naming);
333
+ }
263
334
  function findKeyCollisions(varNames, prefix, naming) {
264
335
  const byKey = /* @__PURE__ */ new Map();
265
336
  for (const name of varNames) {
@@ -278,22 +349,112 @@ function warnOnCollisions(varNames, prefix, naming) {
278
349
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
279
350
  }
280
351
  }
281
- function buildEntries(varNames, prefix, naming, declarations) {
352
+ function buildEntries(varNames, prefix, naming, declarations, properties) {
282
353
  const byKey = /* @__PURE__ */ new Map();
283
354
  for (const name of varNames) {
284
355
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
285
- byKey.set(key, { name, value: declarations?.get(name) });
356
+ byKey.set(key, { name, value: declarations?.get(name), syntax: properties?.get(name)?.syntax });
286
357
  }
287
358
  return [...byKey].map(([key, entry]) => ({ key, ...entry }));
288
359
  }
289
- function formatDefaultComment(value) {
290
- return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
360
+ function buildGroupedEntries(varNames, naming, declarations, properties) {
361
+ const groupMap = /* @__PURE__ */ new Map();
362
+ const ungroupedMap = /* @__PURE__ */ new Map();
363
+ for (const name of varNames) {
364
+ const value = declarations?.get(name);
365
+ const syntax = properties?.get(name)?.syntax;
366
+ const split = splitGroupKey(name);
367
+ if (!split) {
368
+ ungroupedMap.set(formatKey(toKey(name, naming), naming), { name, value, syntax });
369
+ continue;
370
+ }
371
+ const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
372
+ const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
373
+ let leafMap = groupMap.get(groupKey);
374
+ if (!leafMap) {
375
+ leafMap = /* @__PURE__ */ new Map();
376
+ groupMap.set(groupKey, leafMap);
377
+ }
378
+ leafMap.set(leafKey, { name, value, syntax });
379
+ }
380
+ for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
381
+ const groups = [...groupMap].map(([key, leafMap]) => ({
382
+ key,
383
+ entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
384
+ }));
385
+ const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
386
+ return { groups, ungrouped };
387
+ }
388
+ function formatDefaultComment(value, indent = " ") {
389
+ return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
390
+ }
391
+ function unquoteCssString(value) {
392
+ const quote = value[0];
393
+ if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
394
+ return value.slice(1, -1);
395
+ }
396
+ return value;
397
+ }
398
+ function formatSyntaxComment(syntax, indent = " ") {
399
+ return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
400
+ }
401
+ var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
402
+ function parseEnumSyntax(syntax) {
403
+ const unquoted = unquoteCssString(syntax).trim();
404
+ if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
405
+ return unquoted.split("|").map((v) => v.trim());
406
+ }
407
+ function syntaxTypeName(cssVarName) {
408
+ const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
409
+ return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
410
+ }
411
+ function buildSyntaxTypes(varNames, properties) {
412
+ if (!properties) return [];
413
+ const byName = /* @__PURE__ */ new Map();
414
+ for (const name of varNames) {
415
+ const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
416
+ if (values) byName.set(syntaxTypeName(name), values);
417
+ }
418
+ return [...byName].map(([name, values]) => ({ name, values }));
291
419
  }
292
- function generateJs(varNames, prefix, naming, declarations) {
293
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
294
- ...value ? [formatDefaultComment(value)] : [],
295
- ` ${key}: 'var(${name})',`
420
+ function renderSyntaxTypeLines(types) {
421
+ return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
422
+ }
423
+ function buildTailBlocks(varNames, group, properties) {
424
+ const blocks = [];
425
+ if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
426
+ const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
427
+ if (syntaxLines.length > 0) blocks.push(syntaxLines);
428
+ return blocks;
429
+ }
430
+ function renderEntryLines(entries, indent, lineFor) {
431
+ return entries.flatMap(({ key, name, value, syntax }) => [
432
+ ...value ? [formatDefaultComment(value, indent)] : [],
433
+ ...syntax ? [formatSyntaxComment(syntax, indent)] : [],
434
+ `${indent}${lineFor(key, name)}`
296
435
  ]);
436
+ }
437
+ function renderGroupedBlock(varNames, naming, declarations, properties, indent, closeSuffix, lineFor) {
438
+ const { groups, ungrouped } = buildGroupedEntries(varNames, naming, declarations, properties);
439
+ const lines = [];
440
+ for (const group of groups) {
441
+ lines.push(`${indent}${group.key}: {`);
442
+ lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
443
+ lines.push(`${indent}}${closeSuffix}`);
444
+ }
445
+ lines.push(...renderEntryLines(ungrouped, indent, lineFor));
446
+ return lines;
447
+ }
448
+ function assertGroupPrefixCompatible(prefix, group) {
449
+ if (group && prefix) {
450
+ throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
451
+ }
452
+ }
453
+ var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
454
+ var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
455
+ function generateJs(varNames, prefix, naming, declarations, group, properties) {
456
+ assertGroupPrefixCompatible(prefix, group);
457
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ",", codeLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", codeLineFor);
297
458
  return [
298
459
  "// generated \u2014 do not edit",
299
460
  "export const cssVars = {",
@@ -302,16 +463,16 @@ function generateJs(varNames, prefix, naming, declarations) {
302
463
  ""
303
464
  ].join("\n");
304
465
  }
305
- function generateDeclaration(varNames, prefix, naming, declarations) {
306
- const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
307
- ...value ? [formatDefaultComment(value)] : [],
308
- ` ${key}: 'var(${name})';`
309
- ]);
466
+ function generateDeclaration(varNames, prefix, naming, declarations, group, properties) {
467
+ assertGroupPrefixCompatible(prefix, group);
468
+ const entries = group ? renderGroupedBlock(varNames, naming, declarations, properties, " ", ";", declarationLineFor) : renderEntryLines(buildEntries(varNames, prefix, naming, declarations, properties), " ", declarationLineFor);
469
+ const blocks = buildTailBlocks(varNames, group, properties);
470
+ const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
310
471
  return [
311
472
  "export declare const cssVars: {",
312
473
  ...entries,
313
474
  "};",
314
- "export type CssVarName = keyof typeof cssVars;",
475
+ ...tailBody,
315
476
  ""
316
477
  ].join("\n");
317
478
  }
@@ -324,8 +485,27 @@ function getDtsPath(options) {
324
485
  return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
325
486
  }
326
487
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
327
- let cachedDeclarations = null;
328
- const scan = () => scanVarDeclarations(options.input, options.exclude, options.selectors);
488
+ if (options.prune) {
489
+ if (options.group) throw new Error('css-typed-vars: "prune" cannot be combined with "group".');
490
+ if (!options.usage) throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
491
+ }
492
+ let cachedScan = null;
493
+ const scan = () => scanCss(options.input, options.exclude, options.selectors);
494
+ const applyPrune = async (names) => {
495
+ if (!options.prune) return names;
496
+ const usedKeys = await scanUsedKeys(options.usage, options.usageExclude);
497
+ const isUsed = (name) => usedKeys.has(computeKey(name, options.prefix, options.naming));
498
+ const unused = names.filter((name) => !isUsed(name));
499
+ if (unused.length > 0) {
500
+ console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
501
+ }
502
+ return names.filter(isUsed);
503
+ };
504
+ const resolveNames = async (declarations) => {
505
+ const names = [...declarations.keys()].sort();
506
+ warnOnCollisions(names, options.prefix, options.naming);
507
+ return applyPrune(names);
508
+ };
329
509
  return {
330
510
  name: "css-typed-vars",
331
511
  vite: {
@@ -336,15 +516,15 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
336
516
  let writeQueue = Promise.resolve();
337
517
  const rescan = async () => {
338
518
  const myGeneration = ++generation;
339
- const declarationsPromise = scan();
340
- cachedDeclarations = declarationsPromise;
341
- const declarations = await declarationsPromise;
519
+ const scanPromise = scan();
520
+ cachedScan = scanPromise;
521
+ const { declarations, properties } = await scanPromise;
522
+ if (myGeneration !== generation) return;
523
+ const names = await resolveNames(declarations);
342
524
  if (myGeneration !== generation) return;
343
- const names = [...declarations.keys()].sort();
344
- warnOnCollisions(names, options.prefix, options.naming);
345
525
  const dtsPath = getDtsPath(options);
346
526
  if (dtsPath) {
347
- const content = generateDeclaration(names, options.prefix, options.naming, declarations);
527
+ const content = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
348
528
  writeQueue = writeQueue.then(async () => {
349
529
  if (myGeneration !== generation) return;
350
530
  await (0, import_promises2.writeFile)(dtsPath, content, "utf8");
@@ -372,22 +552,21 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
372
552
  }
373
553
  },
374
554
  async buildStart() {
375
- cachedDeclarations = scan();
376
- const declarations = await cachedDeclarations;
377
- const names = [...declarations.keys()].sort();
378
- warnOnCollisions(names, options.prefix, options.naming);
555
+ cachedScan = scan();
556
+ const { declarations, properties } = await cachedScan;
557
+ const names = await resolveNames(declarations);
379
558
  const dtsPath = getDtsPath(options);
380
559
  if (!dtsPath) return;
381
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations), "utf8");
560
+ await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties), "utf8");
382
561
  },
383
562
  resolveId(id) {
384
563
  if (id === VIRTUAL_ID) return RESOLVED_ID;
385
564
  },
386
565
  async load(id) {
387
566
  if (id === RESOLVED_ID) {
388
- const declarations = await (cachedDeclarations ?? scan());
389
- const names = [...declarations.keys()].sort();
390
- return generateJs(names, options.prefix, options.naming, declarations);
567
+ const { declarations, properties } = await (cachedScan ?? scan());
568
+ const names = await applyPrune([...declarations.keys()].sort());
569
+ return generateJs(names, options.prefix, options.naming, declarations, options.group, properties);
391
570
  }
392
571
  }
393
572
  };
@@ -1,5 +1,5 @@
1
1
  import * as unplugin from 'unplugin';
2
- import { N as NamingConvention } from './generator-t6h8Ic7V.cjs';
2
+ import { N as NamingConvention } from './generator-C2AppeJL.cjs';
3
3
 
4
4
  interface Options {
5
5
  input: string | string[];
@@ -14,6 +14,12 @@ interface Options {
14
14
  prefix?: string;
15
15
  naming?: NamingConvention;
16
16
  selectors?: string[];
17
+ group?: boolean;
18
+ /** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage`, and can't be combined with `group`. */
19
+ prune?: boolean;
20
+ /** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
21
+ usage?: string | string[];
22
+ usageExclude?: string | string[];
17
23
  }
18
24
  declare const _default: unplugin.UnpluginInstance<Options, boolean>;
19
25
 
@@ -1,5 +1,5 @@
1
1
  import * as unplugin from 'unplugin';
2
- import { N as NamingConvention } from './generator-t6h8Ic7V.js';
2
+ import { N as NamingConvention } from './generator-C2AppeJL.js';
3
3
 
4
4
  interface Options {
5
5
  input: string | string[];
@@ -14,6 +14,12 @@ interface Options {
14
14
  prefix?: string;
15
15
  naming?: NamingConvention;
16
16
  selectors?: string[];
17
+ group?: boolean;
18
+ /** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage`, and can't be combined with `group`. */
19
+ prune?: boolean;
20
+ /** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
21
+ usage?: string | string[];
22
+ usageExclude?: string | string[];
17
23
  }
18
24
  declare const _default: unplugin.UnpluginInstance<Options, boolean>;
19
25
 
package/dist/unplugin.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-TD7SYMDA.js";
4
+ import "./chunk-LH53WYFF.js";
5
5
  export {
6
6
  unplugin_default as default
7
7
  };