css-typed-vars 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -5
- package/dist/chunk-6YWE4A6S.js +691 -0
- package/dist/chunk-HBUSLYYB.js +127 -0
- package/dist/chunk-PLO2JWR7.js +88 -0
- package/dist/cli.cjs +480 -57
- package/dist/cli.js +51 -9
- package/dist/esbuild.cjs +433 -60
- 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 +452 -47
- package/dist/index.d.cts +27 -6
- package/dist/index.d.ts +27 -6
- package/dist/index.js +14 -2
- package/dist/rollup.cjs +433 -60
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +433 -60
- package/dist/unplugin.d.cts +17 -1
- package/dist/unplugin.d.ts +17 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +433 -60
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +433 -60
- package/dist/webpack.d.cts +1 -1
- package/dist/webpack.d.ts +1 -1
- package/dist/webpack.js +2 -2
- package/package.json +6 -2
- package/dist/chunk-H3T6RMQQ.js +0 -51
- package/dist/chunk-JDZAH2YQ.js +0 -320
- package/dist/chunk-YBZGHG2G.js +0 -91
- package/dist/generator-t6h8Ic7V.d.cts +0 -6
- package/dist/generator-t6h8Ic7V.d.ts +0 -6
package/dist/cli.cjs
CHANGED
|
@@ -157,37 +157,119 @@ 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
|
-
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
174
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
175
|
-
}
|
|
176
|
-
openRegex.lastIndex = start + block.length + 1;
|
|
176
|
+
const end = start + block.length + 1;
|
|
177
|
+
onBlock(block, [start, end]);
|
|
178
|
+
openRegex.lastIndex = end;
|
|
177
179
|
}
|
|
178
180
|
}
|
|
179
181
|
}
|
|
180
|
-
|
|
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;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
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 };
|
|
230
|
+
}
|
|
231
|
+
var PROPERTY_DESCRIPTORS = [
|
|
232
|
+
["syntax", "syntax"],
|
|
233
|
+
["inherits", "inherits"],
|
|
234
|
+
["initial-value", "initialValue"]
|
|
235
|
+
];
|
|
236
|
+
function parsePropertyRules(css) {
|
|
237
|
+
const stripped = stripComments(css);
|
|
238
|
+
const rules = /* @__PURE__ */ new Map();
|
|
239
|
+
const openRegex = /@property\s+(--[\w-]+)\s*\{/g;
|
|
240
|
+
let match;
|
|
241
|
+
while (match = openRegex.exec(stripped)) {
|
|
242
|
+
const name = match[1];
|
|
243
|
+
const start = match.index + match[0].length;
|
|
244
|
+
const block = extractBlock(stripped, start);
|
|
245
|
+
const masked = maskQuotedContent(block);
|
|
246
|
+
const rule = {};
|
|
247
|
+
for (const [descriptor, key] of PROPERTY_DESCRIPTORS) {
|
|
248
|
+
const descRegex = new RegExp(`(?:^|[;{\\s])${descriptor}(?=\\s*:)`);
|
|
249
|
+
const descMatch = descRegex.exec(masked);
|
|
250
|
+
if (!descMatch) continue;
|
|
251
|
+
const nameEnd = descMatch.index + descMatch[0].length;
|
|
252
|
+
const colonIndex = block.indexOf(":", nameEnd);
|
|
253
|
+
rule[key] = extractValue(block, colonIndex + 1);
|
|
254
|
+
}
|
|
255
|
+
if (Object.keys(rule).length > 0) rules.set(name, rule);
|
|
256
|
+
openRegex.lastIndex = start + block.length + 1;
|
|
257
|
+
}
|
|
258
|
+
return rules;
|
|
184
259
|
}
|
|
185
260
|
|
|
186
261
|
// src/scanner.ts
|
|
187
262
|
function normalizePatterns(patterns) {
|
|
188
263
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
189
264
|
}
|
|
190
|
-
|
|
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 = {}) {
|
|
191
273
|
const normalized = normalizePatterns(patterns);
|
|
192
274
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
193
275
|
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -198,18 +280,58 @@ async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
|
198
280
|
css = await (0, import_promises.readFile)(file, "utf8");
|
|
199
281
|
} catch (err) {
|
|
200
282
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
201
|
-
return
|
|
283
|
+
return null;
|
|
202
284
|
}
|
|
203
|
-
return
|
|
285
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
204
286
|
})
|
|
205
287
|
);
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
288
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
289
|
+
const properties = /* @__PURE__ */ new Map();
|
|
290
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
291
|
+
for (const result of perFile) {
|
|
292
|
+
if (!result) continue;
|
|
293
|
+
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
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);
|
|
210
297
|
}
|
|
211
298
|
}
|
|
212
|
-
return
|
|
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);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
async function scanUsage(patterns, exclude) {
|
|
319
|
+
const normalized = normalizePatterns(patterns);
|
|
320
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
321
|
+
const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
|
|
322
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
323
|
+
const texts = await Promise.all(
|
|
324
|
+
files.map(async (file) => {
|
|
325
|
+
try {
|
|
326
|
+
return await (0, import_promises.readFile)(file, "utf8");
|
|
327
|
+
} catch (err) {
|
|
328
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
329
|
+
return "";
|
|
330
|
+
}
|
|
331
|
+
})
|
|
332
|
+
);
|
|
333
|
+
for (const text of texts) extractUsage(text, usage);
|
|
334
|
+
return usage;
|
|
213
335
|
}
|
|
214
336
|
|
|
215
337
|
// src/generator.ts
|
|
@@ -224,10 +346,19 @@ function convertCase(value, naming) {
|
|
|
224
346
|
if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
|
|
225
347
|
return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
|
|
226
348
|
}
|
|
227
|
-
function
|
|
228
|
-
const key = convertCase(
|
|
349
|
+
function toKeyFragment(fragment, naming = "camelCase") {
|
|
350
|
+
const key = convertCase(fragment, naming);
|
|
229
351
|
return naming !== "kebab" && /^\d/.test(key) ? `_${key}` : key;
|
|
230
352
|
}
|
|
353
|
+
function toKey(cssVarName, naming = "camelCase") {
|
|
354
|
+
return toKeyFragment(cssVarName.replace(/^--/, ""), naming);
|
|
355
|
+
}
|
|
356
|
+
function splitGroupKey(cssVarName) {
|
|
357
|
+
const stripped = cssVarName.replace(/^--/, "");
|
|
358
|
+
const dashIndex = stripped.indexOf("-");
|
|
359
|
+
if (dashIndex === -1) return null;
|
|
360
|
+
return { group: stripped.slice(0, dashIndex), rest: stripped.slice(dashIndex + 1) };
|
|
361
|
+
}
|
|
231
362
|
var LINE_SEPARATOR_CHAR = String.fromCharCode(8232);
|
|
232
363
|
var PARAGRAPH_SEPARATOR_CHAR = String.fromCharCode(8233);
|
|
233
364
|
var SINGLE_QUOTE_ESCAPES = {};
|
|
@@ -260,6 +391,15 @@ function formatKey(key, naming = "camelCase") {
|
|
|
260
391
|
if (naming === "kebab") return `'${key}'`;
|
|
261
392
|
return key;
|
|
262
393
|
}
|
|
394
|
+
function computeKey(cssVarName, prefix, naming) {
|
|
395
|
+
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
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
|
+
}
|
|
263
403
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
264
404
|
const byKey = /* @__PURE__ */ new Map();
|
|
265
405
|
for (const name of varNames) {
|
|
@@ -278,76 +418,318 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
278
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.`);
|
|
279
419
|
}
|
|
280
420
|
}
|
|
281
|
-
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;
|
|
282
436
|
const byKey = /* @__PURE__ */ new Map();
|
|
283
437
|
for (const name of varNames) {
|
|
284
438
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
285
|
-
byKey.set(key,
|
|
439
|
+
byKey.set(key, entryMeta(name, options));
|
|
286
440
|
}
|
|
287
441
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
288
442
|
}
|
|
289
|
-
function
|
|
290
|
-
|
|
443
|
+
function buildGroupedEntries(varNames, options) {
|
|
444
|
+
const { naming } = options;
|
|
445
|
+
const groupMap = /* @__PURE__ */ new Map();
|
|
446
|
+
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
447
|
+
for (const name of varNames) {
|
|
448
|
+
const meta = entryMeta(name, options);
|
|
449
|
+
const split = splitGroupKey(name);
|
|
450
|
+
if (!split) {
|
|
451
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
455
|
+
const leafKey = formatKey(toKeyFragment(split.rest, naming), naming);
|
|
456
|
+
let leafMap = groupMap.get(groupKey);
|
|
457
|
+
if (!leafMap) {
|
|
458
|
+
leafMap = /* @__PURE__ */ new Map();
|
|
459
|
+
groupMap.set(groupKey, leafMap);
|
|
460
|
+
}
|
|
461
|
+
leafMap.set(leafKey, meta);
|
|
462
|
+
}
|
|
463
|
+
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
464
|
+
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
465
|
+
key,
|
|
466
|
+
entries: [...leafMap].map(([key2, entry]) => ({ key: key2, ...entry }))
|
|
467
|
+
}));
|
|
468
|
+
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
469
|
+
return { groups, ungrouped };
|
|
470
|
+
}
|
|
471
|
+
function formatDefaultComment(value, indent = " ") {
|
|
472
|
+
return `${indent}/** @default ${value.replace(/\*\//g, "*\\/")} */`;
|
|
473
|
+
}
|
|
474
|
+
function unquoteCssString(value) {
|
|
475
|
+
const quote = value[0];
|
|
476
|
+
if ((quote === '"' || quote === "'") && value[value.length - 1] === quote) {
|
|
477
|
+
return value.slice(1, -1);
|
|
478
|
+
}
|
|
479
|
+
return value;
|
|
480
|
+
}
|
|
481
|
+
function formatSyntaxComment(syntax, indent = " ") {
|
|
482
|
+
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
291
483
|
}
|
|
292
|
-
function
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
484
|
+
function formatThemeComment(theme, value, indent = " ") {
|
|
485
|
+
return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
|
|
486
|
+
}
|
|
487
|
+
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
488
|
+
function parseEnumSyntax(syntax) {
|
|
489
|
+
const unquoted = unquoteCssString(syntax).trim();
|
|
490
|
+
if (!ENUM_SYNTAX_RE.test(unquoted)) return null;
|
|
491
|
+
return unquoted.split("|").map((v) => v.trim());
|
|
492
|
+
}
|
|
493
|
+
function syntaxTypeName(cssVarName) {
|
|
494
|
+
const pascal = convertCase(cssVarName.replace(/^--/, ""), "pascal");
|
|
495
|
+
return (/^\d/.test(pascal) ? `_${pascal}` : pascal) + "Syntax";
|
|
496
|
+
}
|
|
497
|
+
function buildSyntaxTypes(varNames, properties) {
|
|
498
|
+
if (!properties) return [];
|
|
499
|
+
const byName = /* @__PURE__ */ new Map();
|
|
500
|
+
for (const name of varNames) {
|
|
501
|
+
const values = parseEnumSyntax(properties.get(name)?.syntax ?? "");
|
|
502
|
+
if (values) byName.set(syntaxTypeName(name), values);
|
|
503
|
+
}
|
|
504
|
+
return [...byName].map(([name, values]) => ({ name, values }));
|
|
505
|
+
}
|
|
506
|
+
function renderSyntaxTypeLines(types) {
|
|
507
|
+
return types.map(({ name, values }) => `export type ${name} = ${values.map((v) => `'${escapeSingleQuoted(v)}'`).join(" | ")};`);
|
|
508
|
+
}
|
|
509
|
+
function buildTailBlocks(varNames, group, properties) {
|
|
510
|
+
const blocks = [];
|
|
511
|
+
if (!group) blocks.push(["export type CssVarName = keyof typeof cssVars;"]);
|
|
512
|
+
const syntaxLines = renderSyntaxTypeLines(buildSyntaxTypes(varNames, properties));
|
|
513
|
+
if (syntaxLines.length > 0) blocks.push(syntaxLines);
|
|
514
|
+
return blocks;
|
|
515
|
+
}
|
|
516
|
+
function renderEntryLines(entries, indent, lineFor) {
|
|
517
|
+
return entries.flatMap(({ key, name, value, syntax, themes }) => [
|
|
518
|
+
...value ? [formatDefaultComment(value, indent)] : [],
|
|
519
|
+
...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
|
|
520
|
+
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
521
|
+
`${indent}${lineFor(key, name)}`
|
|
296
522
|
]);
|
|
523
|
+
}
|
|
524
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
525
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
526
|
+
const lines = [];
|
|
527
|
+
for (const group of groups) {
|
|
528
|
+
lines.push(`${indent}${group.key}: {`);
|
|
529
|
+
lines.push(...renderEntryLines(group.entries, indent + " ", lineFor));
|
|
530
|
+
lines.push(`${indent}}${closeSuffix}`);
|
|
531
|
+
}
|
|
532
|
+
lines.push(...renderEntryLines(ungrouped, indent, lineFor));
|
|
533
|
+
return lines;
|
|
534
|
+
}
|
|
535
|
+
function assertGroupPrefixCompatible(prefix, group) {
|
|
536
|
+
if (group && prefix) {
|
|
537
|
+
throw new Error('css-typed-vars: the "group" option cannot be combined with "prefix".');
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
541
|
+
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
542
|
+
function normalizeOptions(args2) {
|
|
543
|
+
const [first] = args2;
|
|
544
|
+
if (first !== null && typeof first === "object") return first;
|
|
545
|
+
const [prefix, naming, declarations, group, properties] = args2;
|
|
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_TS = [
|
|
562
|
+
"export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
|
|
563
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
564
|
+
"}",
|
|
565
|
+
"",
|
|
566
|
+
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
567
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
568
|
+
"}"
|
|
569
|
+
];
|
|
570
|
+
var HELPERS_JS = [
|
|
571
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
572
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
573
|
+
"}",
|
|
574
|
+
"",
|
|
575
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
576
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
577
|
+
"}"
|
|
578
|
+
];
|
|
579
|
+
var HELPERS_DTS = [
|
|
580
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
581
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
582
|
+
];
|
|
583
|
+
function generateCode(varNames, ...args2) {
|
|
584
|
+
const options = normalizeOptions(args2);
|
|
585
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
586
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
587
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
|
|
588
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
297
589
|
return [
|
|
298
590
|
"// generated \u2014 do not edit",
|
|
299
591
|
"export const cssVars = {",
|
|
300
592
|
...entries,
|
|
301
593
|
"} as const;",
|
|
302
|
-
"",
|
|
303
|
-
"export type CssVarName = keyof typeof cssVars;",
|
|
594
|
+
...tailBody.length > 0 ? ["", ...tailBody] : [],
|
|
304
595
|
""
|
|
305
596
|
].join("\n");
|
|
306
597
|
}
|
|
307
|
-
function generateJs(varNames,
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
` ${key}: 'var(${name})',`
|
|
311
|
-
]);
|
|
598
|
+
function generateJs(varNames, ...args2) {
|
|
599
|
+
const options = normalizeOptions(args2);
|
|
600
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
312
601
|
return [
|
|
313
602
|
"// generated \u2014 do not edit",
|
|
314
603
|
"export const cssVars = {",
|
|
315
604
|
...entries,
|
|
316
605
|
"};",
|
|
606
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
317
607
|
""
|
|
318
608
|
].join("\n");
|
|
319
609
|
}
|
|
320
|
-
function generateDeclaration(varNames,
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
]);
|
|
610
|
+
function generateDeclaration(varNames, ...args2) {
|
|
611
|
+
const options = normalizeOptions(args2);
|
|
612
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
613
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
614
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
615
|
+
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
325
616
|
return [
|
|
326
617
|
"export declare const cssVars: {",
|
|
327
618
|
...entries,
|
|
328
619
|
"};",
|
|
329
|
-
|
|
620
|
+
...tailBody,
|
|
330
621
|
""
|
|
331
622
|
].join("\n");
|
|
332
623
|
}
|
|
624
|
+
var TOKEN_TYPES = {
|
|
625
|
+
"<color>": "color",
|
|
626
|
+
"<length>": "dimension",
|
|
627
|
+
"<length-percentage>": "dimension",
|
|
628
|
+
"<number>": "number",
|
|
629
|
+
"<integer>": "number",
|
|
630
|
+
"<time>": "duration"
|
|
631
|
+
};
|
|
632
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
633
|
+
function generateTokens(varNames, options = {}) {
|
|
634
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
635
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
636
|
+
const meta = entryMeta(name, options);
|
|
637
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
638
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
639
|
+
});
|
|
640
|
+
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
641
|
+
const resolve3 = (value) => {
|
|
642
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
643
|
+
return target ? `{${target.join(".")}}` : value;
|
|
644
|
+
};
|
|
645
|
+
const root = {};
|
|
646
|
+
for (const { meta, value, path } of tokens) {
|
|
647
|
+
const token = { $value: resolve3(value) };
|
|
648
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
649
|
+
if (type) token.$type = type;
|
|
650
|
+
if (meta.themes) {
|
|
651
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve3(themeValue)]));
|
|
652
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
653
|
+
}
|
|
654
|
+
const [key, leaf] = path;
|
|
655
|
+
if (leaf === void 0) {
|
|
656
|
+
root[key] = token;
|
|
657
|
+
} else {
|
|
658
|
+
const group = root[key] ?? (root[key] = {});
|
|
659
|
+
group[leaf] = token;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// src/prune.ts
|
|
666
|
+
function assertPruneCompatible(options) {
|
|
667
|
+
if (options.prune && !options.usage) {
|
|
668
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
function isUsed(name, usage, options) {
|
|
672
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
673
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
674
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
675
|
+
}
|
|
676
|
+
function partitionUnused(names, usage, options) {
|
|
677
|
+
const used = [];
|
|
678
|
+
const unused = [];
|
|
679
|
+
for (const name of names) {
|
|
680
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
681
|
+
}
|
|
682
|
+
return { used, unused };
|
|
683
|
+
}
|
|
333
684
|
|
|
334
685
|
// src/index.ts
|
|
686
|
+
async function findUnusedVars(options) {
|
|
687
|
+
if (!options.usage) throw new Error('css-typed-vars: findUnusedVars requires "usage" (glob(s) of source files to scan).');
|
|
688
|
+
const [scanned, usage] = await Promise.all([
|
|
689
|
+
scanCss(options.input, options.exclude, options.selectors, options.themes),
|
|
690
|
+
scanUsage(options.usage, options.usageExclude)
|
|
691
|
+
]);
|
|
692
|
+
const names = collectVarNames(scanned);
|
|
693
|
+
return partitionUnused(names, usage, options).unused;
|
|
694
|
+
}
|
|
335
695
|
async function computeOutputs(options) {
|
|
336
|
-
|
|
337
|
-
const
|
|
696
|
+
assertPruneCompatible(options);
|
|
697
|
+
const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
698
|
+
const { declarations, properties } = scanned;
|
|
699
|
+
let names = collectVarNames(scanned);
|
|
338
700
|
if (names.length === 0) {
|
|
339
701
|
console.warn("css-typed-vars: no CSS custom properties found.");
|
|
340
702
|
}
|
|
341
703
|
warnOnCollisions(names, options.prefix, options.naming);
|
|
704
|
+
if (options.prune) {
|
|
705
|
+
const usage = await scanUsage(options.usage, options.usageExclude);
|
|
706
|
+
const { used, unused } = partitionUnused(names, usage, options);
|
|
707
|
+
if (unused.length > 0) {
|
|
708
|
+
console.warn(`css-typed-vars: pruned ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
709
|
+
}
|
|
710
|
+
names = used;
|
|
711
|
+
}
|
|
342
712
|
const outPath = (0, import_node_path.resolve)(options.output);
|
|
713
|
+
const generatorOptions = {
|
|
714
|
+
prefix: options.prefix,
|
|
715
|
+
naming: options.naming,
|
|
716
|
+
declarations,
|
|
717
|
+
group: options.group,
|
|
718
|
+
properties,
|
|
719
|
+
helpers: options.helpers,
|
|
720
|
+
themes: scanned.themes
|
|
721
|
+
};
|
|
722
|
+
if (/\.json$/i.test(options.output)) {
|
|
723
|
+
return { outPath, content: generateTokens(names, generatorOptions) };
|
|
724
|
+
}
|
|
343
725
|
const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
|
|
344
726
|
if (jsExtMatch) {
|
|
345
|
-
const content = generateJs(names,
|
|
727
|
+
const content = generateJs(names, generatorOptions);
|
|
346
728
|
const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
|
|
347
|
-
const dtsContent = generateDeclaration(names,
|
|
729
|
+
const dtsContent = generateDeclaration(names, generatorOptions);
|
|
348
730
|
return { outPath, content, dtsPath, dtsContent };
|
|
349
731
|
}
|
|
350
|
-
return { outPath, content: generateCode(names,
|
|
732
|
+
return { outPath, content: generateCode(names, generatorOptions) };
|
|
351
733
|
}
|
|
352
734
|
async function generate(options) {
|
|
353
735
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
@@ -386,6 +768,10 @@ var getArgs = (flag) => {
|
|
|
386
768
|
};
|
|
387
769
|
var watchMode = args.includes("--watch");
|
|
388
770
|
var checkMode = args.includes("--check");
|
|
771
|
+
var groupFlag = args.includes("--group");
|
|
772
|
+
var pruneFlag = args.includes("--prune");
|
|
773
|
+
var pruneCheckMode = args.includes("--prune-check");
|
|
774
|
+
var helpersFlag = args.includes("--helpers");
|
|
389
775
|
async function loadConfig() {
|
|
390
776
|
const candidates = [
|
|
391
777
|
"css-typed-vars.config.js",
|
|
@@ -410,9 +796,9 @@ async function loadConfig() {
|
|
|
410
796
|
}
|
|
411
797
|
return {};
|
|
412
798
|
}
|
|
413
|
-
async function run(
|
|
414
|
-
await generate(
|
|
415
|
-
console.log(`Generated \u2192 ${output}`);
|
|
799
|
+
async function run(options) {
|
|
800
|
+
await generate(options);
|
|
801
|
+
console.log(`Generated \u2192 ${options.output}`);
|
|
416
802
|
}
|
|
417
803
|
async function main() {
|
|
418
804
|
if (args.includes("--version") || args.includes("-v")) {
|
|
@@ -435,8 +821,23 @@ async function main() {
|
|
|
435
821
|
const naming = namingRaw;
|
|
436
822
|
const selectorArgs = getArgs("--selector");
|
|
437
823
|
const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
|
|
824
|
+
const themeArgs = getArgs("--theme");
|
|
825
|
+
for (const arg of themeArgs) {
|
|
826
|
+
if (!/^[^=]+=.+$/.test(arg)) {
|
|
827
|
+
console.error(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
|
|
828
|
+
process.exit(1);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
const themes = themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes;
|
|
832
|
+
const group = groupFlag || config.group;
|
|
833
|
+
const prune = pruneFlag || config.prune;
|
|
834
|
+
const usageArgs = getArgs("--usage");
|
|
835
|
+
const usage = usageArgs.length > 0 ? usageArgs : config.usage;
|
|
836
|
+
const usageExcludeArgs = getArgs("--usage-exclude");
|
|
837
|
+
const usageExclude = usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude;
|
|
838
|
+
const helpers = helpersFlag || config.helpers;
|
|
438
839
|
if (!input || !output) {
|
|
439
|
-
console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check]");
|
|
840
|
+
console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>]");
|
|
440
841
|
console.error("Or add a css-typed-vars.config.js file with input and output fields.");
|
|
441
842
|
process.exit(1);
|
|
442
843
|
}
|
|
@@ -444,8 +845,30 @@ async function main() {
|
|
|
444
845
|
console.error("css-typed-vars: --check cannot be combined with --watch.");
|
|
445
846
|
process.exit(1);
|
|
446
847
|
}
|
|
848
|
+
if (pruneCheckMode && (watchMode || checkMode)) {
|
|
849
|
+
console.error("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
|
|
850
|
+
process.exit(1);
|
|
851
|
+
}
|
|
852
|
+
if (group && prefix) {
|
|
853
|
+
console.error("css-typed-vars: --group cannot be combined with --prefix.");
|
|
854
|
+
process.exit(1);
|
|
855
|
+
}
|
|
856
|
+
if ((prune || pruneCheckMode) && !usage) {
|
|
857
|
+
console.error("css-typed-vars: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).");
|
|
858
|
+
process.exit(1);
|
|
859
|
+
}
|
|
860
|
+
if (pruneCheckMode) {
|
|
861
|
+
const unused = await findUnusedVars({ input, exclude, selectors, themes, prefix, naming, group, usage, usageExclude });
|
|
862
|
+
if (unused.length > 0) {
|
|
863
|
+
console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
864
|
+
process.exit(1);
|
|
865
|
+
}
|
|
866
|
+
console.log("css-typed-vars: no unused variables.");
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
const runOptions = { input, output, exclude, prefix, naming, selectors, themes, group, prune, usage, usageExclude, helpers };
|
|
447
870
|
if (checkMode) {
|
|
448
|
-
const upToDate = await checkGenerated(
|
|
871
|
+
const upToDate = await checkGenerated(runOptions);
|
|
449
872
|
if (!upToDate) {
|
|
450
873
|
console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
|
|
451
874
|
process.exit(1);
|
|
@@ -453,12 +876,12 @@ async function main() {
|
|
|
453
876
|
console.log(`css-typed-vars: "${output}" is up to date.`);
|
|
454
877
|
return;
|
|
455
878
|
}
|
|
456
|
-
await run(
|
|
879
|
+
await run(runOptions);
|
|
457
880
|
if (watchMode) {
|
|
458
881
|
const patterns = Array.isArray(input) ? input : [input];
|
|
459
882
|
const makeHandler = (label) => (file) => {
|
|
460
883
|
console.log(`${label}: ${file}`);
|
|
461
|
-
run(
|
|
884
|
+
run(runOptions).catch(console.error);
|
|
462
885
|
};
|
|
463
886
|
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
464
887
|
(0, import_chokidar.watch)(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|