css-typed-vars 0.6.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/README.md +91 -6
- package/dist/{chunk-LH53WYFF.js → chunk-6YWE4A6S.js} +259 -55
- package/dist/{chunk-TD7SYMDA.js → chunk-HBUSLYYB.js} +45 -29
- package/dist/{chunk-VZ2BHHXD.js → chunk-PLO2JWR7.js} +31 -29
- package/dist/cli.cjs +277 -83
- package/dist/cli.js +15 -9
- package/dist/esbuild.cjs +273 -79
- package/dist/esbuild.d.cts +1 -1
- package/dist/esbuild.d.ts +1 -1
- package/dist/esbuild.js +2 -2
- package/dist/generator-C1iVNsry.d.cts +49 -0
- package/dist/generator-C1iVNsry.d.ts +49 -0
- package/dist/index.cjs +274 -71
- package/dist/index.d.cts +16 -5
- package/dist/index.d.ts +16 -5
- package/dist/index.js +6 -2
- package/dist/rollup.cjs +273 -79
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +273 -79
- package/dist/unplugin.d.cts +12 -2
- package/dist/unplugin.d.ts +12 -2
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +273 -79
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +273 -79
- package/dist/webpack.d.cts +1 -1
- package/dist/webpack.d.ts +1 -1
- package/dist/webpack.js +2 -2
- package/package.json +1 -1
- package/dist/generator-C2AppeJL.d.cts +0 -15
- package/dist/generator-C2AppeJL.d.ts +0 -15
package/dist/unplugin.cjs
CHANGED
|
@@ -157,30 +157,76 @@ function extractValue(text, start) {
|
|
|
157
157
|
}
|
|
158
158
|
return text.slice(start, i).trim();
|
|
159
159
|
}
|
|
160
|
-
function
|
|
161
|
-
const
|
|
162
|
-
const
|
|
163
|
-
|
|
160
|
+
function forEachProperty(block, onProperty) {
|
|
161
|
+
const masked = maskQuotedContent(block);
|
|
162
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
163
|
+
const name = prop[0];
|
|
164
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
165
|
+
onProperty(name, extractValue(block, colonIndex + 1));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
169
|
+
for (const sel of selectors) {
|
|
164
170
|
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
165
171
|
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
166
172
|
let match;
|
|
167
173
|
while (match = openRegex.exec(stripped)) {
|
|
168
174
|
const start = match.index + match[0].length;
|
|
169
175
|
const block = extractBlock(stripped, start);
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
176
|
+
const end = start + block.length + 1;
|
|
177
|
+
onBlock(block, [start, end]);
|
|
178
|
+
openRegex.lastIndex = end;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
var BASE_SELECTORS = [":root", "@theme"];
|
|
183
|
+
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
184
|
+
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
185
|
+
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
186
|
+
forEachProperty(block, onProperty);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
190
|
+
function forEachMediaBlock(stripped, media, onBlock) {
|
|
191
|
+
const wanted = normalizePrelude(media.replace(/^@media/i, ""));
|
|
192
|
+
const openRegex = /@media([^{;]*)\{/gi;
|
|
193
|
+
let match;
|
|
194
|
+
while (match = openRegex.exec(stripped)) {
|
|
195
|
+
const start = match.index + match[0].length;
|
|
196
|
+
const block = extractBlock(stripped, start);
|
|
197
|
+
const end = start + block.length + 1;
|
|
198
|
+
if (normalizePrelude(match[1]) === wanted) {
|
|
199
|
+
onBlock(block, [start, end]);
|
|
200
|
+
openRegex.lastIndex = end;
|
|
201
|
+
} else {
|
|
202
|
+
openRegex.lastIndex = start;
|
|
177
203
|
}
|
|
178
204
|
}
|
|
179
205
|
}
|
|
180
|
-
function
|
|
206
|
+
function parseThemedDeclarations(css, selectors, themes) {
|
|
207
|
+
const stripped = stripComments(css);
|
|
208
|
+
const themeValues = /* @__PURE__ */ new Map();
|
|
209
|
+
const skip = [];
|
|
210
|
+
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
211
|
+
const values = /* @__PURE__ */ new Map();
|
|
212
|
+
themeValues.set(themeName, values);
|
|
213
|
+
const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
|
|
214
|
+
const selector = themeSelector.trim();
|
|
215
|
+
if (/^@media\b/i.test(selector)) {
|
|
216
|
+
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
217
|
+
skip.push(range);
|
|
218
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
219
|
+
});
|
|
220
|
+
} else {
|
|
221
|
+
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
222
|
+
skip.push(range);
|
|
223
|
+
collect(block);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
181
227
|
const declarations = /* @__PURE__ */ new Map();
|
|
182
|
-
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
|
|
183
|
-
return declarations;
|
|
228
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
|
|
229
|
+
return { declarations, themes: themeValues };
|
|
184
230
|
}
|
|
185
231
|
var PROPERTY_DESCRIPTORS = [
|
|
186
232
|
["syntax", "syntax"],
|
|
@@ -216,7 +262,14 @@ function parsePropertyRules(css) {
|
|
|
216
262
|
function normalizePatterns(patterns) {
|
|
217
263
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
218
264
|
}
|
|
219
|
-
|
|
265
|
+
function collectVarNames(scanned) {
|
|
266
|
+
const names = new Set(scanned.declarations.keys());
|
|
267
|
+
for (const values of scanned.themes.values()) {
|
|
268
|
+
for (const name of values.keys()) names.add(name);
|
|
269
|
+
}
|
|
270
|
+
return [...names].sort();
|
|
271
|
+
}
|
|
272
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
220
273
|
const normalized = normalizePatterns(patterns);
|
|
221
274
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
222
275
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -227,48 +280,58 @@ async function scanCss(patterns, exclude, selectors) {
|
|
|
227
280
|
css = await (0, import_promises.readFile)(file, "utf8");
|
|
228
281
|
} catch (err) {
|
|
229
282
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
230
|
-
return
|
|
283
|
+
return null;
|
|
231
284
|
}
|
|
232
|
-
return {
|
|
285
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
233
286
|
})
|
|
234
287
|
);
|
|
235
288
|
const declarations = /* @__PURE__ */ new Map();
|
|
236
289
|
const properties = /* @__PURE__ */ new Map();
|
|
290
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
237
291
|
for (const result of perFile) {
|
|
292
|
+
if (!result) continue;
|
|
238
293
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
239
294
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
295
|
+
for (const [theme, values] of result.themes) {
|
|
296
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
297
|
+
}
|
|
240
298
|
}
|
|
241
|
-
return { declarations, properties };
|
|
242
|
-
}
|
|
243
|
-
var
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
299
|
+
return { declarations, properties, themes: themeValues };
|
|
300
|
+
}
|
|
301
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
302
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
303
|
+
function readAccess(text, from) {
|
|
304
|
+
ACCESS_RE.lastIndex = from;
|
|
305
|
+
const match = ACCESS_RE.exec(text);
|
|
306
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
307
|
+
}
|
|
308
|
+
function extractUsage(text, into) {
|
|
309
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
310
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
311
|
+
if (!first) continue;
|
|
312
|
+
into.keys.add(first.key);
|
|
313
|
+
const second = readAccess(text, first.end);
|
|
314
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
315
|
+
else into.wholeKeys.add(first.key);
|
|
247
316
|
}
|
|
248
317
|
}
|
|
249
|
-
async function
|
|
318
|
+
async function scanUsage(patterns, exclude) {
|
|
250
319
|
const normalized = normalizePatterns(patterns);
|
|
251
320
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
252
321
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
253
|
-
const
|
|
322
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
323
|
+
const texts = await Promise.all(
|
|
254
324
|
files.map(async (file) => {
|
|
255
|
-
const used = /* @__PURE__ */ new Set();
|
|
256
|
-
let text;
|
|
257
325
|
try {
|
|
258
|
-
|
|
326
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
259
327
|
} catch (err) {
|
|
260
328
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
261
|
-
return
|
|
329
|
+
return "";
|
|
262
330
|
}
|
|
263
|
-
extractUsedKeys(text, used);
|
|
264
|
-
return used;
|
|
265
331
|
})
|
|
266
332
|
);
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
for (const key of used) all.add(key);
|
|
270
|
-
}
|
|
271
|
-
return all;
|
|
333
|
+
for (const text of texts) extractUsage(text, usage);
|
|
334
|
+
return usage;
|
|
272
335
|
}
|
|
273
336
|
|
|
274
337
|
// src/generator.ts
|
|
@@ -331,6 +394,12 @@ function formatKey(key, naming = "camelCase") {
|
|
|
331
394
|
function computeKey(cssVarName, prefix, naming) {
|
|
332
395
|
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
333
396
|
}
|
|
397
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
398
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
399
|
+
const split = splitGroupKey(cssVarName);
|
|
400
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
401
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
402
|
+
}
|
|
334
403
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
335
404
|
const byKey = /* @__PURE__ */ new Map();
|
|
336
405
|
for (const name of varNames) {
|
|
@@ -349,23 +418,37 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
349
418
|
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
350
419
|
}
|
|
351
420
|
}
|
|
352
|
-
function
|
|
421
|
+
function entryMeta(name, options) {
|
|
422
|
+
const themes = [];
|
|
423
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
424
|
+
const value = values.get(name);
|
|
425
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
426
|
+
}
|
|
427
|
+
return {
|
|
428
|
+
name,
|
|
429
|
+
value: options.declarations?.get(name),
|
|
430
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
431
|
+
...themes.length > 0 ? { themes } : {}
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
function buildEntries(varNames, options) {
|
|
435
|
+
const { prefix, naming } = options;
|
|
353
436
|
const byKey = /* @__PURE__ */ new Map();
|
|
354
437
|
for (const name of varNames) {
|
|
355
438
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
356
|
-
byKey.set(key,
|
|
439
|
+
byKey.set(key, entryMeta(name, options));
|
|
357
440
|
}
|
|
358
441
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
359
442
|
}
|
|
360
|
-
function buildGroupedEntries(varNames,
|
|
443
|
+
function buildGroupedEntries(varNames, options) {
|
|
444
|
+
const { naming } = options;
|
|
361
445
|
const groupMap = /* @__PURE__ */ new Map();
|
|
362
446
|
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
363
447
|
for (const name of varNames) {
|
|
364
|
-
const
|
|
365
|
-
const syntax = properties?.get(name)?.syntax;
|
|
448
|
+
const meta = entryMeta(name, options);
|
|
366
449
|
const split = splitGroupKey(name);
|
|
367
450
|
if (!split) {
|
|
368
|
-
ungroupedMap.set(formatKey(toKey(name, naming), naming),
|
|
451
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
369
452
|
continue;
|
|
370
453
|
}
|
|
371
454
|
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
@@ -375,7 +458,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
375
458
|
leafMap = /* @__PURE__ */ new Map();
|
|
376
459
|
groupMap.set(groupKey, leafMap);
|
|
377
460
|
}
|
|
378
|
-
leafMap.set(leafKey,
|
|
461
|
+
leafMap.set(leafKey, meta);
|
|
379
462
|
}
|
|
380
463
|
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
381
464
|
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
@@ -398,6 +481,9 @@ function unquoteCssString(value) {
|
|
|
398
481
|
function formatSyntaxComment(syntax, indent = " ") {
|
|
399
482
|
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
400
483
|
}
|
|
484
|
+
function formatThemeComment(theme, value, indent = " ") {
|
|
485
|
+
return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
|
|
486
|
+
}
|
|
401
487
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
402
488
|
function parseEnumSyntax(syntax) {
|
|
403
489
|
const unquoted = unquoteCssString(syntax).trim();
|
|
@@ -428,14 +514,15 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
428
514
|
return blocks;
|
|
429
515
|
}
|
|
430
516
|
function renderEntryLines(entries, indent, lineFor) {
|
|
431
|
-
return entries.flatMap(({ key, name, value, syntax }) => [
|
|
517
|
+
return entries.flatMap(({ key, name, value, syntax, themes }) => [
|
|
432
518
|
...value ? [formatDefaultComment(value, indent)] : [],
|
|
519
|
+
...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
|
|
433
520
|
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
434
521
|
`${indent}${lineFor(key, name)}`
|
|
435
522
|
]);
|
|
436
523
|
}
|
|
437
|
-
function renderGroupedBlock(varNames,
|
|
438
|
-
const { groups, ungrouped } = buildGroupedEntries(varNames,
|
|
524
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
525
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
439
526
|
const lines = [];
|
|
440
527
|
for (const group of groups) {
|
|
441
528
|
lines.push(`${indent}${group.key}: {`);
|
|
@@ -452,21 +539,55 @@ function assertGroupPrefixCompatible(prefix, group) {
|
|
|
452
539
|
}
|
|
453
540
|
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
454
541
|
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
455
|
-
function
|
|
456
|
-
|
|
457
|
-
|
|
542
|
+
function normalizeOptions(args) {
|
|
543
|
+
const [first] = args;
|
|
544
|
+
if (first !== null && typeof first === "object") return first;
|
|
545
|
+
const [prefix, naming, declarations, group, properties] = args;
|
|
546
|
+
return { prefix, naming, declarations, group, properties };
|
|
547
|
+
}
|
|
548
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
549
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
550
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
551
|
+
}
|
|
552
|
+
function emittedNames(varNames, options) {
|
|
553
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
554
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
555
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
556
|
+
}
|
|
557
|
+
function renderRefType(varNames, options) {
|
|
558
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
559
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
560
|
+
}
|
|
561
|
+
var HELPERS_JS = [
|
|
562
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
563
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
564
|
+
"}",
|
|
565
|
+
"",
|
|
566
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
567
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
568
|
+
"}"
|
|
569
|
+
];
|
|
570
|
+
var HELPERS_DTS = [
|
|
571
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
572
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
573
|
+
];
|
|
574
|
+
function generateJs(varNames, ...args) {
|
|
575
|
+
const options = normalizeOptions(args);
|
|
576
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
458
577
|
return [
|
|
459
578
|
"// generated \u2014 do not edit",
|
|
460
579
|
"export const cssVars = {",
|
|
461
580
|
...entries,
|
|
462
581
|
"};",
|
|
582
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
463
583
|
""
|
|
464
584
|
].join("\n");
|
|
465
585
|
}
|
|
466
|
-
function generateDeclaration(varNames,
|
|
467
|
-
|
|
468
|
-
const entries =
|
|
469
|
-
const blocks = buildTailBlocks(varNames, group, properties);
|
|
586
|
+
function generateDeclaration(varNames, ...args) {
|
|
587
|
+
const options = normalizeOptions(args);
|
|
588
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
589
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
590
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
470
591
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
471
592
|
return [
|
|
472
593
|
"export declare const cssVars: {",
|
|
@@ -476,6 +597,66 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
|
|
|
476
597
|
""
|
|
477
598
|
].join("\n");
|
|
478
599
|
}
|
|
600
|
+
var TOKEN_TYPES = {
|
|
601
|
+
"<color>": "color",
|
|
602
|
+
"<length>": "dimension",
|
|
603
|
+
"<length-percentage>": "dimension",
|
|
604
|
+
"<number>": "number",
|
|
605
|
+
"<integer>": "number",
|
|
606
|
+
"<time>": "duration"
|
|
607
|
+
};
|
|
608
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
609
|
+
function generateTokens(varNames, options = {}) {
|
|
610
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
611
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
612
|
+
const meta = entryMeta(name, options);
|
|
613
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
614
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
615
|
+
});
|
|
616
|
+
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
617
|
+
const resolve2 = (value) => {
|
|
618
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
619
|
+
return target ? `{${target.join(".")}}` : value;
|
|
620
|
+
};
|
|
621
|
+
const root = {};
|
|
622
|
+
for (const { meta, value, path } of tokens) {
|
|
623
|
+
const token = { $value: resolve2(value) };
|
|
624
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
625
|
+
if (type) token.$type = type;
|
|
626
|
+
if (meta.themes) {
|
|
627
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
|
|
628
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
629
|
+
}
|
|
630
|
+
const [key, leaf] = path;
|
|
631
|
+
if (leaf === void 0) {
|
|
632
|
+
root[key] = token;
|
|
633
|
+
} else {
|
|
634
|
+
const group = root[key] ?? (root[key] = {});
|
|
635
|
+
group[leaf] = token;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// src/prune.ts
|
|
642
|
+
function assertPruneCompatible(options) {
|
|
643
|
+
if (options.prune && !options.usage) {
|
|
644
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
function isUsed(name, usage, options) {
|
|
648
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
649
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
650
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
651
|
+
}
|
|
652
|
+
function partitionUnused(names, usage, options) {
|
|
653
|
+
const used = [];
|
|
654
|
+
const unused = [];
|
|
655
|
+
for (const name of names) {
|
|
656
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
657
|
+
}
|
|
658
|
+
return { used, unused };
|
|
659
|
+
}
|
|
479
660
|
|
|
480
661
|
// src/unplugin.ts
|
|
481
662
|
var VIRTUAL_ID = "css-typed-vars/vars";
|
|
@@ -484,25 +665,37 @@ function getDtsPath(options) {
|
|
|
484
665
|
if (options.dts === false) return null;
|
|
485
666
|
return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
|
|
486
667
|
}
|
|
668
|
+
function outputFiles(options, names, generatorOptions) {
|
|
669
|
+
const files = [];
|
|
670
|
+
const dtsPath = getDtsPath(options);
|
|
671
|
+
if (dtsPath) files.push([dtsPath, generateDeclaration(names, generatorOptions)]);
|
|
672
|
+
if (options.tokens) files.push([(0, import_node_path.resolve)(process.cwd(), options.tokens), generateTokens(names, generatorOptions)]);
|
|
673
|
+
return files;
|
|
674
|
+
}
|
|
487
675
|
var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
488
|
-
|
|
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
|
-
}
|
|
676
|
+
assertPruneCompatible(options);
|
|
492
677
|
let cachedScan = null;
|
|
493
|
-
const scan = () => scanCss(options.input, options.exclude, options.selectors);
|
|
678
|
+
const scan = () => scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
494
679
|
const applyPrune = async (names) => {
|
|
495
680
|
if (!options.prune) return names;
|
|
496
|
-
const
|
|
497
|
-
const
|
|
498
|
-
const unused = names.filter((name) => !isUsed(name));
|
|
681
|
+
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
682
|
+
const { used, unused } = partitionUnused(names, usage, options);
|
|
499
683
|
if (unused.length > 0) {
|
|
500
684
|
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
501
685
|
}
|
|
502
|
-
return
|
|
686
|
+
return used;
|
|
503
687
|
};
|
|
504
|
-
const
|
|
505
|
-
|
|
688
|
+
const generatorOptions = ({ declarations, properties, themes }) => ({
|
|
689
|
+
prefix: options.prefix,
|
|
690
|
+
naming: options.naming,
|
|
691
|
+
declarations,
|
|
692
|
+
group: options.group,
|
|
693
|
+
properties,
|
|
694
|
+
helpers: options.helpers,
|
|
695
|
+
themes
|
|
696
|
+
});
|
|
697
|
+
const resolveNames = async (scanned) => {
|
|
698
|
+
const names = collectVarNames(scanned);
|
|
506
699
|
warnOnCollisions(names, options.prefix, options.naming);
|
|
507
700
|
return applyPrune(names);
|
|
508
701
|
};
|
|
@@ -518,16 +711,17 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
518
711
|
const myGeneration = ++generation;
|
|
519
712
|
const scanPromise = scan();
|
|
520
713
|
cachedScan = scanPromise;
|
|
521
|
-
const
|
|
714
|
+
const scanned = await scanPromise;
|
|
522
715
|
if (myGeneration !== generation) return;
|
|
523
|
-
const names = await resolveNames(
|
|
716
|
+
const names = await resolveNames(scanned);
|
|
524
717
|
if (myGeneration !== generation) return;
|
|
525
|
-
const
|
|
526
|
-
if (
|
|
527
|
-
const content = generateDeclaration(names, options.prefix, options.naming, declarations, options.group, properties);
|
|
718
|
+
const files = outputFiles(options, names, generatorOptions(scanned));
|
|
719
|
+
if (files.length > 0) {
|
|
528
720
|
writeQueue = writeQueue.then(async () => {
|
|
529
|
-
|
|
530
|
-
|
|
721
|
+
for (const [path, content] of files) {
|
|
722
|
+
if (myGeneration !== generation) return;
|
|
723
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
724
|
+
}
|
|
531
725
|
}).catch(console.error);
|
|
532
726
|
await writeQueue;
|
|
533
727
|
}
|
|
@@ -553,20 +747,20 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
553
747
|
},
|
|
554
748
|
async buildStart() {
|
|
555
749
|
cachedScan = scan();
|
|
556
|
-
const
|
|
557
|
-
const names = await resolveNames(
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
|
|
750
|
+
const scanned = await cachedScan;
|
|
751
|
+
const names = await resolveNames(scanned);
|
|
752
|
+
for (const [path, content] of outputFiles(options, names, generatorOptions(scanned))) {
|
|
753
|
+
await (0, import_promises2.writeFile)(path, content, "utf8");
|
|
754
|
+
}
|
|
561
755
|
},
|
|
562
756
|
resolveId(id) {
|
|
563
757
|
if (id === VIRTUAL_ID) return RESOLVED_ID;
|
|
564
758
|
},
|
|
565
759
|
async load(id) {
|
|
566
760
|
if (id === RESOLVED_ID) {
|
|
567
|
-
const
|
|
568
|
-
const names = await applyPrune(
|
|
569
|
-
return generateJs(names,
|
|
761
|
+
const scanned = await (cachedScan ?? scan());
|
|
762
|
+
const names = await applyPrune(collectVarNames(scanned));
|
|
763
|
+
return generateJs(names, generatorOptions(scanned));
|
|
570
764
|
}
|
|
571
765
|
}
|
|
572
766
|
};
|
package/dist/unplugin.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as unplugin from 'unplugin';
|
|
2
|
-
import { N as NamingConvention } from './generator-
|
|
2
|
+
import { N as NamingConvention } from './generator-C1iVNsry.cjs';
|
|
3
3
|
|
|
4
4
|
interface Options {
|
|
5
5
|
input: string | string[];
|
|
@@ -10,16 +10,26 @@ interface Options {
|
|
|
10
10
|
* - `false`: skip writing
|
|
11
11
|
*/
|
|
12
12
|
dts?: string | false;
|
|
13
|
+
/** Also write a W3C design tokens (DTCG) JSON file to this path, relative to project root. */
|
|
14
|
+
tokens?: string;
|
|
13
15
|
exclude?: string | string[];
|
|
14
16
|
prefix?: string;
|
|
15
17
|
naming?: NamingConvention;
|
|
16
18
|
selectors?: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Theme name -> selector (`'[data-theme="dark"]'`) or `@media` prelude
|
|
21
|
+
* (`'@media (prefers-color-scheme: dark)'`). Each theme's values are emitted as
|
|
22
|
+
* `@theme <name> <value>` JSDoc tags, and kept out of the default value.
|
|
23
|
+
*/
|
|
24
|
+
themes?: Record<string, string>;
|
|
17
25
|
group?: boolean;
|
|
18
|
-
/** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage
|
|
26
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
19
27
|
prune?: boolean;
|
|
20
28
|
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
|
|
21
29
|
usage?: string | string[];
|
|
22
30
|
usageExclude?: string | string[];
|
|
31
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
32
|
+
helpers?: boolean;
|
|
23
33
|
}
|
|
24
34
|
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
|
25
35
|
|
package/dist/unplugin.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as unplugin from 'unplugin';
|
|
2
|
-
import { N as NamingConvention } from './generator-
|
|
2
|
+
import { N as NamingConvention } from './generator-C1iVNsry.js';
|
|
3
3
|
|
|
4
4
|
interface Options {
|
|
5
5
|
input: string | string[];
|
|
@@ -10,16 +10,26 @@ interface Options {
|
|
|
10
10
|
* - `false`: skip writing
|
|
11
11
|
*/
|
|
12
12
|
dts?: string | false;
|
|
13
|
+
/** Also write a W3C design tokens (DTCG) JSON file to this path, relative to project root. */
|
|
14
|
+
tokens?: string;
|
|
13
15
|
exclude?: string | string[];
|
|
14
16
|
prefix?: string;
|
|
15
17
|
naming?: NamingConvention;
|
|
16
18
|
selectors?: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Theme name -> selector (`'[data-theme="dark"]'`) or `@media` prelude
|
|
21
|
+
* (`'@media (prefers-color-scheme: dark)'`). Each theme's values are emitted as
|
|
22
|
+
* `@theme <name> <value>` JSDoc tags, and kept out of the default value.
|
|
23
|
+
*/
|
|
24
|
+
themes?: Record<string, string>;
|
|
17
25
|
group?: boolean;
|
|
18
|
-
/** Prune generated vars with no detected `cssVars.<key>` usage. Requires `usage
|
|
26
|
+
/** Prune generated vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>`) usage. Requires `usage`. */
|
|
19
27
|
prune?: boolean;
|
|
20
28
|
/** Glob(s) of source files to scan for `cssVars` usage. Required when `prune` is true. */
|
|
21
29
|
usage?: string | string[];
|
|
22
30
|
usageExclude?: string | string[];
|
|
31
|
+
/** Also emit the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers. */
|
|
32
|
+
helpers?: boolean;
|
|
23
33
|
}
|
|
24
34
|
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
|
25
35
|
|