css-typed-vars 0.7.0 → 0.9.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 +119 -16
- package/dist/{chunk-HBUSLYYB.js → chunk-66NEMXYL.js} +14 -8
- package/dist/{chunk-6YWE4A6S.js → chunk-DHBPPGOE.js} +186 -31
- package/dist/{chunk-PLO2JWR7.js → chunk-TB5PSGEF.js} +24 -8
- package/dist/cli.cjs +464 -126
- package/dist/cli.js +280 -89
- package/dist/esbuild.cjs +145 -39
- 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 +200 -39
- package/dist/index.d.cts +24 -4
- package/dist/index.d.ts +24 -4
- package/dist/index.js +12 -2
- package/dist/rollup.cjs +145 -39
- package/dist/rollup.d.cts +1 -1
- package/dist/rollup.d.ts +1 -1
- package/dist/rollup.js +2 -2
- package/dist/unplugin.cjs +145 -39
- package/dist/unplugin.d.cts +1 -1
- package/dist/unplugin.d.ts +1 -1
- package/dist/unplugin.js +2 -2
- package/dist/vite.cjs +145 -39
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +2 -2
- package/dist/webpack.cjs +145 -39
- package/dist/webpack.d.cts +1 -1
- package/dist/webpack.d.ts +1 -1
- package/dist/webpack.js +2 -2
- package/package.json +3 -1
package/dist/cli.cjs
CHANGED
|
@@ -28,18 +28,31 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
|
|
|
28
28
|
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
29
29
|
|
|
30
30
|
// src/cli.ts
|
|
31
|
-
var
|
|
32
|
-
var
|
|
31
|
+
var import_promises4 = require("fs/promises");
|
|
32
|
+
var import_node_path4 = require("path");
|
|
33
33
|
var import_node_url = require("url");
|
|
34
34
|
var import_chokidar = require("chokidar");
|
|
35
35
|
|
|
36
36
|
// src/index.ts
|
|
37
|
-
var
|
|
37
|
+
var import_promises3 = require("fs/promises");
|
|
38
|
+
var import_node_path3 = require("path");
|
|
39
|
+
|
|
40
|
+
// src/write.ts
|
|
41
|
+
var import_promises = require("fs/promises");
|
|
38
42
|
var import_node_path = require("path");
|
|
43
|
+
async function writeOutput(path, content) {
|
|
44
|
+
const current = await (0, import_promises.readFile)(path, "utf8").catch(() => null);
|
|
45
|
+
if (current === content) return false;
|
|
46
|
+
await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
|
|
47
|
+
await (0, import_promises.writeFile)(path, content, "utf8");
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
39
50
|
|
|
40
51
|
// src/scanner.ts
|
|
41
|
-
var
|
|
52
|
+
var import_promises2 = require("fs/promises");
|
|
53
|
+
var import_node_path2 = require("path");
|
|
42
54
|
var import_fast_glob = __toESM(require("fast-glob"), 1);
|
|
55
|
+
var import_picomatch = __toESM(require("picomatch"), 1);
|
|
43
56
|
|
|
44
57
|
// src/parser.ts
|
|
45
58
|
function stepQuote(text, i, quote) {
|
|
@@ -49,6 +62,11 @@ function stepQuote(text, i, quote) {
|
|
|
49
62
|
return { consumed: 1, closed: false };
|
|
50
63
|
}
|
|
51
64
|
function stripComments(text) {
|
|
65
|
+
return stripCommentsWithMap(text).text;
|
|
66
|
+
}
|
|
67
|
+
function stripCommentsWithMap(text) {
|
|
68
|
+
const removed = [];
|
|
69
|
+
const comments = [];
|
|
52
70
|
let result = "";
|
|
53
71
|
let quote = null;
|
|
54
72
|
let urlDepth = 0;
|
|
@@ -83,17 +101,20 @@ function stripComments(text) {
|
|
|
83
101
|
result += char;
|
|
84
102
|
continue;
|
|
85
103
|
}
|
|
104
|
+
comments.push([i, end + 2]);
|
|
105
|
+
removed.push({ at: result.length, length: end + 2 - i });
|
|
86
106
|
i = end + 1;
|
|
87
107
|
continue;
|
|
88
108
|
}
|
|
89
109
|
if (char === "/" && text[i + 1] === "/" && text[i - 1] !== ":") {
|
|
90
110
|
const nl = text.indexOf("\n", i);
|
|
111
|
+
removed.push({ at: result.length, length: (nl === -1 ? text.length : nl) - i });
|
|
91
112
|
i = nl === -1 ? text.length - 1 : nl - 1;
|
|
92
113
|
continue;
|
|
93
114
|
}
|
|
94
115
|
result += char;
|
|
95
116
|
}
|
|
96
|
-
return result;
|
|
117
|
+
return { text: result, removed, comments };
|
|
97
118
|
}
|
|
98
119
|
function extractBlock(text, start) {
|
|
99
120
|
let depth = 1;
|
|
@@ -157,12 +178,12 @@ function extractValue(text, start) {
|
|
|
157
178
|
}
|
|
158
179
|
return text.slice(start, i).trim();
|
|
159
180
|
}
|
|
160
|
-
function forEachProperty(block, onProperty) {
|
|
181
|
+
function forEachProperty(block, onProperty, offset = 0) {
|
|
161
182
|
const masked = maskQuotedContent(block);
|
|
162
183
|
for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
|
|
163
184
|
const name = prop[0];
|
|
164
185
|
const colonIndex = block.indexOf(":", prop.index + name.length);
|
|
165
|
-
onProperty(name, extractValue(block, colonIndex + 1));
|
|
186
|
+
onProperty(name, extractValue(block, colonIndex + 1), offset + prop.index);
|
|
166
187
|
}
|
|
167
188
|
}
|
|
168
189
|
function forEachSelectorBlock(stripped, selectors, onBlock) {
|
|
@@ -183,7 +204,7 @@ var BASE_SELECTORS = [":root", "@theme"];
|
|
|
183
204
|
function scanDeclarations(css, selectors, onProperty, skip = [], stripped = stripComments(css)) {
|
|
184
205
|
forEachSelectorBlock(stripped, [...BASE_SELECTORS, ...selectors ?? []], (block, [bodyStart]) => {
|
|
185
206
|
if (skip.some(([s, e]) => bodyStart >= s && bodyStart < e)) return;
|
|
186
|
-
forEachProperty(block, onProperty);
|
|
207
|
+
forEachProperty(block, onProperty, bodyStart);
|
|
187
208
|
});
|
|
188
209
|
}
|
|
189
210
|
var normalizePrelude = (prelude) => prelude.replace(/\s+/g, "").toLowerCase();
|
|
@@ -203,30 +224,73 @@ function forEachMediaBlock(stripped, media, onBlock) {
|
|
|
203
224
|
}
|
|
204
225
|
}
|
|
205
226
|
}
|
|
227
|
+
function parseDocComment(body) {
|
|
228
|
+
const lines = body.split("\n").map((line) => line.replace(/^\s*\*?\s?/, "").trimEnd());
|
|
229
|
+
const doc = {};
|
|
230
|
+
const description = [];
|
|
231
|
+
let inTags = false;
|
|
232
|
+
for (const line of lines) {
|
|
233
|
+
const tag = /^@(\w+)\s*(.*)$/.exec(line.trim());
|
|
234
|
+
if (tag) {
|
|
235
|
+
inTags = true;
|
|
236
|
+
if (tag[1] === "deprecated") doc.deprecated = tag[2].trim() || true;
|
|
237
|
+
} else if (!inTags) {
|
|
238
|
+
description.push(line);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const text = description.join("\n").trim();
|
|
242
|
+
if (text) doc.description = text;
|
|
243
|
+
return doc.description !== void 0 || doc.deprecated !== void 0 ? doc : void 0;
|
|
244
|
+
}
|
|
245
|
+
function makeDocReader(css, stripped) {
|
|
246
|
+
const commentStartByEnd = new Map(stripped.comments.map(([start, end]) => [end, start]));
|
|
247
|
+
return (strippedPos) => {
|
|
248
|
+
let end = toRawPosition(stripped, strippedPos);
|
|
249
|
+
while (end > 0 && /\s/.test(css[end - 1])) end--;
|
|
250
|
+
const start = commentStartByEnd.get(end);
|
|
251
|
+
if (start === void 0 || !css.startsWith("/**", start) || end - start <= 4) return void 0;
|
|
252
|
+
return parseDocComment(css.slice(start + 3, end - 2));
|
|
253
|
+
};
|
|
254
|
+
}
|
|
206
255
|
function parseThemedDeclarations(css, selectors, themes) {
|
|
207
|
-
const
|
|
256
|
+
const strippedCss = stripCommentsWithMap(css);
|
|
257
|
+
const stripped = strippedCss.text;
|
|
258
|
+
const docAt = makeDocReader(css, strippedCss);
|
|
259
|
+
const themeDocs = /* @__PURE__ */ new Map();
|
|
208
260
|
const themeValues = /* @__PURE__ */ new Map();
|
|
209
261
|
const skip = [];
|
|
210
262
|
for (const [themeName, themeSelector] of Object.entries(themes)) {
|
|
211
263
|
const values = /* @__PURE__ */ new Map();
|
|
212
264
|
themeValues.set(themeName, values);
|
|
213
|
-
const collect = (block) => forEachProperty(block, (name, value) =>
|
|
265
|
+
const collect = (block, offset) => forEachProperty(block, (name, value, position) => {
|
|
266
|
+
values.set(name, value);
|
|
267
|
+
const doc = docAt(position);
|
|
268
|
+
if (doc) themeDocs.set(name, doc);
|
|
269
|
+
}, offset);
|
|
214
270
|
const selector = themeSelector.trim();
|
|
215
271
|
if (/^@media\b/i.test(selector)) {
|
|
216
272
|
forEachMediaBlock(stripped, selector, (mediaBlock, range) => {
|
|
217
273
|
skip.push(range);
|
|
218
|
-
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, collect);
|
|
274
|
+
forEachSelectorBlock(mediaBlock, BASE_SELECTORS, (block, [innerStart]) => collect(block, range[0] + innerStart));
|
|
219
275
|
});
|
|
220
276
|
} else {
|
|
221
277
|
forEachSelectorBlock(stripped, [selector], (block, range) => {
|
|
222
278
|
skip.push(range);
|
|
223
|
-
collect(block);
|
|
279
|
+
collect(block, range[0]);
|
|
224
280
|
});
|
|
225
281
|
}
|
|
226
282
|
}
|
|
227
283
|
const declarations = /* @__PURE__ */ new Map();
|
|
228
|
-
|
|
229
|
-
|
|
284
|
+
const docs = /* @__PURE__ */ new Map();
|
|
285
|
+
scanDeclarations(css, selectors, (name, value, position) => {
|
|
286
|
+
declarations.set(name, value);
|
|
287
|
+
const doc = docAt(position);
|
|
288
|
+
if (doc) docs.set(name, doc);
|
|
289
|
+
}, skip, stripped);
|
|
290
|
+
for (const [name, doc] of themeDocs) {
|
|
291
|
+
if (!docs.has(name)) docs.set(name, doc);
|
|
292
|
+
}
|
|
293
|
+
return { declarations, themes: themeValues, docs };
|
|
230
294
|
}
|
|
231
295
|
var PROPERTY_DESCRIPTORS = [
|
|
232
296
|
["syntax", "syntax"],
|
|
@@ -257,6 +321,35 @@ function parsePropertyRules(css) {
|
|
|
257
321
|
}
|
|
258
322
|
return rules;
|
|
259
323
|
}
|
|
324
|
+
function toRawPosition(stripped, strippedPos) {
|
|
325
|
+
let rawPos = strippedPos;
|
|
326
|
+
for (const { at, length } of stripped.removed) {
|
|
327
|
+
if (at > strippedPos) break;
|
|
328
|
+
rawPos += length;
|
|
329
|
+
}
|
|
330
|
+
return rawPos;
|
|
331
|
+
}
|
|
332
|
+
function parseVarReferences(css) {
|
|
333
|
+
const stripped = stripCommentsWithMap(css);
|
|
334
|
+
const masked = maskQuotedContent(stripped.text);
|
|
335
|
+
const lineStarts = [0];
|
|
336
|
+
for (let i = 0; i < css.length; i++) if (css[i] === "\n") lineStarts.push(i + 1);
|
|
337
|
+
const refs = [];
|
|
338
|
+
for (const match of masked.matchAll(/\bvar\(\s*(--[\w-]+)\s*(,)?/gi)) {
|
|
339
|
+
const rawPos = toRawPosition(stripped, match.index);
|
|
340
|
+
let line = lineStarts.length - 1;
|
|
341
|
+
while (lineStarts[line] > rawPos) line--;
|
|
342
|
+
refs.push({ name: match[1], hasFallback: match[2] === ",", line: line + 1, column: rawPos - lineStarts[line] + 1 });
|
|
343
|
+
}
|
|
344
|
+
return refs;
|
|
345
|
+
}
|
|
346
|
+
function parseDeclaredNames(css) {
|
|
347
|
+
const masked = maskQuotedContent(stripComments(css));
|
|
348
|
+
const names = /* @__PURE__ */ new Set();
|
|
349
|
+
for (const match of masked.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) names.add(match[1]);
|
|
350
|
+
for (const match of masked.matchAll(/@property\s+(--[\w-]+)/g)) names.add(match[1]);
|
|
351
|
+
return names;
|
|
352
|
+
}
|
|
260
353
|
|
|
261
354
|
// src/scanner.ts
|
|
262
355
|
function normalizePatterns(patterns) {
|
|
@@ -277,7 +370,7 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
277
370
|
files.map(async (file) => {
|
|
278
371
|
let css;
|
|
279
372
|
try {
|
|
280
|
-
css = await (0,
|
|
373
|
+
css = await (0, import_promises2.readFile)(file, "utf8");
|
|
281
374
|
} catch (err) {
|
|
282
375
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
283
376
|
return null;
|
|
@@ -288,15 +381,17 @@ async function scanCss(patterns, exclude, selectors, themes = {}) {
|
|
|
288
381
|
const declarations = /* @__PURE__ */ new Map();
|
|
289
382
|
const properties = /* @__PURE__ */ new Map();
|
|
290
383
|
const themeValues = new Map(Object.keys(themes).map((theme) => [theme, /* @__PURE__ */ new Map()]));
|
|
384
|
+
const docs = /* @__PURE__ */ new Map();
|
|
291
385
|
for (const result of perFile) {
|
|
292
386
|
if (!result) continue;
|
|
293
387
|
for (const [name, value] of result.declarations) declarations.set(name, value);
|
|
294
388
|
for (const [name, rule] of result.properties) properties.set(name, rule);
|
|
389
|
+
for (const [name, doc] of result.docs) docs.set(name, doc);
|
|
295
390
|
for (const [theme, values] of result.themes) {
|
|
296
391
|
for (const [name, value] of values) themeValues.get(theme).set(name, value);
|
|
297
392
|
}
|
|
298
393
|
}
|
|
299
|
-
return { declarations, properties, themes: themeValues };
|
|
394
|
+
return { declarations, properties, themes: themeValues, docs };
|
|
300
395
|
}
|
|
301
396
|
var ROOT_RE = /\bcssVars\b/g;
|
|
302
397
|
var ACCESS_RE = /\s*(?:\.\s*([A-Za-z_$][\w$]*)|\[\s*(['"`])((?:(?!\2).)*)\2\s*\])/y;
|
|
@@ -323,7 +418,7 @@ async function scanUsage(patterns, exclude) {
|
|
|
323
418
|
const texts = await Promise.all(
|
|
324
419
|
files.map(async (file) => {
|
|
325
420
|
try {
|
|
326
|
-
return await (0,
|
|
421
|
+
return await (0, import_promises2.readFile)(file, "utf8");
|
|
327
422
|
} catch (err) {
|
|
328
423
|
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
329
424
|
return "";
|
|
@@ -333,6 +428,29 @@ async function scanUsage(patterns, exclude) {
|
|
|
333
428
|
for (const text of texts) extractUsage(text, usage);
|
|
334
429
|
return usage;
|
|
335
430
|
}
|
|
431
|
+
async function scanReferences(patterns, exclude) {
|
|
432
|
+
const normalized = normalizePatterns(patterns);
|
|
433
|
+
const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
|
|
434
|
+
const files = (await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude })).sort();
|
|
435
|
+
const perFile = await Promise.all(
|
|
436
|
+
files.map(async (file) => {
|
|
437
|
+
try {
|
|
438
|
+
return { file, css: await (0, import_promises2.readFile)(file, "utf8") };
|
|
439
|
+
} catch (err) {
|
|
440
|
+
console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
})
|
|
444
|
+
);
|
|
445
|
+
const references = [];
|
|
446
|
+
const declared = /* @__PURE__ */ new Set();
|
|
447
|
+
for (const result of perFile) {
|
|
448
|
+
if (!result) continue;
|
|
449
|
+
for (const ref of parseVarReferences(result.css)) references.push({ ...ref, file: result.file });
|
|
450
|
+
for (const name of parseDeclaredNames(result.css)) declared.add(name);
|
|
451
|
+
}
|
|
452
|
+
return { references, declared };
|
|
453
|
+
}
|
|
336
454
|
|
|
337
455
|
// src/generator.ts
|
|
338
456
|
var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
|
|
@@ -428,7 +546,8 @@ function entryMeta(name, options) {
|
|
|
428
546
|
name,
|
|
429
547
|
value: options.declarations?.get(name),
|
|
430
548
|
syntax: options.properties?.get(name)?.syntax,
|
|
431
|
-
...themes.length > 0 ? { themes } : {}
|
|
549
|
+
...themes.length > 0 ? { themes } : {},
|
|
550
|
+
...options.docs?.has(name) ? { doc: options.docs.get(name) } : {}
|
|
432
551
|
};
|
|
433
552
|
}
|
|
434
553
|
function buildEntries(varNames, options) {
|
|
@@ -468,8 +587,12 @@ function buildGroupedEntries(varNames, options) {
|
|
|
468
587
|
const ungrouped = [...ungroupedMap].map(([key, entry]) => ({ key, ...entry }));
|
|
469
588
|
return { groups, ungrouped };
|
|
470
589
|
}
|
|
471
|
-
|
|
472
|
-
|
|
590
|
+
var escapeComment = (text) => text.replace(/\*\//g, "*\\/");
|
|
591
|
+
function renderJsDoc(tags, indent) {
|
|
592
|
+
if (tags.length === 0) return [];
|
|
593
|
+
if (tags.length === 1 && !tags[0].includes("\n")) return [`${indent}/** ${escapeComment(tags[0])} */`];
|
|
594
|
+
const body = tags.flatMap((tag) => escapeComment(tag).split("\n")).map((line) => `${indent} * ${line}`.trimEnd());
|
|
595
|
+
return [`${indent}/**`, ...body, `${indent} */`];
|
|
473
596
|
}
|
|
474
597
|
function unquoteCssString(value) {
|
|
475
598
|
const quote = value[0];
|
|
@@ -478,11 +601,15 @@ function unquoteCssString(value) {
|
|
|
478
601
|
}
|
|
479
602
|
return value;
|
|
480
603
|
}
|
|
481
|
-
function
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
604
|
+
function entryTags({ value, syntax, themes, doc }) {
|
|
605
|
+
const deprecated = doc?.deprecated;
|
|
606
|
+
return [
|
|
607
|
+
...doc?.description ? [doc.description] : [],
|
|
608
|
+
...value ? [`@default ${value}`] : [],
|
|
609
|
+
...(themes ?? []).map(([theme, themeValue]) => `@theme ${theme} ${themeValue}`),
|
|
610
|
+
...syntax ? [`@syntax ${unquoteCssString(syntax)}`] : [],
|
|
611
|
+
...deprecated ? [deprecated === true ? "@deprecated" : `@deprecated ${deprecated}`] : []
|
|
612
|
+
];
|
|
486
613
|
}
|
|
487
614
|
var ENUM_SYNTAX_RE = /^[\w-]+(?:\s*\|\s*[\w-]+)+$/;
|
|
488
615
|
function parseEnumSyntax(syntax) {
|
|
@@ -514,11 +641,9 @@ function buildTailBlocks(varNames, group, properties) {
|
|
|
514
641
|
return blocks;
|
|
515
642
|
}
|
|
516
643
|
function renderEntryLines(entries, indent, lineFor) {
|
|
517
|
-
return entries.flatMap((
|
|
518
|
-
...
|
|
519
|
-
|
|
520
|
-
...syntax ? [formatSyntaxComment(syntax, indent)] : [],
|
|
521
|
-
`${indent}${lineFor(key, name)}`
|
|
644
|
+
return entries.flatMap((entry) => [
|
|
645
|
+
...renderJsDoc(entryTags(entry), indent),
|
|
646
|
+
`${indent}${lineFor(entry.key, entry.name)}`
|
|
522
647
|
]);
|
|
523
648
|
}
|
|
524
649
|
function renderGroupedBlock(varNames, options, indent, closeSuffix, lineFor) {
|
|
@@ -565,6 +690,12 @@ var HELPERS_TS = [
|
|
|
565
690
|
"",
|
|
566
691
|
"export function setCssVar(ref: CssVarRef, value: string, el: HTMLElement = document.documentElement): void {",
|
|
567
692
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
693
|
+
"}",
|
|
694
|
+
"",
|
|
695
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
696
|
+
"",
|
|
697
|
+
"export function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F> {",
|
|
698
|
+
" return `${ref.slice(0, -1)}, ${fallback})` as CssVarWithFallback<R, F>;",
|
|
568
699
|
"}"
|
|
569
700
|
];
|
|
570
701
|
var HELPERS_JS = [
|
|
@@ -574,11 +705,17 @@ var HELPERS_JS = [
|
|
|
574
705
|
"",
|
|
575
706
|
"export function setCssVar(ref, value, el = document.documentElement) {",
|
|
576
707
|
" el.style.setProperty(ref.slice(4, -1), value);",
|
|
708
|
+
"}",
|
|
709
|
+
"",
|
|
710
|
+
"export function withFallback(ref, fallback) {",
|
|
711
|
+
" return `${ref.slice(0, -1)}, ${fallback})`;",
|
|
577
712
|
"}"
|
|
578
713
|
];
|
|
579
714
|
var HELPERS_DTS = [
|
|
580
715
|
"export declare function getCssVar(ref: CssVarRef, el?: Element): string;",
|
|
581
|
-
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;"
|
|
716
|
+
"export declare function setCssVar(ref: CssVarRef, value: string, el?: HTMLElement): void;",
|
|
717
|
+
"export type CssVarWithFallback<R extends CssVarRef, F extends string | number> = R extends `var(${infer N})` ? `var(${N}, ${F})` : never;",
|
|
718
|
+
"export declare function withFallback<R extends CssVarRef, F extends string | number>(ref: R, fallback: F): CssVarWithFallback<R, F>;"
|
|
582
719
|
];
|
|
583
720
|
function generateCode(varNames, ...args2) {
|
|
584
721
|
const options = normalizeOptions(args2);
|
|
@@ -638,17 +775,19 @@ function generateTokens(varNames, options = {}) {
|
|
|
638
775
|
return value === void 0 ? [] : [{ meta, value, path: computeKeyPath(name, options.prefix, options.naming, options.group) }];
|
|
639
776
|
});
|
|
640
777
|
const paths = new Map(tokens.map(({ meta, path }) => [meta.name, path]));
|
|
641
|
-
const
|
|
778
|
+
const resolve4 = (value) => {
|
|
642
779
|
const target = paths.get(VAR_REF_RE.exec(value.trim())?.[1] ?? "");
|
|
643
780
|
return target ? `{${target.join(".")}}` : value;
|
|
644
781
|
};
|
|
645
782
|
const root = {};
|
|
646
783
|
for (const { meta, value, path } of tokens) {
|
|
647
|
-
const token = { $value:
|
|
784
|
+
const token = { $value: resolve4(value) };
|
|
648
785
|
const type = meta.syntax && TOKEN_TYPES[unquoteCssString(meta.syntax).trim()];
|
|
649
786
|
if (type) token.$type = type;
|
|
787
|
+
if (meta.doc?.description) token.$description = meta.doc.description;
|
|
788
|
+
if (meta.doc?.deprecated) token.$deprecated = meta.doc.deprecated;
|
|
650
789
|
if (meta.themes) {
|
|
651
|
-
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme,
|
|
790
|
+
const themes = Object.fromEntries(meta.themes.map(([theme, themeValue]) => [theme, resolve4(themeValue)]));
|
|
652
791
|
token.$extensions = { "css-typed-vars": { themes } };
|
|
653
792
|
}
|
|
654
793
|
const [key, leaf] = path;
|
|
@@ -692,6 +831,14 @@ async function findUnusedVars(options) {
|
|
|
692
831
|
const names = collectVarNames(scanned);
|
|
693
832
|
return partitionUnused(names, usage, options).unused;
|
|
694
833
|
}
|
|
834
|
+
function matchesIgnore(name, patterns) {
|
|
835
|
+
return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
836
|
+
}
|
|
837
|
+
async function findUndefinedRefs(options) {
|
|
838
|
+
const { references, declared } = await scanReferences(options.input, options.exclude);
|
|
839
|
+
const ignore = options.refsIgnore ?? [];
|
|
840
|
+
return references.filter((ref) => !declared.has(ref.name) && !matchesIgnore(ref.name, ignore));
|
|
841
|
+
}
|
|
695
842
|
async function computeOutputs(options) {
|
|
696
843
|
assertPruneCompatible(options);
|
|
697
844
|
const scanned = await scanCss(options.input, options.exclude, options.selectors, options.themes);
|
|
@@ -709,7 +856,7 @@ async function computeOutputs(options) {
|
|
|
709
856
|
}
|
|
710
857
|
names = used;
|
|
711
858
|
}
|
|
712
|
-
const outPath = (0,
|
|
859
|
+
const outPath = (0, import_node_path3.resolve)(options.output);
|
|
713
860
|
const generatorOptions = {
|
|
714
861
|
prefix: options.prefix,
|
|
715
862
|
naming: options.naming,
|
|
@@ -717,7 +864,8 @@ async function computeOutputs(options) {
|
|
|
717
864
|
group: options.group,
|
|
718
865
|
properties,
|
|
719
866
|
helpers: options.helpers,
|
|
720
|
-
themes: scanned.themes
|
|
867
|
+
themes: scanned.themes,
|
|
868
|
+
docs: scanned.docs
|
|
721
869
|
};
|
|
722
870
|
if (/\.json$/i.test(options.output)) {
|
|
723
871
|
return { outPath, content: generateTokens(names, generatorOptions) };
|
|
@@ -733,18 +881,18 @@ async function computeOutputs(options) {
|
|
|
733
881
|
}
|
|
734
882
|
async function generate(options) {
|
|
735
883
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
736
|
-
|
|
737
|
-
await (0, import_promises2.writeFile)(outPath, content, "utf8");
|
|
884
|
+
let written = await writeOutput(outPath, content);
|
|
738
885
|
if (dtsPath && dtsContent !== void 0) {
|
|
739
|
-
|
|
886
|
+
if (await writeOutput(dtsPath, dtsContent)) written = true;
|
|
740
887
|
}
|
|
888
|
+
return written;
|
|
741
889
|
}
|
|
742
890
|
async function checkGenerated(options) {
|
|
743
891
|
const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
|
|
744
|
-
const current = await (0,
|
|
892
|
+
const current = await (0, import_promises3.readFile)(outPath, "utf8").catch(() => null);
|
|
745
893
|
if (current !== content) return false;
|
|
746
894
|
if (dtsPath && dtsContent !== void 0) {
|
|
747
|
-
const currentDts = await (0,
|
|
895
|
+
const currentDts = await (0, import_promises3.readFile)(dtsPath, "utf8").catch(() => null);
|
|
748
896
|
if (currentDts !== dtsContent) return false;
|
|
749
897
|
}
|
|
750
898
|
return true;
|
|
@@ -768,127 +916,317 @@ var getArgs = (flag) => {
|
|
|
768
916
|
};
|
|
769
917
|
var watchMode = args.includes("--watch");
|
|
770
918
|
var checkMode = args.includes("--check");
|
|
771
|
-
var groupFlag = args.includes("--group");
|
|
772
|
-
var pruneFlag = args.includes("--prune");
|
|
773
919
|
var pruneCheckMode = args.includes("--prune-check");
|
|
774
|
-
var
|
|
920
|
+
var lintRefsMode = args.includes("--lint-refs");
|
|
921
|
+
var OPTION_FLAGS = [
|
|
922
|
+
"--input",
|
|
923
|
+
"--output",
|
|
924
|
+
"--exclude",
|
|
925
|
+
"--prefix",
|
|
926
|
+
"--naming",
|
|
927
|
+
"--selector",
|
|
928
|
+
"--theme",
|
|
929
|
+
"--group",
|
|
930
|
+
"--prune",
|
|
931
|
+
"--usage",
|
|
932
|
+
"--usage-exclude",
|
|
933
|
+
"--helpers",
|
|
934
|
+
"--refs-ignore"
|
|
935
|
+
];
|
|
936
|
+
var USAGE = "Usage: css-typed-vars --input <glob> --output <file> [options]";
|
|
937
|
+
var VALUE_FLAGS = [
|
|
938
|
+
"--input",
|
|
939
|
+
"--output",
|
|
940
|
+
"--exclude",
|
|
941
|
+
"--prefix",
|
|
942
|
+
"--naming",
|
|
943
|
+
"--selector",
|
|
944
|
+
"--theme",
|
|
945
|
+
"--usage",
|
|
946
|
+
"--usage-exclude",
|
|
947
|
+
"--refs-ignore",
|
|
948
|
+
"--config"
|
|
949
|
+
];
|
|
950
|
+
var BOOLEAN_FLAGS = [
|
|
951
|
+
"--group",
|
|
952
|
+
"--prune",
|
|
953
|
+
"--helpers",
|
|
954
|
+
"--watch",
|
|
955
|
+
"--check",
|
|
956
|
+
"--prune-check",
|
|
957
|
+
"--lint-refs",
|
|
958
|
+
"--version",
|
|
959
|
+
"-v",
|
|
960
|
+
"--help",
|
|
961
|
+
"-h"
|
|
962
|
+
];
|
|
963
|
+
var HELP = `${USAGE}
|
|
964
|
+
|
|
965
|
+
Generates typed constants for the CSS custom properties found in <glob>.
|
|
966
|
+
Options can also be set in css-typed-vars.config.{js,mjs,cjs,ts,mts,json}; flags take precedence.
|
|
967
|
+
|
|
968
|
+
Options:
|
|
969
|
+
--config <file> Config file to use instead of looking one up
|
|
970
|
+
--input <glob> CSS files to scan (repeatable)
|
|
971
|
+
--output <file> .ts, .js/.mjs/.cjs (plus a .d.ts), or .json (design tokens)
|
|
972
|
+
--exclude <glob> Files to skip (repeatable)
|
|
973
|
+
--prefix <prefix> Prefix every generated key
|
|
974
|
+
--naming <convention> camelCase (default), snake, kebab, constant or pascal
|
|
975
|
+
--selector <selector> Also scan this selector's blocks, not just :root/@theme (repeatable)
|
|
976
|
+
--theme <name>=<sel> Theme block, emitted as @theme JSDoc tags (repeatable)
|
|
977
|
+
--group Nest keys by the first hyphen segment (cssVars.color.primary)
|
|
978
|
+
--helpers Also emit CssVarRef and getCssVar/setCssVar/withFallback
|
|
979
|
+
--prune Drop vars with no cssVars.<key> usage (needs --usage)
|
|
980
|
+
--usage <glob> Source files to scan for cssVars usage (repeatable)
|
|
981
|
+
--usage-exclude <glob> Source files to skip in the usage scan (repeatable)
|
|
982
|
+
|
|
983
|
+
Modes:
|
|
984
|
+
--watch Regenerate when input (or, with --prune, usage) files change
|
|
985
|
+
--check Exit 1 if the output is out of date, without writing
|
|
986
|
+
--prune-check Exit 1 if any var has no cssVars.<key> usage (needs --usage)
|
|
987
|
+
--lint-refs Exit 1 on var() references to undeclared variables
|
|
988
|
+
--refs-ignore <name> Name or --prefix-* pattern for --lint-refs to skip (repeatable)
|
|
989
|
+
--version, -v Print the version
|
|
990
|
+
--help, -h Print this help
|
|
991
|
+
|
|
992
|
+
Docs: https://stanislavkozachenko.github.io/css-typed-vars/`;
|
|
993
|
+
function editDistance(a, b) {
|
|
994
|
+
let row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
995
|
+
for (let i = 1; i <= a.length; i++) {
|
|
996
|
+
const next = [i];
|
|
997
|
+
for (let j = 1; j <= b.length; j++) {
|
|
998
|
+
next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
999
|
+
}
|
|
1000
|
+
row = next;
|
|
1001
|
+
}
|
|
1002
|
+
return row[b.length];
|
|
1003
|
+
}
|
|
1004
|
+
function validateArgs() {
|
|
1005
|
+
for (let i = 0; i < args.length; i++) {
|
|
1006
|
+
const arg = args[i];
|
|
1007
|
+
if (VALUE_FLAGS.includes(arg)) {
|
|
1008
|
+
if (i + 1 >= args.length) throw new CliError(`css-typed-vars: ${arg} requires a value.`);
|
|
1009
|
+
i++;
|
|
1010
|
+
continue;
|
|
1011
|
+
}
|
|
1012
|
+
if (BOOLEAN_FLAGS.includes(arg)) continue;
|
|
1013
|
+
if (arg.startsWith("-")) {
|
|
1014
|
+
const known = [...VALUE_FLAGS, ...BOOLEAN_FLAGS].filter((flag) => flag.startsWith("--"));
|
|
1015
|
+
const closest = known.reduce((best, flag) => editDistance(arg, flag) < editDistance(arg, best) ? flag : best);
|
|
1016
|
+
const hint = editDistance(arg, closest) <= 2 ? ` Did you mean ${closest}?` : "";
|
|
1017
|
+
throw new CliError(`css-typed-vars: unknown option "${arg}".${hint} Run with --help to see all options.`);
|
|
1018
|
+
}
|
|
1019
|
+
throw new CliError(`css-typed-vars: unexpected argument "${arg}". If it's a glob, quote it so the shell doesn't expand it: --input "src/**/*.css".`);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
var CliError = class extends Error {
|
|
1023
|
+
};
|
|
1024
|
+
var CONFIG_FILES = [
|
|
1025
|
+
"css-typed-vars.config.js",
|
|
1026
|
+
"css-typed-vars.config.mjs",
|
|
1027
|
+
"css-typed-vars.config.cjs",
|
|
1028
|
+
"css-typed-vars.config.ts",
|
|
1029
|
+
"css-typed-vars.config.mts",
|
|
1030
|
+
"css-typed-vars.config.json"
|
|
1031
|
+
];
|
|
1032
|
+
async function importConfig(path) {
|
|
1033
|
+
if (/\.json$/i.test(path)) return JSON.parse(await (0, import_promises4.readFile)(path, "utf8"));
|
|
1034
|
+
const mod = await import((0, import_node_url.pathToFileURL)(path).href);
|
|
1035
|
+
return mod.default ?? {};
|
|
1036
|
+
}
|
|
775
1037
|
async function loadConfig() {
|
|
776
|
-
const
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
];
|
|
781
|
-
for (const file of candidates) {
|
|
782
|
-
const path = (0, import_node_path2.resolve)(process.cwd(), file);
|
|
1038
|
+
const explicit = getArg("--config");
|
|
1039
|
+
if (explicit !== void 0) {
|
|
1040
|
+
const path = (0, import_node_path4.resolve)(process.cwd(), explicit);
|
|
1041
|
+
if (!await exists(path)) throw new CliError(`css-typed-vars: config file "${explicit}" not found.`);
|
|
783
1042
|
try {
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
1043
|
+
return await importConfig(path);
|
|
1044
|
+
} catch (err) {
|
|
1045
|
+
throw new CliError(`css-typed-vars: failed to load config "${explicit}": ${err.message}`);
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
for (const file of CONFIG_FILES) {
|
|
1049
|
+
const path = (0, import_node_path4.resolve)(process.cwd(), file);
|
|
1050
|
+
if (!await exists(path)) continue;
|
|
1051
|
+
try {
|
|
1052
|
+
return await importConfig(path);
|
|
791
1053
|
} catch (err) {
|
|
792
|
-
const code = err.code;
|
|
793
|
-
if (code === "ENOENT" || code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") continue;
|
|
794
1054
|
console.warn(`css-typed-vars: failed to load config "${file}": ${err.message}`);
|
|
795
1055
|
}
|
|
796
1056
|
}
|
|
797
1057
|
return {};
|
|
798
1058
|
}
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
console.log(`Generated \u2192 ${options.output}`);
|
|
802
|
-
}
|
|
803
|
-
async function main() {
|
|
804
|
-
if (args.includes("--version") || args.includes("-v")) {
|
|
805
|
-
const pkg = JSON.parse(await (0, import_promises3.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
|
|
806
|
-
console.log(pkg.version);
|
|
807
|
-
process.exit(0);
|
|
808
|
-
}
|
|
809
|
-
const config = await loadConfig();
|
|
1059
|
+
var exists = (path) => (0, import_promises4.access)(path).then(() => true, () => false);
|
|
1060
|
+
function applyFlags(config) {
|
|
810
1061
|
const inputArgs = getArgs("--input");
|
|
811
|
-
const input = inputArgs.length > 0 ? inputArgs : config.input;
|
|
812
|
-
const output = getArg("--output") ?? config.output;
|
|
813
1062
|
const excludeArgs = getArgs("--exclude");
|
|
814
|
-
const exclude = excludeArgs.length > 0 ? excludeArgs : config.exclude;
|
|
815
|
-
const prefix = getArg("--prefix") ?? config.prefix;
|
|
816
|
-
const namingRaw = getArg("--naming") ?? config.naming;
|
|
817
|
-
if (namingRaw !== void 0 && !VALID_NAMINGS.includes(namingRaw)) {
|
|
818
|
-
console.error(`css-typed-vars: invalid --naming value "${namingRaw}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
819
|
-
process.exit(1);
|
|
820
|
-
}
|
|
821
|
-
const naming = namingRaw;
|
|
822
1063
|
const selectorArgs = getArgs("--selector");
|
|
823
|
-
const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
|
|
824
1064
|
const themeArgs = getArgs("--theme");
|
|
825
1065
|
for (const arg of themeArgs) {
|
|
826
1066
|
if (!/^[^=]+=.+$/.test(arg)) {
|
|
827
|
-
|
|
828
|
-
process.exit(1);
|
|
1067
|
+
throw new CliError(`css-typed-vars: invalid --theme value "${arg}". Expected <name>=<selector or @media prelude>, e.g. dark=[data-theme="dark"].`);
|
|
829
1068
|
}
|
|
830
1069
|
}
|
|
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
1070
|
const usageArgs = getArgs("--usage");
|
|
835
|
-
const usage = usageArgs.length > 0 ? usageArgs : config.usage;
|
|
836
1071
|
const usageExcludeArgs = getArgs("--usage-exclude");
|
|
837
|
-
const
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
1072
|
+
const refsIgnoreArgs = getArgs("--refs-ignore");
|
|
1073
|
+
return {
|
|
1074
|
+
...config,
|
|
1075
|
+
input: inputArgs.length > 0 ? inputArgs : config.input,
|
|
1076
|
+
output: getArg("--output") ?? config.output,
|
|
1077
|
+
exclude: excludeArgs.length > 0 ? excludeArgs : config.exclude,
|
|
1078
|
+
prefix: getArg("--prefix") ?? config.prefix,
|
|
1079
|
+
naming: getArg("--naming") ?? config.naming,
|
|
1080
|
+
selectors: selectorArgs.length > 0 ? selectorArgs : config.selectors,
|
|
1081
|
+
themes: themeArgs.length > 0 ? Object.fromEntries(themeArgs.map((arg) => [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)])) : config.themes,
|
|
1082
|
+
group: args.includes("--group") || config.group,
|
|
1083
|
+
prune: args.includes("--prune") || config.prune,
|
|
1084
|
+
usage: usageArgs.length > 0 ? usageArgs : config.usage,
|
|
1085
|
+
usageExclude: usageExcludeArgs.length > 0 ? usageExcludeArgs : config.usageExclude,
|
|
1086
|
+
helpers: args.includes("--helpers") || config.helpers,
|
|
1087
|
+
refsIgnore: refsIgnoreArgs.length > 0 ? refsIgnoreArgs : config.refsIgnore
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
function loadTargets(config) {
|
|
1091
|
+
if (!Array.isArray(config)) return [{ options: applyFlags(config), tag: "css-typed-vars" }];
|
|
1092
|
+
if (config.length === 0) throw new CliError("css-typed-vars: the config file exports an empty array.");
|
|
1093
|
+
const used = OPTION_FLAGS.filter((flag) => args.includes(flag));
|
|
1094
|
+
if (used.length > 0) {
|
|
1095
|
+
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.`);
|
|
843
1096
|
}
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
1097
|
+
return config.map((options, i) => ({ options, tag: `css-typed-vars [${options.output ?? `target ${i + 1}`}]` }));
|
|
1098
|
+
}
|
|
1099
|
+
function validateModes() {
|
|
1100
|
+
if (lintRefsMode && (watchMode || checkMode || pruneCheckMode)) {
|
|
1101
|
+
throw new CliError("css-typed-vars: --lint-refs cannot be combined with --watch, --check or --prune-check.");
|
|
847
1102
|
}
|
|
1103
|
+
if (checkMode && watchMode) throw new CliError("css-typed-vars: --check cannot be combined with --watch.");
|
|
848
1104
|
if (pruneCheckMode && (watchMode || checkMode)) {
|
|
849
|
-
|
|
850
|
-
process.exit(1);
|
|
1105
|
+
throw new CliError("css-typed-vars: --prune-check cannot be combined with --watch or --check.");
|
|
851
1106
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1107
|
+
}
|
|
1108
|
+
function validateTarget({ options, tag }, single) {
|
|
1109
|
+
const { input, output, naming, group, prefix, prune, usage } = options;
|
|
1110
|
+
if (naming !== void 0 && !VALID_NAMINGS.includes(naming)) {
|
|
1111
|
+
throw new CliError(`${tag}: invalid --naming value "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
|
|
1112
|
+
}
|
|
1113
|
+
if (lintRefsMode) {
|
|
1114
|
+
if (!input) throw new CliError(`${tag}: --lint-refs requires --input <glob> (or "input" in the config file).`);
|
|
1115
|
+
return;
|
|
855
1116
|
}
|
|
1117
|
+
if (!input || !output) {
|
|
1118
|
+
throw new CliError(single ? `${USAGE}
|
|
1119
|
+
Or add a css-typed-vars.config.js file with input and output fields. Run with --help to see all options.` : `${tag}: every target needs "input" and "output".`);
|
|
1120
|
+
}
|
|
1121
|
+
if (group && prefix) throw new CliError(`${tag}: --group cannot be combined with --prefix.`);
|
|
856
1122
|
if ((prune || pruneCheckMode) && !usage) {
|
|
857
|
-
|
|
858
|
-
process.exit(1);
|
|
1123
|
+
throw new CliError(`${tag}: --prune/--prune-check requires --usage <glob> (source files to scan for cssVars usage).`);
|
|
859
1124
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
1125
|
+
}
|
|
1126
|
+
async function lintRefs({ options, tag }) {
|
|
1127
|
+
const refs = await findUndefinedRefs({ input: options.input, exclude: options.exclude, refsIgnore: options.refsIgnore });
|
|
1128
|
+
const format = (ref) => ` ${(0, import_node_path4.relative)(process.cwd(), ref.file).replace(/\\/g, "/")}:${ref.line}:${ref.column} var(${ref.name}${ref.hasFallback ? ", \u2026" : ""})`;
|
|
1129
|
+
const errors = refs.filter((ref) => !ref.hasFallback);
|
|
1130
|
+
const warnings = refs.filter((ref) => ref.hasFallback);
|
|
1131
|
+
if (warnings.length > 0) {
|
|
1132
|
+
console.warn(`${tag}: ${warnings.length} reference(s) to undeclared variables with a fallback:`);
|
|
1133
|
+
for (const ref of warnings) console.warn(format(ref));
|
|
1134
|
+
}
|
|
1135
|
+
if (errors.length > 0) {
|
|
1136
|
+
console.error(`${tag}: ${errors.length} reference(s) to undeclared variables:`);
|
|
1137
|
+
for (const ref of errors) console.error(format(ref));
|
|
1138
|
+
return false;
|
|
1139
|
+
}
|
|
1140
|
+
console.log(`${tag}: no references to undeclared variables.`);
|
|
1141
|
+
return true;
|
|
1142
|
+
}
|
|
1143
|
+
async function pruneCheck({ options, tag }) {
|
|
1144
|
+
const unused = await findUnusedVars({ ...options, input: options.input });
|
|
1145
|
+
if (unused.length > 0) {
|
|
1146
|
+
console.error(`${tag}: ${unused.length} unused variable(s): ${unused.join(", ")}`);
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
console.log(`${tag}: no unused variables.`);
|
|
1150
|
+
return true;
|
|
1151
|
+
}
|
|
1152
|
+
async function check({ options, tag }) {
|
|
1153
|
+
if (!await checkGenerated({ ...options, input: options.input, output: options.output })) {
|
|
1154
|
+
console.error(`${tag}: "${options.output}" is out of date. Run without --check to regenerate.`);
|
|
1155
|
+
return false;
|
|
1156
|
+
}
|
|
1157
|
+
console.log(`${tag}: "${options.output}" is up to date.`);
|
|
1158
|
+
return true;
|
|
1159
|
+
}
|
|
1160
|
+
async function run({ options }) {
|
|
1161
|
+
const written = await generate({ ...options, input: options.input, output: options.output });
|
|
1162
|
+
console.log(`${written ? "Generated" : "Up to date"} \u2192 ${options.output}`);
|
|
1163
|
+
}
|
|
1164
|
+
var toArray = (value) => value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
|
1165
|
+
function watchTarget(target) {
|
|
1166
|
+
const { input, exclude, output, prune, usage, usageExclude } = target.options;
|
|
1167
|
+
const jsExt = /\.(m|c)?js$/i.exec(output);
|
|
1168
|
+
const outputs = new Set([output, ...jsExt ? [output.slice(0, -jsExt[0].length) + ".d.ts"] : []].map((path) => (0, import_node_path4.resolve)(path)));
|
|
1169
|
+
let timer = null;
|
|
1170
|
+
let running = false;
|
|
1171
|
+
let pending = false;
|
|
1172
|
+
const regenerate = async () => {
|
|
1173
|
+
if (running) {
|
|
1174
|
+
pending = true;
|
|
1175
|
+
return;
|
|
865
1176
|
}
|
|
866
|
-
|
|
1177
|
+
running = true;
|
|
1178
|
+
await run(target).catch(console.error);
|
|
1179
|
+
running = false;
|
|
1180
|
+
if (pending) {
|
|
1181
|
+
pending = false;
|
|
1182
|
+
await regenerate();
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
const makeHandler = (label) => (file) => {
|
|
1186
|
+
if (outputs.has((0, import_node_path4.resolve)(file))) return;
|
|
1187
|
+
console.log(`${label}: ${file}`);
|
|
1188
|
+
if (timer) clearTimeout(timer);
|
|
1189
|
+
timer = setTimeout(() => {
|
|
1190
|
+
timer = null;
|
|
1191
|
+
void regenerate();
|
|
1192
|
+
}, 100);
|
|
1193
|
+
};
|
|
1194
|
+
const subscribe = (patterns, ignored) => {
|
|
1195
|
+
(0, import_chokidar.watch)(patterns, { ignoreInitial: true, ...ignored.length > 0 ? { ignored } : {} }).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
1196
|
+
};
|
|
1197
|
+
subscribe(toArray(input), toArray(exclude));
|
|
1198
|
+
if (prune) subscribe(toArray(usage), toArray(usageExclude));
|
|
1199
|
+
}
|
|
1200
|
+
async function main() {
|
|
1201
|
+
validateArgs();
|
|
1202
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
1203
|
+
console.log(HELP);
|
|
867
1204
|
return;
|
|
868
1205
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1206
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
1207
|
+
const pkg = JSON.parse(await (0, import_promises4.readFile)(new URL("../package.json", importMetaUrl), "utf8"));
|
|
1208
|
+
console.log(pkg.version);
|
|
1209
|
+
process.exit(0);
|
|
1210
|
+
}
|
|
1211
|
+
const targets = loadTargets(await loadConfig());
|
|
1212
|
+
validateModes();
|
|
1213
|
+
for (const target of targets) validateTarget(target, targets.length === 1);
|
|
1214
|
+
const mode = lintRefsMode ? lintRefs : pruneCheckMode ? pruneCheck : checkMode ? check : null;
|
|
1215
|
+
if (mode) {
|
|
1216
|
+
let ok = true;
|
|
1217
|
+
for (const target of targets) {
|
|
1218
|
+
if (!await mode(target)) ok = false;
|
|
875
1219
|
}
|
|
876
|
-
|
|
1220
|
+
if (!ok) process.exit(1);
|
|
877
1221
|
return;
|
|
878
1222
|
}
|
|
879
|
-
await run(
|
|
1223
|
+
for (const target of targets) await run(target);
|
|
880
1224
|
if (watchMode) {
|
|
881
|
-
const
|
|
882
|
-
const makeHandler = (label) => (file) => {
|
|
883
|
-
console.log(`${label}: ${file}`);
|
|
884
|
-
run(runOptions).catch(console.error);
|
|
885
|
-
};
|
|
886
|
-
const ignored = exclude ? Array.isArray(exclude) ? exclude : [exclude] : void 0;
|
|
887
|
-
(0, import_chokidar.watch)(patterns, ignored ? { ignored } : void 0).on("change", makeHandler("Changed")).on("add", makeHandler("Added")).on("unlink", makeHandler("Removed"));
|
|
1225
|
+
for (const target of targets) watchTarget(target);
|
|
888
1226
|
console.log("Watching for changes...");
|
|
889
1227
|
}
|
|
890
1228
|
}
|
|
891
1229
|
main().catch((err) => {
|
|
892
|
-
console.error(err);
|
|
1230
|
+
console.error(err instanceof CliError ? err.message : err);
|
|
893
1231
|
process.exit(1);
|
|
894
1232
|
});
|