css-typed-vars 0.7.0 → 0.8.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 +106 -11
- package/dist/{chunk-HBUSLYYB.js → chunk-32V3V6WT.js} +4 -3
- package/dist/{chunk-6YWE4A6S.js → chunk-5HPTHW7S.js} +154 -25
- package/dist/{chunk-PLO2JWR7.js → chunk-YDXCJQPL.js} +13 -2
- package/dist/cli.cjs +294 -97
- package/dist/cli.js +138 -75
- package/dist/esbuild.cjs +104 -27
- 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.ts → generator-DJ9uOYBP.d.cts} +21 -1
- package/dist/{generator-C1iVNsry.d.cts → generator-DJ9uOYBP.d.ts} +21 -1
- package/dist/index.cjs +169 -26
- package/dist/index.d.cts +15 -3
- package/dist/index.d.ts +15 -3
- package/dist/index.js +10 -2
- package/dist/rollup.cjs +104 -27
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +104 -27
- package/dist/unplugin.d.cts +1 -1
- package/dist/unplugin.d.ts +1 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +104 -27
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +104 -27
- 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/cli.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
checkGenerated,
|
|
4
|
+
findUndefinedRefs,
|
|
4
5
|
findUnusedVars,
|
|
5
6
|
generate
|
|
6
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-YDXCJQPL.js";
|
|
7
8
|
import {
|
|
8
9
|
VALID_NAMINGS
|
|
9
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-5HPTHW7S.js";
|
|
10
11
|
|
|
11
12
|
// src/cli.ts
|
|
12
13
|
import { readFile } from "fs/promises";
|
|
13
|
-
import { resolve } from "path";
|
|
14
|
+
import { relative, resolve } from "path";
|
|
14
15
|
import { pathToFileURL } from "url";
|
|
15
16
|
import { watch } from "chokidar";
|
|
16
17
|
var args = process.argv.slice(2).flatMap((arg) => {
|
|
@@ -30,10 +31,26 @@ var getArgs = (flag) => {
|
|
|
30
31
|
};
|
|
31
32
|
var watchMode = args.includes("--watch");
|
|
32
33
|
var checkMode = args.includes("--check");
|
|
33
|
-
var groupFlag = args.includes("--group");
|
|
34
|
-
var pruneFlag = args.includes("--prune");
|
|
35
34
|
var pruneCheckMode = args.includes("--prune-check");
|
|
36
|
-
var
|
|
35
|
+
var lintRefsMode = args.includes("--lint-refs");
|
|
36
|
+
var OPTION_FLAGS = [
|
|
37
|
+
"--input",
|
|
38
|
+
"--output",
|
|
39
|
+
"--exclude",
|
|
40
|
+
"--prefix",
|
|
41
|
+
"--naming",
|
|
42
|
+
"--selector",
|
|
43
|
+
"--theme",
|
|
44
|
+
"--group",
|
|
45
|
+
"--prune",
|
|
46
|
+
"--usage",
|
|
47
|
+
"--usage-exclude",
|
|
48
|
+
"--helpers",
|
|
49
|
+
"--refs-ignore"
|
|
50
|
+
];
|
|
51
|
+
var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check] [--group] [--helpers] [--theme <name>=<selector>] [--prune --usage <glob>] [--prune-check --usage <glob>] [--lint-refs]";
|
|
52
|
+
var CliError = class extends Error {
|
|
53
|
+
};
|
|
37
54
|
async function loadConfig() {
|
|
38
55
|
const candidates = [
|
|
39
56
|
"css-typed-vars.config.js",
|
|
@@ -58,99 +75,145 @@ async function loadConfig() {
|
|
|
58
75
|
}
|
|
59
76
|
return {};
|
|
60
77
|
}
|
|
61
|
-
|
|
62
|
-
await generate(options);
|
|
63
|
-
console.log(`Generated \u2192 ${options.output}`);
|
|
64
|
-
}
|
|
65
|
-
async function main() {
|
|
66
|
-
if (args.includes("--version") || args.includes("-v")) {
|
|
67
|
-
const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
68
|
-
console.log(pkg.version);
|
|
69
|
-
process.exit(0);
|
|
70
|
-
}
|
|
71
|
-
const config = await loadConfig();
|
|
78
|
+
function applyFlags(config) {
|
|
72
79
|
const inputArgs = getArgs("--input");
|
|
73
|
-
const input = inputArgs.length > 0 ? inputArgs : config.input;
|
|
74
|
-
const output = getArg("--output") ?? config.output;
|
|
75
80
|
const excludeArgs = getArgs("--exclude");
|
|
76
|
-
const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
|
|
77
|
-
const prefix = getArg("--prefix") ?? config.prefix;
|
|
78
|
-
const namingRaw = getArg("--naming") ?? config.naming;
|
|
79
|
-
if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
|
|
80
|
-
console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
81
|
-
process.exit(1);
|
|
82
|
-
}
|
|
83
|
-
const naming = namingRaw;
|
|
84
81
|
const selectorArgs = getArgs("--selector");
|
|
85
|
-
const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
|
|
86
82
|
const themeArgs = getArgs("--theme");
|
|
87
83
|
for (const arg of themeArgs) {
|
|
88
84
|
if (!/^[^=]+=.+$/.test(arg)) {
|
|
89
|
-
|
|
90
|
-
process.exit(1);
|
|
85
|
+
throw new CliError(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
|
|
91
86
|
}
|
|
92
87
|
}
|
|
93
|
-
const themes = themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes;
|
|
94
|
-
const group = groupFlag || config.group;
|
|
95
|
-
const prune = pruneFlag || config.prune;
|
|
96
88
|
const usageArgs = getArgs("--usage");
|
|
97
|
-
const usage = usageArgs.length > 0 ? usageArgs : config.usage;
|
|
98
89
|
const usageExcludeArgs = getArgs("--usage-exclude");
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
90
|
+
const refsIgnoreArgs = getArgs("--refs-ignore");
|
|
91
|
+
return {
|
|
92
|
+
...config,
|
|
93
|
+
input: inputArgs.length > 0 ? inputArgs : config.input,
|
|
94
|
+
output: getArg("--output") ?? config.output,
|
|
95
|
+
exclude: excludeArgs.length > 0 ? excludeArgs : config.exclude,
|
|
96
|
+
prefix: getArg("--prefix") ?? config.prefix,
|
|
97
|
+
naming: getArg("--naming") ?? config.naming,
|
|
98
|
+
selectors: selectorArgs.length > 0 ? selectorArgs : config.selectors,
|
|
99
|
+
themes: themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes,
|
|
100
|
+
group: args.includes("--group") || config.group,
|
|
101
|
+
prune: args.includes("--prune") || config.prune,
|
|
102
|
+
usage: usageArgs.length > 0 ? usageArgs : config.usage,
|
|
103
|
+
usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
|
|
104
|
+
helpers: args.includes("--helpers") || config.helpers,
|
|
105
|
+
refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function loadTargets(config) {
|
|
109
|
+
if (!Array.isArray(config)) return [{ options: applyFlags(config), tag: "css-typed-vars" }];
|
|
110
|
+
if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
|
|
111
|
+
const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
|
|
112
|
+
if (used.length > 0) {
|
|
113
|
+
throw new CliError(`css-typed-vars: ${used.join(", ")} can't be used with an array config \u2014 set options per target in the config file instead.`);
|
|
105
114
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
115
|
+
return config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
|
|
116
|
+
}
|
|
117
|
+
function validateModes() {
|
|
118
|
+
if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
|
|
119
|
+
throw new CliError("css-typed-vars: --lint-refs cannot be combined with --watch, --check or --prune-check.");
|
|
109
120
|
}
|
|
121
|
+
if (checkMode && watchMode) throw new CliError("css-typed-vars: --check cannot be combined with --watch.");
|
|
110
122
|
if (pruneCheckMode && (watchMode || checkMode)) {
|
|
111
|
-
|
|
112
|
-
process.exit(1);
|
|
123
|
+
throw new CliError("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
|
|
113
124
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
125
|
+
}
|
|
126
|
+
function validateTarget({ options, tag }, single) {
|
|
127
|
+
const { input, output, naming, group, prefix, prune, usage } = options;
|
|
128
|
+
if (naming !== void 0 && !VALID_NAMINGS.includes(naming)) {
|
|
129
|
+
throw new CliError(`${tag}: invalid --naming value "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
117
130
|
}
|
|
118
|
-
if (
|
|
119
|
-
|
|
120
|
-
process.exit(1);
|
|
121
|
-
}
|
|
122
|
-
if (pruneCheckMode) {
|
|
123
|
-
const unused = await findUnusedVars({ input, exclude, selectors, themes, prefix, naming, group, usage, usageExclude });
|
|
124
|
-
if (unused.length > 0) {
|
|
125
|
-
console.error(`css-typed-vars: ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
126
|
-
process.exit(1);
|
|
127
|
-
}
|
|
128
|
-
console.log("css-typed-vars: no unused variables.");
|
|
131
|
+
if (lintRefsMode) {
|
|
132
|
+
if (!input) throw new CliError(`${tag}: --lint-refs requires --input <glob> (or "input" in the config file).`);
|
|
129
133
|
return;
|
|
130
134
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
if (!input || !output) {
|
|
136
|
+
throw new CliError(single ? `${USAGE}
|
|
137
|
+
Or add a css-typed-vars.config.js file with input and output fields.` : `${tag}: every target needs "input" and "output".`);
|
|
138
|
+
}
|
|
139
|
+
if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
|
|
140
|
+
if ((prune || pruneCheckMode) && !usage) {
|
|
141
|
+
throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function lintRefs({ options, tag }) {
|
|
145
|
+
const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
|
|
146
|
+
const format = (ref) => ` ${relative(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
|
|
147
|
+
const errors = refs.filter((ref) => !ref.hasFallback);
|
|
148
|
+
const warnings = refs.filter((ref) => ref.hasFallback);
|
|
149
|
+
if (warnings.length > 0) {
|
|
150
|
+
console.warn(`${tag}: ${warnings.length} reference(s) to undeclared variables with a fallback:`);
|
|
151
|
+
for (const ref of warnings) console.warn(format(ref));
|
|
152
|
+
}
|
|
153
|
+
if (errors.length > 0) {
|
|
154
|
+
console.error(`${tag}: ${errors.length} reference(s) to undeclared variables:`);
|
|
155
|
+
for (const ref of errors) console.error(format(ref));
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
console.log(`${tag}: no references to undeclared variables.`);
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
async function pruneCheck({ options, tag }) {
|
|
162
|
+
const unused = await findUnusedVars({ ...options, input: options.input });
|
|
163
|
+
if (unused.length > 0) {
|
|
164
|
+
console.error(`${tag}: ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
console.log(`${tag}: no unused variables.`);
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
async function check({ options, tag }) {
|
|
171
|
+
if (!await checkGenerated({ ...options, input: options.input, output: options.output })) {
|
|
172
|
+
console.error(`${tag}: "${options.output}" is out of date. Run without --check to regenerate.`);
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
console.log(`${tag}: "${options.output}" is up to date.`);
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
async function run({ options }) {
|
|
179
|
+
await generate({ ...options, input: options.input, output: options.output });
|
|
180
|
+
console.log(`Generated \u2192 ${options.output}`);
|
|
181
|
+
}
|
|
182
|
+
function watchTarget(target) {
|
|
183
|
+
const { input, exclude } = target.options;
|
|
184
|
+
const patterns = Array.isArray(input) ? input : [input];
|
|
185
|
+
const makeHandler = (label) => (file) => {
|
|
186
|
+
console.log(`${label}: ${file}`);
|
|
187
|
+
run(target).catch(console.error);
|
|
188
|
+
};
|
|
189
|
+
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
190
|
+
watch(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
191
|
+
}
|
|
192
|
+
async function main() {
|
|
193
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
194
|
+
const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
195
|
+
console.log(pkg.version);
|
|
196
|
+
process.exit(0);
|
|
197
|
+
}
|
|
198
|
+
const targets = loadTargets(await loadConfig());
|
|
199
|
+
validateModes();
|
|
200
|
+
for (const target of targets) validateTarget(target, targets.length === 1);
|
|
201
|
+
const mode = lintRefsMode ? lintRefs : pruneCheckMode ? pruneCheck : checkMode ? check : null;
|
|
202
|
+
if (mode) {
|
|
203
|
+
let ok = true;
|
|
204
|
+
for (const target of targets) {
|
|
205
|
+
if (!await mode(target)) ok = false;
|
|
137
206
|
}
|
|
138
|
-
|
|
207
|
+
if (!ok) process.exit(1);
|
|
139
208
|
return;
|
|
140
209
|
}
|
|
141
|
-
await run(
|
|
210
|
+
for (const target of targets) await run(target);
|
|
142
211
|
if (watchMode) {
|
|
143
|
-
const
|
|
144
|
-
const makeHandler = (label) => (file) => {
|
|
145
|
-
console.log(`${label}: ${file}`);
|
|
146
|
-
run(runOptions).catch(console.error);
|
|
147
|
-
};
|
|
148
|
-
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
149
|
-
watch(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
212
|
+
for (const target of targets) watchTarget(target);
|
|
150
213
|
console.log("Watching for changes...");
|
|
151
214
|
}
|
|
152
215
|
}
|
|
153
216
|
main().catch((err) => {
|
|
154
|
-
console.error(err);
|
|
217
|
+
console.error(err instanceof CliError ? err.message : err);
|
|
155
218
|
process.exit(1);
|
|
156
219
|
});
|
package/dist/esbuild.cjs
CHANGED
|
@@ -51,6 +51,11 @@ function stepQuote(text, i, quote) {
|
|
|
51
51
|
return { consumed: 1, closed: false };
|
|
52
52
|
}
|
|
53
53
|
function stripComments(text) {
|
|
54
|
+
return stripCommentsWithMap(text).text;
|
|
55
|
+
}
|
|
56
|
+
function stripCommentsWithMap(text) {
|
|
57
|
+
const removed = [];
|
|
58
|
+
const comments = [];
|
|
54
59
|
let result = "";
|
|
55
60
|
let quote = null;
|
|
56
61
|
let urlDepth = 0;
|
|
@@ -85,17 +90,20 @@ function stripComments(text) {
|
|
|
85
90
|
result += char;
|
|
86
91
|
continue;
|
|
87
92
|
}
|
|
93
|
+
comments.push([i, end + 2]);
|
|
94
|
+
removed.push({ at: result.length, length: end + 2 - i });
|
|
88
95
|
i = end + 1;
|
|
89
96
|
continue;
|
|
90
97
|
}
|
|
91
98
|
if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
|
|
92
99
|
const nl = text.indexOf("\n", i);
|
|
100
|
+
removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
|
|
93
101
|
i = nl === -1 ? text.length - 1 : nl - 1;
|
|
94
102
|
continue;
|
|
95
103
|
}
|
|
96
104
|
result += char;
|
|
97
105
|
}
|
|
98
|
-
return result;
|
|
106
|
+
return { text: result, removed, comments };
|
|
99
107
|
}
|
|
100
108
|
function extractBlock(text, start) {
|
|
101
109
|
let depth = 1;
|
|
@@ -159,12 +167,12 @@ function extractValue(text, start) {
|
|
|
159
167
|
}
|
|
160
168
|
return text.slice(start, i).trim();
|
|
161
169
|
}
|
|
162
|
-
function forEachProperty(block, onProperty) {
|
|
170
|
+
function forEachProperty(block, onProperty, offset = 0) {
|
|
163
171
|
const masked = maskQuotedContent(block);
|
|
164
172
|
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
165
173
|
const name = prop[0];
|
|
166
174
|
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
167
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
175
|
+
onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
|
|
168
176
|
}
|
|
169
177
|
}
|
|
170
178
|
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
@@ -185,7 +193,7 @@ var BASE_SELECTORS = [":root", "@theme"];
|
|
|
185
193
|
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
186
194
|
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
187
195
|
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
188
|
-
forEachProperty(block, onProperty);
|
|
196
|
+
forEachProperty(block, onProperty, bodyStart);
|
|
189
197
|
});
|
|
190
198
|
}
|
|
191
199
|
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
@@ -205,30 +213,73 @@ function forEachMediaBlock(stripped, media, onBlock) {
|
|
|
205
213
|
}
|
|
206
214
|
}
|
|
207
215
|
}
|
|
216
|
+
function parseDocComment(body) {
|
|
217
|
+
const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
|
|
218
|
+
const doc = {};
|
|
219
|
+
const description = [];
|
|
220
|
+
let inTags = false;
|
|
221
|
+
for (const line of lines) {
|
|
222
|
+
const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
|
|
223
|
+
if (tag) {
|
|
224
|
+
inTags = true;
|
|
225
|
+
if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
|
|
226
|
+
} else if (!inTags) {
|
|
227
|
+
description.push(line);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const text = description.join("\n").trim();
|
|
231
|
+
if (text) doc.description = text;
|
|
232
|
+
return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
|
|
233
|
+
}
|
|
234
|
+
function makeDocReader(css, stripped) {
|
|
235
|
+
const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
|
|
236
|
+
return (strippedPos) => {
|
|
237
|
+
let end = toRawPosition(stripped, strippedPos);
|
|
238
|
+
while (end > 0 && /\s/.test(css[end - 1])) end--;
|
|
239
|
+
const start = commentStartByEnd.get(end);
|
|
240
|
+
if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
|
|
241
|
+
return parseDocComment(css.slice(start + 3, end - 2));
|
|
242
|
+
};
|
|
243
|
+
}
|
|
208
244
|
function parseThemedDeclarations(css, selectors, themes) {
|
|
209
|
-
const
|
|
245
|
+
const strippedCss = stripCommentsWithMap(css);
|
|
246
|
+
const stripped = strippedCss.text;
|
|
247
|
+
const docAt = makeDocReader(css, strippedCss);
|
|
248
|
+
const themeDocs = /* @__PURE__ */ new Map();
|
|
210
249
|
const themeValues = /* @__PURE__ */ new Map();
|
|
211
250
|
const skip = [];
|
|
212
251
|
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
213
252
|
const values = /* @__PURE__ */ new Map();
|
|
214
253
|
themeValues.set(themeName, values);
|
|
215
|
-
const collect = (block) => forEachProperty(block, (name, value) =>
|
|
254
|
+
const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
|
|
255
|
+
values.set(name, value);
|
|
256
|
+
const doc = docAt(position);
|
|
257
|
+
if (doc) themeDocs.set(name, doc);
|
|
258
|
+
}, offset);
|
|
216
259
|
const selector = themeSelector.trim();
|
|
217
260
|
if (/^@media\b/i.test(selector)) {
|
|
218
261
|
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
219
262
|
skip.push(range);
|
|
220
|
-
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
263
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
|
|
221
264
|
});
|
|
222
265
|
} else {
|
|
223
266
|
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
224
267
|
skip.push(range);
|
|
225
|
-
collect(block);
|
|
268
|
+
collect(block, range[0]);
|
|
226
269
|
});
|
|
227
270
|
}
|
|
228
271
|
}
|
|
229
272
|
const declarations = /* @__PURE__ */ new Map();
|
|
230
|
-
|
|
231
|
-
|
|
273
|
+
const docs = /* @__PURE__ */ new Map();
|
|
274
|
+
scanDeclarations(css, selectors, (name, value, position) => {
|
|
275
|
+
declarations.set(name, value);
|
|
276
|
+
const doc = docAt(position);
|
|
277
|
+
if (doc) docs.set(name, doc);
|
|
278
|
+
}, skip, stripped);
|
|
279
|
+
for (const [name, doc] of themeDocs) {
|
|
280
|
+
if (!docs.has(name)) docs.set(name, doc);
|
|
281
|
+
}
|
|
282
|
+
return { declarations, themes: themeValues, docs };
|
|
232
283
|
}
|
|
233
284
|
var PROPERTY_DESCRIPTORS = [
|
|
234
285
|
["syntax", "syntax"],
|
|
@@ -259,6 +310,14 @@ function parsePropertyRules(css) {
|
|
|
259
310
|
}
|
|
260
311
|
return rules;
|
|
261
312
|
}
|
|
313
|
+
function toRawPosition(stripped, strippedPos) {
|
|
314
|
+
let rawPos = strippedPos;
|
|
315
|
+
for (const { at, length } of stripped.removed) {
|
|
316
|
+
if (at > strippedPos) break;
|
|
317
|
+
rawPos += length;
|
|
318
|
+
}
|
|
319
|
+
return rawPos;
|
|
320
|
+
}
|
|
262
321
|
|
|
263
322
|
// src/scanner.ts
|
|
264
323
|
function normalizePatterns(patterns) {
|
|
@@ -290,15 +349,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
290
349
|
const declarations = /* @__PURE__ */ new Map();
|
|
291
350
|
const properties = /* @__PURE__ */ new Map();
|
|
292
351
|
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
352
|
+
const docs = /* @__PURE__ */ new Map();
|
|
293
353
|
for (const result of perFile) {
|
|
294
354
|
if (!result) continue;
|
|
295
355
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
296
356
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
357
|
+
for (const [name, doc] of result.docs) docs.set(name, doc);
|
|
297
358
|
for (const [theme, values] of result.themes) {
|
|
298
359
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
299
360
|
}
|
|
300
361
|
}
|
|
301
|
-
return { declarations, properties, themes: themeValues };
|
|
362
|
+
return { declarations, properties, themes: themeValues, docs };
|
|
302
363
|
}
|
|
303
364
|
var ROOT_RE = /\bcssVars\b/g;
|
|
304
365
|
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
@@ -430,7 +491,8 @@ function entryMeta(name, options) {
|
|
|
430
491
|
name,
|
|
431
492
|
value: options.declarations?.get(name),
|
|
432
493
|
syntax: options.properties?.get(name)?.syntax,
|
|
433
|
-
...themes.length > 0 ? { themes } : {}
|
|
494
|
+
...themes.length > 0 ? { themes } : {},
|
|
495
|
+
...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
|
|
434
496
|
};
|
|
435
497
|
}
|
|
436
498
|
function buildEntries(varNames, options) {
|
|
@@ -470,8 +532,12 @@ function buildGroupedEntries(varNames, options) {
|
|
|
470
532
|
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
471
533
|
return { groups, ungrouped };
|
|
472
534
|
}
|
|
473
|
-
|
|
474
|
-
|
|
535
|
+
var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
|
|
536
|
+
function renderJsDoc(tags, indent) {
|
|
537
|
+
if (tags.length === 0) return [];
|
|
538
|
+
if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
|
|
539
|
+
const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
|
|
540
|
+
return [`${indent}/**`, ...body, `${indent} */`];
|
|
475
541
|
}
|
|
476
542
|
function unquoteCssString(value) {
|
|
477
543
|
const quote = value[0];
|
|
@@ -480,11 +546,15 @@ function unquoteCssString(value) {
|
|
|
480
546
|
}
|
|
481
547
|
return value;
|
|
482
548
|
}
|
|
483
|
-
function
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
549
|
+
function entryTags({ value, syntax, themes, doc }) {
|
|
550
|
+
const deprecated = doc?.deprecated;
|
|
551
|
+
return [
|
|
552
|
+
...doc?.description ? [doc.description] : [],
|
|
553
|
+
...value ? [`@default ${value}`] : [],
|
|
554
|
+
...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
|
|
555
|
+
...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
|
|
556
|
+
...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
|
|
557
|
+
];
|
|
488
558
|
}
|
|
489
559
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
490
560
|
function parseEnumSyntax(syntax) {
|
|
@@ -516,11 +586,9 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
516
586
|
return blocks;
|
|
517
587
|
}
|
|
518
588
|
function renderEntryLines(entries, indent, lineFor) {
|
|
519
|
-
return entries.flatMap((
|
|
520
|
-
...
|
|
521
|
-
|
|
522
|
-
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
523
|
-
`${indent}${lineFor(key, name)}`
|
|
589
|
+
return entries.flatMap((entry) => [
|
|
590
|
+
...renderJsDoc(entryTags(entry), indent),
|
|
591
|
+
`${indent}${lineFor(entry.key, entry.name)}`
|
|
524
592
|
]);
|
|
525
593
|
}
|
|
526
594
|
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
@@ -567,11 +635,17 @@ var HELPERS_JS = [
|
|
|
567
635
|
"",
|
|
568
636
|
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
569
637
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
638
|
+
"}",
|
|
639
|
+
"",
|
|
640
|
+
"export function withFallback(ref, fallback) {",
|
|
641
|
+
" return `${ref.slice(0, -1)}, ${fallback})`;",
|
|
570
642
|
"}"
|
|
571
643
|
];
|
|
572
644
|
var HELPERS_DTS = [
|
|
573
645
|
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
574
|
-
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
646
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
|
|
647
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
648
|
+
"export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
|
|
575
649
|
];
|
|
576
650
|
function generateJs(varNames, ...args) {
|
|
577
651
|
const options = normalizeOptions(args);
|
|
@@ -625,6 +699,8 @@ function generateTokens(varNames, options = {}) {
|
|
|
625
699
|
const token = { $value: resolve2(value) };
|
|
626
700
|
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
627
701
|
if (type) token.$type = type;
|
|
702
|
+
if (meta.doc?.description) token.$description = meta.doc.description;
|
|
703
|
+
if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
|
|
628
704
|
if (meta.themes) {
|
|
629
705
|
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve2(themeValue)]));
|
|
630
706
|
token.$extensions = { "css-typed-vars": { themes } };
|
|
@@ -687,14 +763,15 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
|
|
|
687
763
|
}
|
|
688
764
|
return used;
|
|
689
765
|
};
|
|
690
|
-
const generatorOptions = ({ declarations, properties, themes }) => ({
|
|
766
|
+
const generatorOptions = ({ declarations, properties, themes, docs }) => ({
|
|
691
767
|
prefix: options.prefix,
|
|
692
768
|
naming: options.naming,
|
|
693
769
|
declarations,
|
|
694
770
|
group: options.group,
|
|
695
771
|
properties,
|
|
696
772
|
helpers: options.helpers,
|
|
697
|
-
themes
|
|
773
|
+
themes,
|
|
774
|
+
docs
|
|
698
775
|
});
|
|
699
776
|
const resolveNames = async (scanned) => {
|
|
700
777
|
const names = collectVarNames(scanned);
|
package/dist/esbuild.d.cts
CHANGED
package/dist/esbuild.d.ts
CHANGED
package/dist/esbuild.js
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
declare function parseVarNames(css: string, selectors?: string[]): string[];
|
|
2
2
|
declare function parseVarDeclarations(css: string, selectors?: string[]): Map<string, string>;
|
|
3
|
+
interface VarDoc {
|
|
4
|
+
/** Free text of the comment, before any tag. */
|
|
5
|
+
description?: string;
|
|
6
|
+
/** `true` for a bare `@deprecated`, or its reason text. */
|
|
7
|
+
deprecated?: string | true;
|
|
8
|
+
}
|
|
3
9
|
interface ThemedDeclarations {
|
|
4
10
|
/** Base values, from `:root`/`@theme`/`selectors` blocks outside any theme block. */
|
|
5
11
|
declarations: Map<string, string>;
|
|
6
12
|
/** Per theme name, the values declared inside that theme's blocks. */
|
|
7
13
|
themes: Map<string, Map<string, string>>;
|
|
14
|
+
/** `/** ... *\/` doc comments placed directly before a declaration — from a base block, else from a theme block. */
|
|
15
|
+
docs: Map<string, VarDoc>;
|
|
8
16
|
}
|
|
9
17
|
declare function parseThemedDeclarations(css: string, selectors: string[] | undefined, themes: Record<string, string>): ThemedDeclarations;
|
|
10
18
|
interface PropertyRule {
|
|
@@ -13,6 +21,16 @@ interface PropertyRule {
|
|
|
13
21
|
initialValue?: string;
|
|
14
22
|
}
|
|
15
23
|
declare function parsePropertyRules(css: string): Map<string, PropertyRule>;
|
|
24
|
+
interface VarReference {
|
|
25
|
+
name: string;
|
|
26
|
+
/** Whether the reference has a fallback, e.g. `var(--x, red)`. */
|
|
27
|
+
hasFallback: boolean;
|
|
28
|
+
/** 1-based line and column of `var(` in the original css. */
|
|
29
|
+
line: number;
|
|
30
|
+
column: number;
|
|
31
|
+
}
|
|
32
|
+
declare function parseVarReferences(css: string): VarReference[];
|
|
33
|
+
declare function parseDeclaredNames(css: string): Set<string>;
|
|
16
34
|
|
|
17
35
|
type NamingConvention = 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal';
|
|
18
36
|
interface GeneratorOptions {
|
|
@@ -27,6 +45,8 @@ interface GeneratorOptions {
|
|
|
27
45
|
helpers?: boolean;
|
|
28
46
|
/** Per theme name, the values declared for it, emitted as `@theme <name> <value>` JSDoc tags. */
|
|
29
47
|
themes?: Map<string, Map<string, string>>;
|
|
48
|
+
/** CSS doc comments per var name, emitted as the JSDoc description and `@deprecated` tag. */
|
|
49
|
+
docs?: Map<string, VarDoc>;
|
|
30
50
|
}
|
|
31
51
|
type LegacyArgs = [
|
|
32
52
|
prefix?: string,
|
|
@@ -46,4 +66,4 @@ declare function generateDeclaration(varNames: string[], options?: GeneratorOpti
|
|
|
46
66
|
declare function generateDeclaration(varNames: string[], ...args: LegacyArgs): string;
|
|
47
67
|
declare function generateTokens(varNames: string[], options?: GeneratorOptions): string;
|
|
48
68
|
|
|
49
|
-
export { type GeneratorOptions as G, type NamingConvention as N, type PropertyRule as P, type ThemedDeclarations as T,
|
|
69
|
+
export { type GeneratorOptions as G, type NamingConvention as N, type PropertyRule as P, type ThemedDeclarations as T, type VarReference as V, type VarDoc as a, generateDeclaration as b, generateJs as c, generateTokens as d, parsePropertyRules as e, parseThemedDeclarations as f, generateCode as g, parseVarDeclarations as h, parseVarNames as i, parseVarReferences as j, parseDeclaredNames as p };
|