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