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/README.md
CHANGED
|
@@ -118,6 +118,7 @@ npx css-typed-vars --input "src/styles/**/*.{css,scss}" --output src/cssVars.ts
|
|
|
118
118
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --exclude "**/vendor/**"
|
|
119
119
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prefix theme --naming snake
|
|
120
120
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.js # generates .js + .d.ts
|
|
121
|
+
npx css-typed-vars --input "src/**/*.css" --output tokens.json # W3C design tokens (DTCG) JSON
|
|
121
122
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --selector ".dark" --selector "[data-theme='dark']"
|
|
122
123
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --check # for CI: exits 1 if out of date
|
|
123
124
|
npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --group # nest keys by first name segment
|
|
@@ -128,13 +129,15 @@ npx css-typed-vars --input "src/**/*.css" --output src/cssVars.ts --prune-check
|
|
|
128
129
|
| Flag | Description |
|
|
129
130
|
|------|-------------|
|
|
130
131
|
| `--input` | Glob pattern for CSS/SCSS/Less files (repeatable: `--input "src/**/*.css" --input "lib/**/*.css"`) |
|
|
131
|
-
| `--output` | Output file. `.ts` → TypeScript, `.js` → JavaScript + `.d.ts` alongside |
|
|
132
|
+
| `--output` | Output file. `.ts` → TypeScript, `.js` → JavaScript + `.d.ts` alongside, `.json` → [design tokens](#design-tokens-dtcg) |
|
|
132
133
|
| `--exclude` | Glob pattern for files to exclude (repeatable: `--exclude "**/a/**" --exclude "**/b/**"`) |
|
|
133
134
|
| `--prefix` | Prefix for generated keys: `--prefix theme` → `themeColorPrimary` |
|
|
134
135
|
| `--naming` | Key naming: `camelCase` (default), `snake`, `kebab`, `constant`, `pascal` |
|
|
135
136
|
| `--selector` | Extra CSS selector to scan for variables (repeatable: `--selector ".dark" --selector "[data-theme='dark']"`) |
|
|
137
|
+
| `--theme` | Named theme block, kept out of the default value and emitted as `@theme <name> <value>` JSDoc tags (repeatable: `--theme dark='[data-theme="dark"]' --theme contrast='@media (prefers-contrast: more)'`) — see [Theme values](#theme-values) |
|
|
136
138
|
| `--group` | Nest keys under an object named after each variable's first hyphen segment: `--color-primary`/`--color-secondary` → `cssVars.color.primary`/`cssVars.color.secondary`. A variable with no hyphen stays top-level. Can't be combined with `--prefix`. |
|
|
137
|
-
| `--
|
|
139
|
+
| `--helpers` | Also emit the `CssVarRef` type and typed `getCssVar(ref, el?)`/`setCssVar(ref, value, el?)` runtime helpers — see [Usage](#usage). |
|
|
140
|
+
| `--prune` | Drop generated vars with no detected `cssVars.<key>` usage. Requires `--usage <glob>` (repeatable). With `--group`, matches `cssVars.<group>.<key>` and keeps a whole group referenced as `cssVars.<group>`. |
|
|
138
141
|
| `--prune-check` | Like `--prune`, but only reports unused vars without writing; exits 1 if any are found. Useful in CI. |
|
|
139
142
|
| `--usage` | Glob of source files to scan for `cssVars` usage, for `--prune`/`--prune-check` (repeatable) |
|
|
140
143
|
| `--usage-exclude` | Glob of source files to exclude from the usage scan (repeatable) |
|
|
@@ -172,7 +175,9 @@ export default {
|
|
|
172
175
|
prefix: 'theme',
|
|
173
176
|
naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
|
|
174
177
|
selectors: ['.dark', '[data-theme="dark"]'],
|
|
178
|
+
themes: { dark: '[data-theme="dark"]' },
|
|
175
179
|
group: false,
|
|
180
|
+
helpers: false,
|
|
176
181
|
prune: false,
|
|
177
182
|
usage: 'src/**/*.{ts,tsx}',
|
|
178
183
|
};
|
|
@@ -273,11 +278,14 @@ Turbopack does not yet have a public plugin API for virtual modules. Use the CLI
|
|
|
273
278
|
| `prefix` | `string` | — | Prefix for generated keys: `'theme'` → `themeColorPrimary` |
|
|
274
279
|
| `naming` | `'camelCase' \| 'snake' \| 'kebab' \| 'constant' \| 'pascal'` | `'camelCase'` | Key naming convention |
|
|
275
280
|
| `selectors` | `string[]` | — | Extra CSS selectors to scan, e.g. `['.dark', '[data-theme="dark"]']` |
|
|
281
|
+
| `themes` | `Record<string, string>` | — | Theme name → selector or `@media` prelude; values become `@theme` JSDoc tags — see [Theme values](#theme-values) |
|
|
276
282
|
| `group` | `boolean` | `false` | Nest keys by each variable's first hyphen segment, e.g. `cssVars.color.primary`. Can't be combined with `prefix` |
|
|
277
|
-
| `
|
|
283
|
+
| `helpers` | `boolean` | `false` | Also export the `CssVarRef` type and `getCssVar`/`setCssVar` runtime helpers from `css-typed-vars/vars` |
|
|
284
|
+
| `prune` | `boolean` | `false` | Drop vars with no detected `cssVars.<key>` (or `cssVars.<group>.<key>` with `group`) usage. Requires `usage` |
|
|
278
285
|
| `usage` | `string \| string[]` | — | Glob(s) of source files to scan for `cssVars` usage, for `prune` |
|
|
279
286
|
| `usageExclude` | `string \| string[]` | — | Glob(s) of source files to exclude from the usage scan |
|
|
280
287
|
| `dts` | `string \| false` | inside `node_modules` | Path to write type declarations. `false` to skip |
|
|
288
|
+
| `tokens` | `string` | — | Also write a [design tokens (DTCG)](#design-tokens-dtcg) JSON file to this path |
|
|
281
289
|
|
|
282
290
|
---
|
|
283
291
|
|
|
@@ -320,6 +328,18 @@ const Button = styled.button`
|
|
|
320
328
|
<div className={`text-[${cssVars.colorPrimary}]`} />
|
|
321
329
|
```
|
|
322
330
|
|
|
331
|
+
**Reading and writing at runtime** (`helpers: true` / `--helpers`):
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
import { cssVars, getCssVar, setCssVar } from './cssVars';
|
|
335
|
+
|
|
336
|
+
getCssVar(cssVars.colorPrimary); // computed value on <html>, e.g. '#3b82f6'
|
|
337
|
+
setCssVar(cssVars.colorPrimary, '#ef4444'); // inline style on <html>
|
|
338
|
+
setCssVar(cssVars.spacingMd, '12px', cardEl); // or on a specific element
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
The helpers take a `cssVars` value (typed as `CssVarRef`, the union of every generated `'var(--name)'`), so they work the same with any `naming`, `prefix` or `group`. They use `getComputedStyle`/`style.setProperty`, so call them in the browser only, and the TS output needs the `DOM` lib in your `tsconfig`.
|
|
342
|
+
|
|
323
343
|
---
|
|
324
344
|
|
|
325
345
|
## Programmatic API
|
|
@@ -329,12 +349,14 @@ import { generate } from 'css-typed-vars';
|
|
|
329
349
|
|
|
330
350
|
await generate({
|
|
331
351
|
input: 'src/styles/**/*.{css,scss}',
|
|
332
|
-
output: 'src/cssVars.ts', // or 'src/cssVars.js' →
|
|
352
|
+
output: 'src/cssVars.ts', // or 'src/cssVars.js' → .js + .d.ts, or 'tokens.json' → design tokens
|
|
333
353
|
exclude: ['**/vendor/**'],
|
|
334
354
|
prefix: 'theme',
|
|
335
355
|
naming: 'snake', // 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal'
|
|
336
356
|
selectors: ['.dark', '[data-theme="dark"]'],
|
|
357
|
+
themes: { dark: '[data-theme="dark"]' }, // per-theme values as @theme JSDoc tags
|
|
337
358
|
group: false, // nest keys by first hyphen segment, e.g. cssVars.color.primary
|
|
359
|
+
helpers: false, // also emit getCssVar/setCssVar runtime helpers
|
|
338
360
|
prune: false, // drop vars with no detected cssVars.<key> usage (requires `usage`)
|
|
339
361
|
usage: 'src/**/*.{ts,tsx}',
|
|
340
362
|
});
|
|
@@ -342,12 +364,12 @@ await generate({
|
|
|
342
364
|
|
|
343
365
|
`checkGenerated(options)` takes the same options and returns `Promise<boolean>` — `true` if the existing output already matches what would be generated, without writing anything. Same thing `--check` does on the CLI.
|
|
344
366
|
|
|
345
|
-
`findUnusedVars(options)` takes `input`/`exclude`/`selectors`/`prefix`/`naming`/`usage`/`usageExclude` and returns `Promise<string[]>` — the CSS variable names with no detected `cssVars.<key>` usage, without writing or pruning anything. Same thing `--prune-check` does on the CLI.
|
|
367
|
+
`findUnusedVars(options)` takes `input`/`exclude`/`selectors`/`prefix`/`naming`/`group`/`usage`/`usageExclude` and returns `Promise<string[]>` — the CSS variable names with no detected `cssVars.<key>` usage, without writing or pruning anything. Same thing `--prune-check` does on the CLI.
|
|
346
368
|
|
|
347
369
|
Lower-level exports:
|
|
348
370
|
|
|
349
371
|
```ts
|
|
350
|
-
import { parseVarNames, parseVarDeclarations, parsePropertyRules, generateCode, scanVarNames, scanVarDeclarations, scanCss, scanUsedKeys } from 'css-typed-vars';
|
|
372
|
+
import { parseVarNames, parseVarDeclarations, parsePropertyRules, parseThemedDeclarations, generateCode, generateTokens, scanVarNames, scanVarDeclarations, scanCss, scanUsedKeys } from 'css-typed-vars';
|
|
351
373
|
```
|
|
352
374
|
|
|
353
375
|
## Supported formats
|
|
@@ -360,6 +382,69 @@ import { parseVarNames, parseVarDeclarations, parsePropertyRules, generateCode,
|
|
|
360
382
|
|
|
361
383
|
By default, variables are scanned from `:root {}` blocks (including attribute selectors like `:root[data-theme="dark"]`) and Tailwind CSS v4's `@theme {}` blocks. Use the `selectors` option to also pick up variables from other selectors such as `.dark` or `[data-theme="dark"]`.
|
|
362
384
|
|
|
385
|
+
## Theme values
|
|
386
|
+
|
|
387
|
+
By default, a variable redeclared in another block (`:root[data-theme="dark"]`, or a `selectors` entry) simply overwrites its `@default` value — last one wins. The `themes` option names those blocks instead, so each theme's value is kept separately:
|
|
388
|
+
|
|
389
|
+
```js
|
|
390
|
+
// css-typed-vars.config.js
|
|
391
|
+
export default {
|
|
392
|
+
input: 'src/**/*.css',
|
|
393
|
+
output: 'src/cssVars.ts',
|
|
394
|
+
themes: {
|
|
395
|
+
dark: '[data-theme="dark"]', // a selector...
|
|
396
|
+
contrast: '@media (prefers-contrast: more)', // ...or an @media prelude (its :root/@theme blocks are read)
|
|
397
|
+
},
|
|
398
|
+
};
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
```css
|
|
402
|
+
:root { --color-bg: #ffffff; }
|
|
403
|
+
[data-theme="dark"] { --color-bg: #0b0b0f; --glow: 0 0 8px #7c3aed; }
|
|
404
|
+
@media (prefers-contrast: more) { :root { --color-bg: #000000; } }
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
```ts
|
|
408
|
+
export const cssVars = {
|
|
409
|
+
/** @default #ffffff */
|
|
410
|
+
/** @theme dark #0b0b0f */
|
|
411
|
+
/** @theme contrast #000000 */
|
|
412
|
+
colorBg: 'var(--color-bg)',
|
|
413
|
+
/** @theme dark 0 0 8px #7c3aed */
|
|
414
|
+
glow: 'var(--glow)',
|
|
415
|
+
} as const;
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
- Theme blocks are kept out of the default value, so `@default` always shows the base (`:root`/`@theme`/`selectors`) value.
|
|
419
|
+
- A variable declared only inside a theme (`--glow` above) is still generated, with just its theme tags.
|
|
420
|
+
- An `@media` theme matches by its prelude, ignoring whitespace and case. Other `@media` blocks are read as before.
|
|
421
|
+
- On the CLI, pass `--theme <name>=<selector>` (repeatable): `--theme dark='[data-theme="dark"]'`.
|
|
422
|
+
|
|
423
|
+
## Design tokens (DTCG)
|
|
424
|
+
|
|
425
|
+
Point `output` at a `.json` file to get a [W3C Design Tokens](https://www.designtokens.org/tr/drafts/format/) document instead of TypeScript, for Style Dictionary, Tokens Studio and similar tools:
|
|
426
|
+
|
|
427
|
+
```sh
|
|
428
|
+
npx css-typed-vars --input "src/**/*.css" --output tokens/tokens.json --group
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
```json
|
|
432
|
+
{
|
|
433
|
+
"color": {
|
|
434
|
+
"link": { "$value": "{color.primary}" },
|
|
435
|
+
"primary": { "$value": "#3b82f6", "$type": "color" }
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
- Keys follow `naming`/`prefix`/`group`, like the generated object.
|
|
441
|
+
- `$value` is the declared value (or the `@property` `initial-value`); `$type` is inferred from the `@property` syntax (`<color>`, `<length>`, `<number>`, `<time>`, ...).
|
|
442
|
+
- A value that's exactly `var(--other)` becomes an alias (`{color.primary}`) when `--other` is in the file.
|
|
443
|
+
- [Theme values](#theme-values) go under `$extensions["css-typed-vars"].themes`.
|
|
444
|
+
- The plugin can write the file too: `cssTypedVars({ input, tokens: 'tokens/tokens.json' })`.
|
|
445
|
+
|
|
446
|
+
See the [Design tokens guide](https://stanislavkozachenko.github.io/css-typed-vars/guide/design-tokens) for details.
|
|
447
|
+
|
|
363
448
|
## @property syntax typing
|
|
364
449
|
|
|
365
450
|
If a variable is registered via the [CSS Properties and Values API](https://developer.mozilla.org/en-US/docs/Web/CSS/@property), its `syntax` descriptor is picked up automatically — no config needed:
|
|
@@ -121,26 +121,35 @@ function extractValue(text, start) {
|
|
|
121
121
|
}
|
|
122
122
|
return text.slice(start, i).trim();
|
|
123
123
|
}
|
|
124
|
-
function
|
|
125
|
-
const
|
|
126
|
-
const
|
|
127
|
-
|
|
124
|
+
function forEachProperty(block, onProperty) {
|
|
125
|
+
const masked = maskQuotedContent(block);
|
|
126
|
+
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
127
|
+
const name = prop[0];
|
|
128
|
+
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
129
|
+
onProperty(name, extractValue(block, colonIndex + 1));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
133
|
+
for (const sel of selectors) {
|
|
128
134
|
const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
129
135
|
const openRegex = new RegExp(`${escaped}(?![\\w-])[^{]*\\{`, "g");
|
|
130
136
|
let match;
|
|
131
137
|
while (match = openRegex.exec(stripped)) {
|
|
132
138
|
const start = match.index + match[0].length;
|
|
133
139
|
const block = extractBlock(stripped, start);
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
138
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
139
|
-
}
|
|
140
|
-
openRegex.lastIndex = start + block.length + 1;
|
|
140
|
+
const end = start + block.length + 1;
|
|
141
|
+
onBlock(block, [start, end]);
|
|
142
|
+
openRegex.lastIndex = end;
|
|
141
143
|
}
|
|
142
144
|
}
|
|
143
145
|
}
|
|
146
|
+
var BASE_SELECTORS = [":root", "@theme"];
|
|
147
|
+
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
148
|
+
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
149
|
+
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
150
|
+
forEachProperty(block, onProperty);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
144
153
|
function parseVarNames(css, selectors) {
|
|
145
154
|
const names = /* @__PURE__ */ new Set();
|
|
146
155
|
scanDeclarations(css, selectors, (name) => names.add(name));
|
|
@@ -151,6 +160,48 @@ function parseVarDeclarations(css, selectors) {
|
|
|
151
160
|
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
|
|
152
161
|
return declarations;
|
|
153
162
|
}
|
|
163
|
+
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
164
|
+
function forEachMediaBlock(stripped, media, onBlock) {
|
|
165
|
+
const wanted = normalizePrelude(media.replace(/^@media/i, ""));
|
|
166
|
+
const openRegex = /@media([^{;]*)\{/gi;
|
|
167
|
+
let match;
|
|
168
|
+
while (match = openRegex.exec(stripped)) {
|
|
169
|
+
const start = match.index + match[0].length;
|
|
170
|
+
const block = extractBlock(stripped, start);
|
|
171
|
+
const end = start + block.length + 1;
|
|
172
|
+
if (normalizePrelude(match[1]) === wanted) {
|
|
173
|
+
onBlock(block, [start, end]);
|
|
174
|
+
openRegex.lastIndex = end;
|
|
175
|
+
} else {
|
|
176
|
+
openRegex.lastIndex = start;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function parseThemedDeclarations(css, selectors, themes) {
|
|
181
|
+
const stripped = stripComments(css);
|
|
182
|
+
const themeValues = /* @__PURE__ */ new Map();
|
|
183
|
+
const skip = [];
|
|
184
|
+
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
185
|
+
const values = /* @__PURE__ */ new Map();
|
|
186
|
+
themeValues.set(themeName, values);
|
|
187
|
+
const collect = (block) => forEachProperty(block, (name, value) => values.set(name, value));
|
|
188
|
+
const selector = themeSelector.trim();
|
|
189
|
+
if (/^@media\b/i.test(selector)) {
|
|
190
|
+
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
191
|
+
skip.push(range);
|
|
192
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
193
|
+
});
|
|
194
|
+
} else {
|
|
195
|
+
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
196
|
+
skip.push(range);
|
|
197
|
+
collect(block);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
202
|
+
scanDeclarations(css, selectors, (name, value) => declarations.set(name, value), skip, stripped);
|
|
203
|
+
return { declarations, themes: themeValues };
|
|
204
|
+
}
|
|
154
205
|
var PROPERTY_DESCRIPTORS = [
|
|
155
206
|
["syntax", "syntax"],
|
|
156
207
|
["inherits", "inherits"],
|
|
@@ -187,7 +238,14 @@ import fg from "fast-glob";
|
|
|
187
238
|
function normalizePatterns(patterns) {
|
|
188
239
|
return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
|
|
189
240
|
}
|
|
190
|
-
|
|
241
|
+
function collectVarNames(scanned) {
|
|
242
|
+
const names = new Set(scanned.declarations.keys());
|
|
243
|
+
for (const values of scanned.themes.values()) {
|
|
244
|
+
for (const name of values.keys()) names.add(name);
|
|
245
|
+
}
|
|
246
|
+
return [...names].sort();
|
|
247
|
+
}
|
|
248
|
+
async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
191
249
|
const normalized = normalizePatterns(patterns);
|
|
192
250
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
193
251
|
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
@@ -198,18 +256,23 @@ async function scanCss(patterns, exclude, selectors) {
|
|
|
198
256
|
css = await readFile(file, "utf8");
|
|
199
257
|
} catch (err) {
|
|
200
258
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
201
|
-
return
|
|
259
|
+
return null;
|
|
202
260
|
}
|
|
203
|
-
return {
|
|
261
|
+
return { ...parseThemedDeclarations(css, selectors, themes), properties: parsePropertyRules(css) };
|
|
204
262
|
})
|
|
205
263
|
);
|
|
206
264
|
const declarations = /* @__PURE__ */ new Map();
|
|
207
265
|
const properties = /* @__PURE__ */ new Map();
|
|
266
|
+
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
208
267
|
for (const result of perFile) {
|
|
268
|
+
if (!result) continue;
|
|
209
269
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
210
270
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
271
|
+
for (const [theme, values] of result.themes) {
|
|
272
|
+
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
273
|
+
}
|
|
211
274
|
}
|
|
212
|
-
return { declarations, properties };
|
|
275
|
+
return { declarations, properties, themes: themeValues };
|
|
213
276
|
}
|
|
214
277
|
async function scanVarDeclarations(patterns, exclude, selectors) {
|
|
215
278
|
return (await scanCss(patterns, exclude, selectors)).declarations;
|
|
@@ -218,35 +281,43 @@ async function scanVarNames(patterns, exclude, selectors) {
|
|
|
218
281
|
const declarations = await scanVarDeclarations(patterns, exclude, selectors);
|
|
219
282
|
return [...declarations.keys()].sort();
|
|
220
283
|
}
|
|
221
|
-
var
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
284
|
+
var ROOT_RE = /\bcssVars\b/g;
|
|
285
|
+
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
286
|
+
function readAccess(text, from) {
|
|
287
|
+
ACCESS_RE.lastIndex = from;
|
|
288
|
+
const match = ACCESS_RE.exec(text);
|
|
289
|
+
return match ? { key: match[1] ?? match[3], end: ACCESS_RE.lastIndex } : null;
|
|
290
|
+
}
|
|
291
|
+
function extractUsage(text, into) {
|
|
292
|
+
for (const root of text.matchAll(ROOT_RE)) {
|
|
293
|
+
const first = readAccess(text, root.index + root[0].length);
|
|
294
|
+
if (!first) continue;
|
|
295
|
+
into.keys.add(first.key);
|
|
296
|
+
const second = readAccess(text, first.end);
|
|
297
|
+
if (second) into.paths.add(`${first.key}\0${second.key}`);
|
|
298
|
+
else into.wholeKeys.add(first.key);
|
|
225
299
|
}
|
|
226
300
|
}
|
|
227
|
-
async function
|
|
301
|
+
async function scanUsage(patterns, exclude) {
|
|
228
302
|
const normalized = normalizePatterns(patterns);
|
|
229
303
|
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
230
304
|
const files = await fg(normalized, { absolute: true, ignore: normalizedExclude });
|
|
231
|
-
const
|
|
305
|
+
const usage = { keys: /* @__PURE__ */ new Set(), wholeKeys: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
306
|
+
const texts = await Promise.all(
|
|
232
307
|
files.map(async (file) => {
|
|
233
|
-
const used = /* @__PURE__ */ new Set();
|
|
234
|
-
let text;
|
|
235
308
|
try {
|
|
236
|
-
|
|
309
|
+
return await readFile(file, "utf8");
|
|
237
310
|
} catch (err) {
|
|
238
311
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
239
|
-
return
|
|
312
|
+
return "";
|
|
240
313
|
}
|
|
241
|
-
extractUsedKeys(text, used);
|
|
242
|
-
return used;
|
|
243
314
|
})
|
|
244
315
|
);
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
return
|
|
316
|
+
for (const text of texts) extractUsage(text, usage);
|
|
317
|
+
return usage;
|
|
318
|
+
}
|
|
319
|
+
async function scanUsedKeys(patterns, exclude) {
|
|
320
|
+
return (await scanUsage(patterns, exclude)).keys;
|
|
250
321
|
}
|
|
251
322
|
|
|
252
323
|
// src/generator.ts
|
|
@@ -309,6 +380,12 @@ function formatKey(key, naming = "camelCase") {
|
|
|
309
380
|
function computeKey(cssVarName, prefix, naming) {
|
|
310
381
|
return applyPrefix(toKey(cssVarName, naming), prefix, naming);
|
|
311
382
|
}
|
|
383
|
+
function computeKeyPath(cssVarName, prefix, naming, group) {
|
|
384
|
+
if (!group) return [computeKey(cssVarName, prefix, naming)];
|
|
385
|
+
const split = splitGroupKey(cssVarName);
|
|
386
|
+
if (!split) return [toKey(cssVarName, naming)];
|
|
387
|
+
return [toKeyFragment(split.group, naming), toKeyFragment(split.rest, naming)];
|
|
388
|
+
}
|
|
312
389
|
function findKeyCollisions(varNames, prefix, naming) {
|
|
313
390
|
const byKey = /* @__PURE__ */ new Map();
|
|
314
391
|
for (const name of varNames) {
|
|
@@ -327,23 +404,37 @@ function warnOnCollisions(varNames, prefix, naming) {
|
|
|
327
404
|
console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
|
|
328
405
|
}
|
|
329
406
|
}
|
|
330
|
-
function
|
|
407
|
+
function entryMeta(name, options) {
|
|
408
|
+
const themes = [];
|
|
409
|
+
for (const [theme, values] of options.themes ?? []) {
|
|
410
|
+
const value = values.get(name);
|
|
411
|
+
if (value !== void 0) themes.push([theme, value]);
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
name,
|
|
415
|
+
value: options.declarations?.get(name),
|
|
416
|
+
syntax: options.properties?.get(name)?.syntax,
|
|
417
|
+
...themes.length > 0 ? { themes } : {}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function buildEntries(varNames, options) {
|
|
421
|
+
const { prefix, naming } = options;
|
|
331
422
|
const byKey = /* @__PURE__ */ new Map();
|
|
332
423
|
for (const name of varNames) {
|
|
333
424
|
const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
|
|
334
|
-
byKey.set(key,
|
|
425
|
+
byKey.set(key, entryMeta(name, options));
|
|
335
426
|
}
|
|
336
427
|
return [...byKey].map(([key, entry]) => ({ key, ...entry }));
|
|
337
428
|
}
|
|
338
|
-
function buildGroupedEntries(varNames,
|
|
429
|
+
function buildGroupedEntries(varNames, options) {
|
|
430
|
+
const { naming } = options;
|
|
339
431
|
const groupMap = /* @__PURE__ */ new Map();
|
|
340
432
|
const ungroupedMap = /* @__PURE__ */ new Map();
|
|
341
433
|
for (const name of varNames) {
|
|
342
|
-
const
|
|
343
|
-
const syntax = properties?.get(name)?.syntax;
|
|
434
|
+
const meta = entryMeta(name, options);
|
|
344
435
|
const split = splitGroupKey(name);
|
|
345
436
|
if (!split) {
|
|
346
|
-
ungroupedMap.set(formatKey(toKey(name, naming), naming),
|
|
437
|
+
ungroupedMap.set(formatKey(toKey(name, naming), naming), meta);
|
|
347
438
|
continue;
|
|
348
439
|
}
|
|
349
440
|
const groupKey = formatKey(toKeyFragment(split.group, naming), naming);
|
|
@@ -353,7 +444,7 @@ function buildGroupedEntries(varNames, naming, declarations, properties) {
|
|
|
353
444
|
leafMap = /* @__PURE__ */ new Map();
|
|
354
445
|
groupMap.set(groupKey, leafMap);
|
|
355
446
|
}
|
|
356
|
-
leafMap.set(leafKey,
|
|
447
|
+
leafMap.set(leafKey, meta);
|
|
357
448
|
}
|
|
358
449
|
for (const groupKey of groupMap.keys()) ungroupedMap.delete(groupKey);
|
|
359
450
|
const groups = [...groupMap].map(([key, leafMap]) => ({
|
|
@@ -376,6 +467,9 @@ function unquoteCssString(value) {
|
|
|
376
467
|
function formatSyntaxComment(syntax, indent = " ") {
|
|
377
468
|
return `${indent}/** @syntax ${unquoteCssString(syntax).replace(/\*\//g, "*\\/")} */`;
|
|
378
469
|
}
|
|
470
|
+
function formatThemeComment(theme, value, indent = " ") {
|
|
471
|
+
return `${indent}/** @theme ${theme} ${value.replace(/\*\//g, "*\\/")} */`;
|
|
472
|
+
}
|
|
379
473
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
380
474
|
function parseEnumSyntax(syntax) {
|
|
381
475
|
const unquoted = unquoteCssString(syntax).trim();
|
|
@@ -406,14 +500,15 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
406
500
|
return blocks;
|
|
407
501
|
}
|
|
408
502
|
function renderEntryLines(entries, indent, lineFor) {
|
|
409
|
-
return entries.flatMap(({ key, name, value, syntax }) => [
|
|
503
|
+
return entries.flatMap(({ key, name, value, syntax, themes }) => [
|
|
410
504
|
...value ? [formatDefaultComment(value, indent)] : [],
|
|
505
|
+
...(themes ?? []).map(([theme, themeValue]) => formatThemeComment(theme, themeValue, indent)),
|
|
411
506
|
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
412
507
|
`${indent}${lineFor(key, name)}`
|
|
413
508
|
]);
|
|
414
509
|
}
|
|
415
|
-
function renderGroupedBlock(varNames,
|
|
416
|
-
const { groups, ungrouped } = buildGroupedEntries(varNames,
|
|
510
|
+
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
511
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
417
512
|
const lines = [];
|
|
418
513
|
for (const group of groups) {
|
|
419
514
|
lines.push(`${indent}${group.key}: {`);
|
|
@@ -430,10 +525,52 @@ function assertGroupPrefixCompatible(prefix, group) {
|
|
|
430
525
|
}
|
|
431
526
|
var codeLineFor = (key, name) => `${key}: 'var(${name})',`;
|
|
432
527
|
var declarationLineFor = (key, name) => `${key}: 'var(${name})';`;
|
|
433
|
-
function
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
const
|
|
528
|
+
function normalizeOptions(args) {
|
|
529
|
+
const [first] = args;
|
|
530
|
+
if (first !== null && typeof first === "object") return first;
|
|
531
|
+
const [prefix, naming, declarations, group, properties] = args;
|
|
532
|
+
return { prefix, naming, declarations, group, properties };
|
|
533
|
+
}
|
|
534
|
+
function renderEntries(varNames, options, closeSuffix, lineFor) {
|
|
535
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
536
|
+
return options.group ? renderGroupedBlock(varNames, options, " ", closeSuffix, lineFor) : renderEntryLines(buildEntries(varNames, options), " ", lineFor);
|
|
537
|
+
}
|
|
538
|
+
function emittedNames(varNames, options) {
|
|
539
|
+
if (!options.group) return buildEntries(varNames, options).map((e) => e.name);
|
|
540
|
+
const { groups, ungrouped } = buildGroupedEntries(varNames, options);
|
|
541
|
+
return [...groups.flatMap((g) => g.entries), ...ungrouped].map((e) => e.name);
|
|
542
|
+
}
|
|
543
|
+
function renderRefType(varNames, options) {
|
|
544
|
+
const refs = emittedNames(varNames, options).map((name) => `'var(${name})'`);
|
|
545
|
+
return `export type CssVarRef = ${refs.length > 0 ? refs.join(" | ") : "never"};`;
|
|
546
|
+
}
|
|
547
|
+
var HELPERS_TS = [
|
|
548
|
+
"export function getCssVar(ref: CssVarRef, el: Element = document.documentElement): string {",
|
|
549
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
550
|
+
"}",
|
|
551
|
+
"",
|
|
552
|
+
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
553
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
554
|
+
"}"
|
|
555
|
+
];
|
|
556
|
+
var HELPERS_JS = [
|
|
557
|
+
"export function getCssVar(ref, el = document.documentElement) {",
|
|
558
|
+
" return getComputedStyle(el).getPropertyValue(ref.slice(4, -1)).trim();",
|
|
559
|
+
"}",
|
|
560
|
+
"",
|
|
561
|
+
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
562
|
+
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
563
|
+
"}"
|
|
564
|
+
];
|
|
565
|
+
var HELPERS_DTS = [
|
|
566
|
+
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
567
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
568
|
+
];
|
|
569
|
+
function generateCode(varNames, ...args) {
|
|
570
|
+
const options = normalizeOptions(args);
|
|
571
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
572
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
573
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_TS);
|
|
437
574
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
438
575
|
return [
|
|
439
576
|
"// generated \u2014 do not edit",
|
|
@@ -444,21 +581,23 @@ function generateCode(varNames, prefix, naming, declarations, group, properties)
|
|
|
444
581
|
""
|
|
445
582
|
].join("\n");
|
|
446
583
|
}
|
|
447
|
-
function generateJs(varNames,
|
|
448
|
-
|
|
449
|
-
const entries =
|
|
584
|
+
function generateJs(varNames, ...args) {
|
|
585
|
+
const options = normalizeOptions(args);
|
|
586
|
+
const entries = renderEntries(varNames, options, ",", codeLineFor);
|
|
450
587
|
return [
|
|
451
588
|
"// generated \u2014 do not edit",
|
|
452
589
|
"export const cssVars = {",
|
|
453
590
|
...entries,
|
|
454
591
|
"};",
|
|
592
|
+
...options.helpers ? ["", ...HELPERS_JS] : [],
|
|
455
593
|
""
|
|
456
594
|
].join("\n");
|
|
457
595
|
}
|
|
458
|
-
function generateDeclaration(varNames,
|
|
459
|
-
|
|
460
|
-
const entries =
|
|
461
|
-
const blocks = buildTailBlocks(varNames, group, properties);
|
|
596
|
+
function generateDeclaration(varNames, ...args) {
|
|
597
|
+
const options = normalizeOptions(args);
|
|
598
|
+
const entries = renderEntries(varNames, options, ";", declarationLineFor);
|
|
599
|
+
const blocks = buildTailBlocks(varNames, options.group, options.properties);
|
|
600
|
+
if (options.helpers) blocks.push([renderRefType(varNames, options)], HELPERS_DTS);
|
|
462
601
|
const tailBody = blocks.flatMap((block, i) => i === 0 ? block : ["", ...block]);
|
|
463
602
|
return [
|
|
464
603
|
"export declare const cssVars: {",
|
|
@@ -468,20 +607,85 @@ function generateDeclaration(varNames, prefix, naming, declarations, group, prop
|
|
|
468
607
|
""
|
|
469
608
|
].join("\n");
|
|
470
609
|
}
|
|
610
|
+
var TOKEN_TYPES = {
|
|
611
|
+
"<color>": "color",
|
|
612
|
+
"<length>": "dimension",
|
|
613
|
+
"<length-percentage>": "dimension",
|
|
614
|
+
"<number>": "number",
|
|
615
|
+
"<integer>": "number",
|
|
616
|
+
"<time>": "duration"
|
|
617
|
+
};
|
|
618
|
+
var VAR_REF_RE = /^var\(\s*(--[\w-]+)\s*\)$/;
|
|
619
|
+
function generateTokens(varNames, options = {}) {
|
|
620
|
+
assertGroupPrefixCompatible(options.prefix, options.group);
|
|
621
|
+
const tokens = emittedNames(varNames, options).flatMap((name) => {
|
|
622
|
+
const meta = entryMeta(name, options);
|
|
623
|
+
const value = meta.value ?? options.properties?.get(name)?.initialValue;
|
|
624
|
+
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
625
|
+
});
|
|
626
|
+
const paths = new Map(tokens.map(({ meta, path: path2 }) => [meta.name, path2]));
|
|
627
|
+
const resolve = (value) => {
|
|
628
|
+
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
629
|
+
return target ? `{${target.join(".")}}` : value;
|
|
630
|
+
};
|
|
631
|
+
const root = {};
|
|
632
|
+
for (const { meta, value, path: path2 } of tokens) {
|
|
633
|
+
const token = { $value: resolve(value) };
|
|
634
|
+
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
635
|
+
if (type) token.$type = type;
|
|
636
|
+
if (meta.themes) {
|
|
637
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve(themeValue)]));
|
|
638
|
+
token.$extensions = { "css-typed-vars": { themes } };
|
|
639
|
+
}
|
|
640
|
+
const [key, leaf] = path2;
|
|
641
|
+
if (leaf === void 0) {
|
|
642
|
+
root[key] = token;
|
|
643
|
+
} else {
|
|
644
|
+
const group = root[key] ?? (root[key] = {});
|
|
645
|
+
group[leaf] = token;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return JSON.stringify(root, null, 2) + "\n";
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// src/prune.ts
|
|
652
|
+
function assertPruneCompatible(options) {
|
|
653
|
+
if (options.prune && !options.usage) {
|
|
654
|
+
throw new Error('css-typed-vars: "prune" requires "usage" (glob(s) of source files to scan).');
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function isUsed(name, usage, options) {
|
|
658
|
+
const [key, leaf] = computeKeyPath(name, options.prefix, options.naming, options.group);
|
|
659
|
+
if (leaf === void 0) return usage.keys.has(key);
|
|
660
|
+
return usage.wholeKeys.has(key) || usage.paths.has(`${key}\0${leaf}`);
|
|
661
|
+
}
|
|
662
|
+
function partitionUnused(names, usage, options) {
|
|
663
|
+
const used = [];
|
|
664
|
+
const unused = [];
|
|
665
|
+
for (const name of names) {
|
|
666
|
+
(isUsed(name, usage, options) ? used : unused).push(name);
|
|
667
|
+
}
|
|
668
|
+
return { used, unused };
|
|
669
|
+
}
|
|
471
670
|
|
|
472
671
|
export {
|
|
473
672
|
__dirname,
|
|
474
673
|
parseVarNames,
|
|
475
674
|
parseVarDeclarations,
|
|
675
|
+
parseThemedDeclarations,
|
|
476
676
|
parsePropertyRules,
|
|
677
|
+
collectVarNames,
|
|
477
678
|
scanCss,
|
|
478
679
|
scanVarDeclarations,
|
|
479
680
|
scanVarNames,
|
|
681
|
+
scanUsage,
|
|
480
682
|
scanUsedKeys,
|
|
481
683
|
VALID_NAMINGS,
|
|
482
|
-
computeKey,
|
|
483
684
|
warnOnCollisions,
|
|
484
685
|
generateCode,
|
|
485
686
|
generateJs,
|
|
486
|
-
generateDeclaration
|
|
687
|
+
generateDeclaration,
|
|
688
|
+
generateTokens,
|
|
689
|
+
assertPruneCompatible,
|
|
690
|
+
partitionUnused
|
|
487
691
|
};
|