css-typed-vars 0.4.16 → 0.5.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/dist/cli.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ checkGenerated,
3
4
  generate
4
- } from "./chunk-ARQR224L.js";
5
+ } from "./chunk-H3T6RMQQ.js";
5
6
  import {
6
7
  VALID_NAMINGS
7
- } from "./chunk-NS2BULH3.js";
8
+ } from "./chunk-JDZAH2YQ.js";
8
9
 
9
10
  // src/cli.ts
10
11
  import { readFile } from "fs/promises";
@@ -27,6 +28,7 @@ var getArgs = (flag) => {
27
28
  return result;
28
29
  };
29
30
  var watchMode = args.includes("--watch");
31
+ var checkMode = args.includes("--check");
30
32
  async function loadConfig() {
31
33
  const candidates = [
32
34
  "css-typed-vars.config.js",
@@ -77,10 +79,23 @@ async function main() {
77
79
  const selectorArgs = getArgs("--selector");
78
80
  const selectors = selectorArgs.length > 0 ? selectorArgs : config.selectors;
79
81
  if (!input || !output) {
80
- console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch]");
82
+ console.error("Usage: css-typed-vars --input <glob> --output <file> [--watch] [--check]");
81
83
  console.error("Or add a css-typed-vars.config.js file with input and output fields.");
82
84
  process.exit(1);
83
85
  }
86
+ if (checkMode && watchMode) {
87
+ console.error("css-typed-vars: --check cannot be combined with --watch.");
88
+ process.exit(1);
89
+ }
90
+ if (checkMode) {
91
+ const upToDate = await checkGenerated({ input, output, exclude, prefix, naming, selectors });
92
+ if (!upToDate) {
93
+ console.error(`css-typed-vars: "${output}" is out of date. Run without --check to regenerate.`);
94
+ process.exit(1);
95
+ }
96
+ console.log(`css-typed-vars: "${output}" is up to date.`);
97
+ return;
98
+ }
84
99
  await run(input, output, exclude, prefix, naming, selectors);
85
100
  if (watchMode) {
86
101
  const patterns = Array.isArray(input) ? input : [input];
package/dist/esbuild.cjs CHANGED
@@ -104,8 +104,9 @@ function extractBlock(text, start) {
104
104
  for (; i < text.length && depth > 0; i++) {
105
105
  const char = text[i];
106
106
  if (quote) {
107
- if (char === "\\") i++;
108
- else if (char === quote) quote = null;
107
+ const step = stepQuote(text, i, quote);
108
+ if (step.closed) quote = null;
109
+ i += step.consumed - 1;
109
110
  } else if (char === '"' || char === "'") {
110
111
  quote = char;
111
112
  } else if (char === "{") {
@@ -139,9 +140,27 @@ function maskQuotedContent(text) {
139
140
  }
140
141
  return result;
141
142
  }
142
- function parseVarNames(css, selectors) {
143
+ function extractValue(text, start) {
144
+ let i = start;
145
+ let quote = null;
146
+ for (; i < text.length; i++) {
147
+ const char = text[i];
148
+ if (quote) {
149
+ const step = stepQuote(text, i, quote);
150
+ if (step.closed) quote = null;
151
+ i += step.consumed - 1;
152
+ continue;
153
+ }
154
+ if (char === '"' || char === "'") {
155
+ quote = char;
156
+ continue;
157
+ }
158
+ if (char === ";" || char === "}") break;
159
+ }
160
+ return text.slice(start, i).trim();
161
+ }
162
+ function scanDeclarations(css, selectors, onProperty) {
143
163
  const stripped = stripComments(css);
144
- const names = /* @__PURE__ */ new Set();
145
164
  const allSelectors = [":root", ...selectors ?? []];
146
165
  for (const sel of allSelectors) {
147
166
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -150,48 +169,62 @@ function parseVarNames(css, selectors) {
150
169
  while (match = openRegex.exec(stripped)) {
151
170
  const start = match.index + match[0].length;
152
171
  const block = extractBlock(stripped, start);
153
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
154
- names.add(prop[0]);
172
+ const masked = maskQuotedContent(block);
173
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
174
+ const name = prop[0];
175
+ const colonIndex = block.indexOf(":", prop.index + name.length);
176
+ onProperty(name, extractValue(block, colonIndex + 1));
155
177
  }
156
178
  openRegex.lastIndex = start + block.length + 1;
157
179
  }
158
180
  }
159
- return [...names];
181
+ }
182
+ function parseVarDeclarations(css, selectors) {
183
+ const declarations = /* @__PURE__ */ new Map();
184
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
185
+ return declarations;
160
186
  }
161
187
 
162
188
  // src/scanner.ts
163
- async function scanVarNames(patterns, exclude, selectors) {
164
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
165
- (p) => p.replace(/\\/g, "/")
166
- );
167
- const normalizedExclude = exclude ? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => p.replace(/\\/g, "/")) : [];
189
+ function normalizePatterns(patterns) {
190
+ return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
191
+ }
192
+ async function scanVarDeclarations(patterns, exclude, selectors) {
193
+ const normalized = normalizePatterns(patterns);
194
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
168
195
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
169
- const all = /* @__PURE__ */ new Set();
170
- await Promise.all(
196
+ const perFile = await Promise.all(
171
197
  files.map(async (file) => {
172
198
  let css;
173
199
  try {
174
200
  css = await (0, import_promises.readFile)(file, "utf8");
175
201
  } catch (err) {
176
202
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
177
- return;
178
- }
179
- for (const name of parseVarNames(css, selectors)) {
180
- all.add(name);
203
+ return /* @__PURE__ */ new Map();
181
204
  }
205
+ return parseVarDeclarations(css, selectors);
182
206
  })
183
207
  );
184
- return [...all].sort();
208
+ const all = /* @__PURE__ */ new Map();
209
+ for (const declarations of perFile) {
210
+ for (const [name, value] of declarations) {
211
+ all.set(name, value);
212
+ }
213
+ }
214
+ return all;
185
215
  }
186
216
 
187
217
  // src/generator.ts
188
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
218
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
189
219
  function convertCase(value, naming) {
190
220
  if (!VALID_NAMINGS.includes(naming)) {
191
221
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
192
222
  }
193
223
  if (naming === "kebab") return value;
194
- return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
224
+ if (naming === "snake") return value.replace(/-+/g, "_");
225
+ if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
226
+ if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
227
+ return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
195
228
  }
196
229
  function toKey(cssVarName, naming = "camelCase") {
197
230
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
@@ -222,7 +255,7 @@ function applyPrefix(key, prefix, naming = "camelCase") {
222
255
  }
223
256
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
224
257
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
225
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
258
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
226
259
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
227
260
  }
228
261
  function formatKey(key, naming = "camelCase") {
@@ -247,16 +280,22 @@ function warnOnCollisions(varNames, prefix, naming) {
247
280
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
248
281
  }
249
282
  }
250
- function buildEntries(varNames, prefix, naming) {
283
+ function buildEntries(varNames, prefix, naming, declarations) {
251
284
  const byKey = /* @__PURE__ */ new Map();
252
285
  for (const name of varNames) {
253
286
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
254
- byKey.set(key, name);
287
+ byKey.set(key, { name, value: declarations?.get(name) });
255
288
  }
256
- return [...byKey].map(([key, name]) => ({ key, name }));
289
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
290
+ }
291
+ function formatDefaultComment(value) {
292
+ return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
257
293
  }
258
- function generateJs(varNames, prefix, naming) {
259
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
294
+ function generateJs(varNames, prefix, naming, declarations) {
295
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
296
+ ...value ? [formatDefaultComment(value)] : [],
297
+ ` ${key}: 'var(${name})',`
298
+ ]);
260
299
  return [
261
300
  "// generated \u2014 do not edit",
262
301
  "export const cssVars = {",
@@ -265,8 +304,11 @@ function generateJs(varNames, prefix, naming) {
265
304
  ""
266
305
  ].join("\n");
267
306
  }
268
- function generateDeclaration(varNames, prefix, naming) {
269
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
307
+ function generateDeclaration(varNames, prefix, naming, declarations) {
308
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
309
+ ...value ? [formatDefaultComment(value)] : [],
310
+ ` ${key}: 'var(${name})';`
311
+ ]);
270
312
  return [
271
313
  "export declare const cssVars: {",
272
314
  ...entries,
@@ -284,7 +326,8 @@ function getDtsPath(options) {
284
326
  return options.dts ? (0, import_node_path.resolve)(process.cwd(), options.dts) : (0, import_node_path.join)(__dirname, "generated.d.ts");
285
327
  }
286
328
  var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
287
- let cachedNames = null;
329
+ let cachedDeclarations = null;
330
+ const scan = () => scanVarDeclarations(options.input, options.exclude, options.selectors);
288
331
  return {
289
332
  name: "css-typed-vars",
290
333
  vite: {
@@ -295,14 +338,15 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
295
338
  let writeQueue = Promise.resolve();
296
339
  const rescan = async () => {
297
340
  const myGeneration = ++generation;
298
- const namesPromise = scanVarNames(options.input, options.exclude, options.selectors);
299
- cachedNames = namesPromise;
300
- const names = await namesPromise;
341
+ const declarationsPromise = scan();
342
+ cachedDeclarations = declarationsPromise;
343
+ const declarations = await declarationsPromise;
301
344
  if (myGeneration !== generation) return;
345
+ const names = [...declarations.keys()].sort();
302
346
  warnOnCollisions(names, options.prefix, options.naming);
303
347
  const dtsPath = getDtsPath(options);
304
348
  if (dtsPath) {
305
- const content = generateDeclaration(names, options.prefix, options.naming);
349
+ const content = generateDeclaration(names, options.prefix, options.naming, declarations);
306
350
  writeQueue = writeQueue.then(async () => {
307
351
  if (myGeneration !== generation) return;
308
352
  await (0, import_promises2.writeFile)(dtsPath, content, "utf8");
@@ -330,20 +374,22 @@ var unplugin_default = (0, import_unplugin.createUnplugin)((options) => {
330
374
  }
331
375
  },
332
376
  async buildStart() {
333
- cachedNames = scanVarNames(options.input, options.exclude, options.selectors);
334
- const names = await cachedNames;
377
+ cachedDeclarations = scan();
378
+ const declarations = await cachedDeclarations;
379
+ const names = [...declarations.keys()].sort();
335
380
  warnOnCollisions(names, options.prefix, options.naming);
336
381
  const dtsPath = getDtsPath(options);
337
382
  if (!dtsPath) return;
338
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
383
+ await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming, declarations), "utf8");
339
384
  },
340
385
  resolveId(id) {
341
386
  if (id === VIRTUAL_ID) return RESOLVED_ID;
342
387
  },
343
388
  async load(id) {
344
389
  if (id === RESOLVED_ID) {
345
- const names = await (cachedNames ?? scanVarNames(options.input, options.exclude, options.selectors));
346
- return generateJs(names, options.prefix, options.naming);
390
+ const declarations = await (cachedDeclarations ?? scan());
391
+ const names = [...declarations.keys()].sort();
392
+ return generateJs(names, options.prefix, options.naming, declarations);
347
393
  }
348
394
  }
349
395
  };
@@ -1,7 +1,7 @@
1
1
  import * as esbuild from 'esbuild';
2
2
  import { Options } from './unplugin.cjs';
3
3
  import 'unplugin';
4
- import './generator-Ba8XeISD.cjs';
4
+ import './generator-t6h8Ic7V.cjs';
5
5
 
6
6
  declare const _default: (options: Options) => esbuild.Plugin;
7
7
 
package/dist/esbuild.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as esbuild from 'esbuild';
2
2
  import { Options } from './unplugin.js';
3
3
  import 'unplugin';
4
- import './generator-Ba8XeISD.js';
4
+ import './generator-t6h8Ic7V.js';
5
5
 
6
6
  declare const _default: (options: Options) => esbuild.Plugin;
7
7
 
package/dist/esbuild.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  unplugin_default
3
- } from "./chunk-YJPHNISO.js";
4
- import "./chunk-NS2BULH3.js";
3
+ } from "./chunk-YBZGHG2G.js";
4
+ import "./chunk-JDZAH2YQ.js";
5
5
 
6
6
  // src/esbuild.ts
7
7
  var esbuild_default = unplugin_default.esbuild;
@@ -0,0 +1,6 @@
1
+ type NamingConvention = 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal';
2
+ declare function generateCode(varNames: string[], prefix?: string, naming?: NamingConvention, declarations?: Map<string, string>): string;
3
+ declare function generateJs(varNames: string[], prefix?: string, naming?: NamingConvention, declarations?: Map<string, string>): string;
4
+ declare function generateDeclaration(varNames: string[], prefix?: string, naming?: NamingConvention, declarations?: Map<string, string>): string;
5
+
6
+ export { type NamingConvention as N, generateDeclaration as a, generateJs as b, generateCode as g };
@@ -0,0 +1,6 @@
1
+ type NamingConvention = 'camelCase' | 'snake' | 'kebab' | 'constant' | 'pascal';
2
+ declare function generateCode(varNames: string[], prefix?: string, naming?: NamingConvention, declarations?: Map<string, string>): string;
3
+ declare function generateJs(varNames: string[], prefix?: string, naming?: NamingConvention, declarations?: Map<string, string>): string;
4
+ declare function generateDeclaration(varNames: string[], prefix?: string, naming?: NamingConvention, declarations?: Map<string, string>): string;
5
+
6
+ export { type NamingConvention as N, generateDeclaration as a, generateJs as b, generateCode as g };
package/dist/index.cjs CHANGED
@@ -30,11 +30,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
+ checkGenerated: () => checkGenerated,
33
34
  generate: () => generate,
34
35
  generateCode: () => generateCode,
35
36
  generateDeclaration: () => generateDeclaration,
36
37
  generateJs: () => generateJs,
38
+ parseVarDeclarations: () => parseVarDeclarations,
37
39
  parseVarNames: () => parseVarNames,
40
+ scanVarDeclarations: () => scanVarDeclarations,
38
41
  scanVarNames: () => scanVarNames
39
42
  });
40
43
  module.exports = __toCommonJS(src_exports);
@@ -106,8 +109,9 @@ function extractBlock(text, start) {
106
109
  for (; i < text.length && depth > 0; i++) {
107
110
  const char = text[i];
108
111
  if (quote) {
109
- if (char === "\\") i++;
110
- else if (char === quote) quote = null;
112
+ const step = stepQuote(text, i, quote);
113
+ if (step.closed) quote = null;
114
+ i += step.consumed - 1;
111
115
  } else if (char === '"' || char === "'") {
112
116
  quote = char;
113
117
  } else if (char === "{") {
@@ -141,9 +145,27 @@ function maskQuotedContent(text) {
141
145
  }
142
146
  return result;
143
147
  }
144
- function parseVarNames(css, selectors) {
148
+ function extractValue(text, start) {
149
+ let i = start;
150
+ let quote = null;
151
+ for (; i < text.length; i++) {
152
+ const char = text[i];
153
+ if (quote) {
154
+ const step = stepQuote(text, i, quote);
155
+ if (step.closed) quote = null;
156
+ i += step.consumed - 1;
157
+ continue;
158
+ }
159
+ if (char === '"' || char === "'") {
160
+ quote = char;
161
+ continue;
162
+ }
163
+ if (char === ";" || char === "}") break;
164
+ }
165
+ return text.slice(start, i).trim();
166
+ }
167
+ function scanDeclarations(css, selectors, onProperty) {
145
168
  const stripped = stripComments(css);
146
- const names = /* @__PURE__ */ new Set();
147
169
  const allSelectors = [":root", ...selectors ?? []];
148
170
  for (const sel of allSelectors) {
149
171
  const escaped = sel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -152,48 +174,71 @@ function parseVarNames(css, selectors) {
152
174
  while (match = openRegex.exec(stripped)) {
153
175
  const start = match.index + match[0].length;
154
176
  const block = extractBlock(stripped, start);
155
- for (const prop of maskQuotedContent(block).matchAll(/--[\w-]+(?=\s*:)/g)) {
156
- names.add(prop[0]);
177
+ const masked = maskQuotedContent(block);
178
+ for (const prop of masked.matchAll(/--[\w-]+(?=\s*:)/g)) {
179
+ const name = prop[0];
180
+ const colonIndex = block.indexOf(":", prop.index + name.length);
181
+ onProperty(name, extractValue(block, colonIndex + 1));
157
182
  }
158
183
  openRegex.lastIndex = start + block.length + 1;
159
184
  }
160
185
  }
186
+ }
187
+ function parseVarNames(css, selectors) {
188
+ const names = /* @__PURE__ */ new Set();
189
+ scanDeclarations(css, selectors, (name) => names.add(name));
161
190
  return [...names];
162
191
  }
192
+ function parseVarDeclarations(css, selectors) {
193
+ const declarations = /* @__PURE__ */ new Map();
194
+ scanDeclarations(css, selectors, (name, value) => declarations.set(name, value));
195
+ return declarations;
196
+ }
163
197
 
164
198
  // src/scanner.ts
165
- async function scanVarNames(patterns, exclude, selectors) {
166
- const normalized = (Array.isArray(patterns) ? patterns : [patterns]).map(
167
- (p) => p.replace(/\\/g, "/")
168
- );
169
- const normalizedExclude = exclude ? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => p.replace(/\\/g, "/")) : [];
199
+ function normalizePatterns(patterns) {
200
+ return (Array.isArray(patterns) ? patterns : [patterns]).map((p) => p.replace(/\\/g, "/"));
201
+ }
202
+ async function scanVarDeclarations(patterns, exclude, selectors) {
203
+ const normalized = normalizePatterns(patterns);
204
+ const normalizedExclude = exclude ? normalizePatterns(exclude) : [];
170
205
  const files = await (0, import_fast_glob.default)(normalized, { absolute: true, ignore: normalizedExclude });
171
- const all = /* @__PURE__ */ new Set();
172
- await Promise.all(
206
+ const perFile = await Promise.all(
173
207
  files.map(async (file) => {
174
208
  let css;
175
209
  try {
176
210
  css = await (0, import_promises.readFile)(file, "utf8");
177
211
  } catch (err) {
178
212
  console.warn(`css-typed-vars: skipping "${file}": ${err.message}`);
179
- return;
180
- }
181
- for (const name of parseVarNames(css, selectors)) {
182
- all.add(name);
213
+ return /* @__PURE__ */ new Map();
183
214
  }
215
+ return parseVarDeclarations(css, selectors);
184
216
  })
185
217
  );
186
- return [...all].sort();
218
+ const all = /* @__PURE__ */ new Map();
219
+ for (const declarations of perFile) {
220
+ for (const [name, value] of declarations) {
221
+ all.set(name, value);
222
+ }
223
+ }
224
+ return all;
225
+ }
226
+ async function scanVarNames(patterns, exclude, selectors) {
227
+ const declarations = await scanVarDeclarations(patterns, exclude, selectors);
228
+ return [...declarations.keys()].sort();
187
229
  }
188
230
 
189
231
  // src/generator.ts
190
- var VALID_NAMINGS = ["camelCase", "snake", "kebab"];
232
+ var VALID_NAMINGS = ["camelCase", "snake", "kebab", "constant", "pascal"];
191
233
  function convertCase(value, naming) {
192
234
  if (!VALID_NAMINGS.includes(naming)) {
193
235
  throw new Error(`css-typed-vars: invalid naming "${naming}". Valid values: ${VALID_NAMINGS.join(", ")}`);
194
236
  }
195
237
  if (naming === "kebab") return value;
196
- return naming === "snake" ? value.replace(/-+/g, "_") : value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
238
+ if (naming === "snake") return value.replace(/-+/g, "_");
239
+ if (naming === "constant") return value.replace(/-+/g, "_").toUpperCase();
240
+ if (naming === "pascal") return value.replace(/(^|-+)([a-z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/-/g, "");
241
+ return value.replace(/-+([a-z0-9])/g, (_, c) => c.toUpperCase()).replace(/-/g, "");
197
242
  }
198
243
  function toKey(cssVarName, naming = "camelCase") {
199
244
  const key = convertCase(cssVarName.replace(/^--/, ""), naming);
@@ -224,7 +269,7 @@ function applyPrefix(key, prefix, naming = "camelCase") {
224
269
  }
225
270
  normalizedPrefix = normalizedPrefix.replace(/[^A-Za-z0-9_$]/g, "");
226
271
  if (/^\d/.test(normalizedPrefix)) normalizedPrefix = `_${normalizedPrefix}`;
227
- if (naming === "snake") return `${normalizedPrefix}_${key}`;
272
+ if (naming === "snake" || naming === "constant") return `${normalizedPrefix}_${key}`;
228
273
  return normalizedPrefix + key.charAt(0).toUpperCase() + key.slice(1);
229
274
  }
230
275
  function formatKey(key, naming = "camelCase") {
@@ -249,16 +294,22 @@ function warnOnCollisions(varNames, prefix, naming) {
249
294
  console.warn(`css-typed-vars: multiple CSS variables map to the same key "${key}" (${vars.join(", ")}) \u2014 only the last one will be kept.`);
250
295
  }
251
296
  }
252
- function buildEntries(varNames, prefix, naming) {
297
+ function buildEntries(varNames, prefix, naming, declarations) {
253
298
  const byKey = /* @__PURE__ */ new Map();
254
299
  for (const name of varNames) {
255
300
  const key = formatKey(applyPrefix(toKey(name, naming), prefix, naming), naming);
256
- byKey.set(key, name);
301
+ byKey.set(key, { name, value: declarations?.get(name) });
257
302
  }
258
- return [...byKey].map(([key, name]) => ({ key, name }));
303
+ return [...byKey].map(([key, entry]) => ({ key, ...entry }));
304
+ }
305
+ function formatDefaultComment(value) {
306
+ return ` /** @default ${value.replace(/\*\//g, "*\\/")} */`;
259
307
  }
260
- function generateCode(varNames, prefix, naming) {
261
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
308
+ function generateCode(varNames, prefix, naming, declarations) {
309
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
310
+ ...value ? [formatDefaultComment(value)] : [],
311
+ ` ${key}: 'var(${name})',`
312
+ ]);
262
313
  return [
263
314
  "// generated \u2014 do not edit",
264
315
  "export const cssVars = {",
@@ -269,8 +320,11 @@ function generateCode(varNames, prefix, naming) {
269
320
  ""
270
321
  ].join("\n");
271
322
  }
272
- function generateJs(varNames, prefix, naming) {
273
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})',`);
323
+ function generateJs(varNames, prefix, naming, declarations) {
324
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
325
+ ...value ? [formatDefaultComment(value)] : [],
326
+ ` ${key}: 'var(${name})',`
327
+ ]);
274
328
  return [
275
329
  "// generated \u2014 do not edit",
276
330
  "export const cssVars = {",
@@ -279,8 +333,11 @@ function generateJs(varNames, prefix, naming) {
279
333
  ""
280
334
  ].join("\n");
281
335
  }
282
- function generateDeclaration(varNames, prefix, naming) {
283
- const entries = buildEntries(varNames, prefix, naming).map(({ key, name }) => ` ${key}: 'var(${name})';`);
336
+ function generateDeclaration(varNames, prefix, naming, declarations) {
337
+ const entries = buildEntries(varNames, prefix, naming, declarations).flatMap(({ key, name, value }) => [
338
+ ...value ? [formatDefaultComment(value)] : [],
339
+ ` ${key}: 'var(${name})';`
340
+ ]);
284
341
  return [
285
342
  "export declare const cssVars: {",
286
343
  ...entries,
@@ -291,29 +348,50 @@ function generateDeclaration(varNames, prefix, naming) {
291
348
  }
292
349
 
293
350
  // src/index.ts
294
- async function generate(options) {
295
- const names = await scanVarNames(options.input, options.exclude, options.selectors);
351
+ async function computeOutputs(options) {
352
+ const declarations = await scanVarDeclarations(options.input, options.exclude, options.selectors);
353
+ const names = [...declarations.keys()].sort();
296
354
  if (names.length === 0) {
297
355
  console.warn("css-typed-vars: no CSS custom properties found.");
298
356
  }
299
357
  warnOnCollisions(names, options.prefix, options.naming);
300
358
  const outPath = (0, import_node_path.resolve)(options.output);
301
- await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
302
359
  const jsExtMatch = /\.(m|c)?js$/i.exec(options.output);
303
360
  if (jsExtMatch) {
304
- await (0, import_promises2.writeFile)(outPath, generateJs(names, options.prefix, options.naming), "utf8");
361
+ const content = generateJs(names, options.prefix, options.naming, declarations);
305
362
  const dtsPath = outPath.slice(0, -jsExtMatch[0].length) + ".d.ts";
306
- await (0, import_promises2.writeFile)(dtsPath, generateDeclaration(names, options.prefix, options.naming), "utf8");
307
- } else {
308
- await (0, import_promises2.writeFile)(outPath, generateCode(names, options.prefix, options.naming), "utf8");
363
+ const dtsContent = generateDeclaration(names, options.prefix, options.naming, declarations);
364
+ return { outPath, content, dtsPath, dtsContent };
365
+ }
366
+ return { outPath, content: generateCode(names, options.prefix, options.naming, declarations) };
367
+ }
368
+ async function generate(options) {
369
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
370
+ await (0, import_promises2.mkdir)((0, import_node_path.dirname)(outPath), { recursive: true });
371
+ await (0, import_promises2.writeFile)(outPath, content, "utf8");
372
+ if (dtsPath && dtsContent !== void 0) {
373
+ await (0, import_promises2.writeFile)(dtsPath, dtsContent, "utf8");
374
+ }
375
+ }
376
+ async function checkGenerated(options) {
377
+ const { outPath, content, dtsPath, dtsContent } = await computeOutputs(options);
378
+ const current = await (0, import_promises2.readFile)(outPath, "utf8").catch(() => null);
379
+ if (current !== content) return false;
380
+ if (dtsPath && dtsContent !== void 0) {
381
+ const currentDts = await (0, import_promises2.readFile)(dtsPath, "utf8").catch(() => null);
382
+ if (currentDts !== dtsContent) return false;
309
383
  }
384
+ return true;
310
385
  }
311
386
  // Annotate the CommonJS export names for ESM import in node:
312
387
  0 && (module.exports = {
388
+ checkGenerated,
313
389
  generate,
314
390
  generateCode,
315
391
  generateDeclaration,
316
392
  generateJs,
393
+ parseVarDeclarations,
317
394
  parseVarNames,
395
+ scanVarDeclarations,
318
396
  scanVarNames
319
397
  });
package/dist/index.d.cts CHANGED
@@ -1,8 +1,10 @@
1
- import { N as NamingConvention } from './generator-Ba8XeISD.cjs';
2
- export { g as generateCode, a as generateDeclaration, b as generateJs } from './generator-Ba8XeISD.cjs';
1
+ import { N as NamingConvention } from './generator-t6h8Ic7V.cjs';
2
+ export { g as generateCode, a as generateDeclaration, b as generateJs } from './generator-t6h8Ic7V.cjs';
3
3
 
4
4
  declare function parseVarNames(css: string, selectors?: string[]): string[];
5
+ declare function parseVarDeclarations(css: string, selectors?: string[]): Map<string, string>;
5
6
 
7
+ declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
6
8
  declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
7
9
 
8
10
  interface GenerateOptions {
@@ -14,5 +16,6 @@ interface GenerateOptions {
14
16
  selectors?: string[];
15
17
  }
16
18
  declare function generate(options: GenerateOptions): Promise<void>;
19
+ declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
17
20
 
18
- export { type GenerateOptions, NamingConvention, generate, parseVarNames, scanVarNames };
21
+ export { type GenerateOptions, NamingConvention, checkGenerated, generate, parseVarDeclarations, parseVarNames, scanVarDeclarations, scanVarNames };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
- import { N as NamingConvention } from './generator-Ba8XeISD.js';
2
- export { g as generateCode, a as generateDeclaration, b as generateJs } from './generator-Ba8XeISD.js';
1
+ import { N as NamingConvention } from './generator-t6h8Ic7V.js';
2
+ export { g as generateCode, a as generateDeclaration, b as generateJs } from './generator-t6h8Ic7V.js';
3
3
 
4
4
  declare function parseVarNames(css: string, selectors?: string[]): string[];
5
+ declare function parseVarDeclarations(css: string, selectors?: string[]): Map<string, string>;
5
6
 
7
+ declare function scanVarDeclarations(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<Map<string, string>>;
6
8
  declare function scanVarNames(patterns: string | string[], exclude?: string | string[], selectors?: string[]): Promise<string[]>;
7
9
 
8
10
  interface GenerateOptions {
@@ -14,5 +16,6 @@ interface GenerateOptions {
14
16
  selectors?: string[];
15
17
  }
16
18
  declare function generate(options: GenerateOptions): Promise<void>;
19
+ declare function checkGenerated(options: GenerateOptions): Promise<boolean>;
17
20
 
18
- export { type GenerateOptions, NamingConvention, generate, parseVarNames, scanVarNames };
21
+ export { type GenerateOptions, NamingConvention, checkGenerated, generate, parseVarDeclarations, parseVarNames, scanVarDeclarations, scanVarNames };
package/dist/index.js CHANGED
@@ -1,18 +1,24 @@
1
1
  import {
2
+ checkGenerated,
2
3
  generate
3
- } from "./chunk-ARQR224L.js";
4
+ } from "./chunk-H3T6RMQQ.js";
4
5
  import {
5
6
  generateCode,
6
7
  generateDeclaration,
7
8
  generateJs,
9
+ parseVarDeclarations,
8
10
  parseVarNames,
11
+ scanVarDeclarations,
9
12
  scanVarNames
10
- } from "./chunk-NS2BULH3.js";
13
+ } from "./chunk-JDZAH2YQ.js";
11
14
  export {
15
+ checkGenerated,
12
16
  generate,
13
17
  generateCode,
14
18
  generateDeclaration,
15
19
  generateJs,
20
+ parseVarDeclarations,
16
21
  parseVarNames,
22
+ scanVarDeclarations,
17
23
  scanVarNames
18
24
  };