@better-css-modules/core 0.1.3 → 0.2.1

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.
@@ -0,0 +1,1524 @@
1
+ import fs, { realpathSync, statSync } from "node:fs";
2
+ import postcss, { CssSyntaxError } from "postcss";
3
+ import * as csstree from "css-tree";
4
+ import patches from "@csstools/css-syntax-patches-for-csstree/dist/index.json" with { type: "json" };
5
+ import { createJiti } from "jiti";
6
+ import path from "node:path";
7
+ import fs$1 from "node:fs/promises";
8
+ import { ResolverFactory } from "oxc-resolver";
9
+ import fg from "fast-glob";
10
+ import picomatch from "picomatch";
11
+ import { SourceMapGenerator } from "source-map-js";
12
+ const { parse, generate: generate$1, lexer } = csstree.fork({
13
+ atrules: patches.next.atrules,
14
+ properties: patches.next.properties,
15
+ types: patches.next.types
16
+ });
17
+ const { walk, find, ident, property } = csstree;
18
+ //#endregion
19
+ //#region src/css.ts
20
+ const ANIMATION_PROPERTIES = /* @__PURE__ */ new Set([
21
+ "animation",
22
+ "animation-name",
23
+ "-webkit-animation",
24
+ "-webkit-animation-name"
25
+ ]);
26
+ const ANIMATION_KEYWORDS = /* @__PURE__ */ new Set([
27
+ "none",
28
+ "inherit",
29
+ "initial",
30
+ "unset",
31
+ "revert",
32
+ "revert-layer",
33
+ "ease",
34
+ "ease-in",
35
+ "ease-out",
36
+ "ease-in-out",
37
+ "linear",
38
+ "step-start",
39
+ "step-end",
40
+ "normal",
41
+ "reverse",
42
+ "alternate",
43
+ "alternate-reverse",
44
+ "forwards",
45
+ "backwards",
46
+ "both",
47
+ "running",
48
+ "paused",
49
+ "infinite",
50
+ "replace",
51
+ "add",
52
+ "accumulate",
53
+ "auto"
54
+ ]);
55
+ /**
56
+ * Analyze the source of a CSS Modules file. Throws postcss's `CssSyntaxError`
57
+ * when the stylesheet itself cannot be parsed.
58
+ */
59
+ function analyzeCss(source, file) {
60
+ const root = postcss.parse(source, { from: file });
61
+ const collector = {
62
+ file,
63
+ node: null,
64
+ classes: [],
65
+ identifiers: [],
66
+ composes: [],
67
+ valueImports: [],
68
+ diagnostics: []
69
+ };
70
+ walkContainer(root, true, collector);
71
+ const exportNames = unique([...collector.classes.map((occurrence) => occurrence.name), ...collector.identifiers.map((identifier) => identifier.name)]);
72
+ return {
73
+ file,
74
+ root,
75
+ classes: collector.classes,
76
+ identifiers: collector.identifiers,
77
+ exportNames,
78
+ composes: collector.composes,
79
+ valueImports: collector.valueImports,
80
+ diagnostics: collector.diagnostics
81
+ };
82
+ }
83
+ function unique(names) {
84
+ return [...new Set(names)].sort();
85
+ }
86
+ /** `composing` is the class of the top-level rule the declarations belong to, or null elsewhere. */
87
+ function walkContainer(container, local, collector, composing = null) {
88
+ container.each((node) => {
89
+ if (node.type === "rule") visitRule(node, local, collector);
90
+ else if (node.type === "atrule") visitAtRule(node, local, collector);
91
+ else if (node.type === "decl" && node.prop.toLowerCase() === "composes") collectComposes(node, composing, collector);
92
+ else if (node.type === "decl" && local) visitDeclaration(node, collector);
93
+ });
94
+ }
95
+ function visitRule(rule, local, collector) {
96
+ if (rule.parent?.type === "atrule" && isKeyframes(rule.parent)) return;
97
+ const selector = rule.raws.selector?.raw ?? rule.selector;
98
+ const trimmed = selector.trim();
99
+ let blockLocal = local;
100
+ let singleClass = null;
101
+ if (trimmed === ":global" || trimmed === ":local") blockLocal = trimmed === ":local";
102
+ else {
103
+ collector.node = rule;
104
+ singleClass = collectSelectorList(selector, startOf(rule), local, collector);
105
+ }
106
+ walkContainer(rule, blockLocal, collector, rule.parent?.type === "root" ? singleClass : null);
107
+ }
108
+ function visitAtRule(atRule, local, collector) {
109
+ const name = atRule.name.toLowerCase();
110
+ if (name === "value") collectValueImport(atRule, collector);
111
+ else if (name === "scope") collectScopePrelude(atRule, local, collector);
112
+ else if (isKeyframes(atRule) && local) collectKeyframesName(atRule, collector);
113
+ if (atRule.nodes) walkContainer(atRule, local, collector);
114
+ }
115
+ function isKeyframes(atRule) {
116
+ return /keyframes$/i.test(atRule.name);
117
+ }
118
+ /**
119
+ * Collect local classes of a selector list. Returns the class name when the
120
+ * list is one local class (`.a` or `:local(.a)`), the only shape `composes` accepts.
121
+ */
122
+ function collectSelectorList(text, base, local, collector) {
123
+ const list = parseSelectorList(text, base, collector);
124
+ if (!list) return null;
125
+ const before = collector.classes.length;
126
+ visitSelectorList(list, local, collector);
127
+ const selectors = list.children.toArray();
128
+ const only = selectors.length === 1 && selectors[0].type === "Selector" ? selectors[0] : null;
129
+ const parts = only ? only.children.toArray() : [];
130
+ return parts.length === 1 && (parts[0].type === "ClassSelector" || parts[0].type === "PseudoClassSelector" && parts[0].name.toLowerCase() === "local") && collector.classes.length === before + 1 ? collector.classes[before].name : null;
131
+ }
132
+ function parseSelectorList(text, base, collector) {
133
+ try {
134
+ const node = parse(text, {
135
+ context: "selectorList",
136
+ positions: true,
137
+ line: base.line,
138
+ column: base.column
139
+ });
140
+ if (node.type !== "SelectorList") return null;
141
+ collector.diagnostics.push(...checkSelectorEnds(node, base, collector.file));
142
+ return node;
143
+ } catch (error) {
144
+ collector.diagnostics.push(syntaxDiagnostic(collector.file, error, base));
145
+ return null;
146
+ }
147
+ }
148
+ /**
149
+ * css-tree reads an empty selector list and a selector that ends with a
150
+ * combinator without complaint; browsers and lightningcss refuse both.
151
+ */
152
+ function checkSelectorEnds(list, base, file) {
153
+ if (list.children.isEmpty) return [{
154
+ file,
155
+ line: base.line,
156
+ column: base.column,
157
+ rule: "syntax",
158
+ message: "Selector is expected"
159
+ }];
160
+ const diagnostics = [];
161
+ list.children.forEach((selector) => {
162
+ const last = selector.type === "Selector" ? selector.children.last : null;
163
+ if (last?.type !== "Combinator" || !last.loc) return;
164
+ diagnostics.push({
165
+ file,
166
+ line: last.loc.start.line,
167
+ column: last.loc.start.column,
168
+ endLine: last.loc.end.line,
169
+ endColumn: last.loc.end.column,
170
+ rule: "syntax",
171
+ message: `Selector is expected after ${last.name}`
172
+ });
173
+ });
174
+ return diagnostics;
175
+ }
176
+ function visitSelectorList(list, local, collector) {
177
+ list.children.forEach((selector) => {
178
+ if (selector.type === "Selector") visitSelector(selector, local, collector);
179
+ });
180
+ }
181
+ function visitSelector(selector, initialLocal, collector) {
182
+ let local = initialLocal;
183
+ selector.children.forEach((node) => {
184
+ if (node.type === "ClassSelector") {
185
+ if (local && node.loc) collector.classes.push({
186
+ name: ident.decode(node.name),
187
+ range: rangeOf(node.loc),
188
+ node: collector.node
189
+ });
190
+ return;
191
+ }
192
+ if (node.type === "IdSelector") {
193
+ if (local && node.loc) collector.identifiers.push({
194
+ name: ident.decode(node.name),
195
+ kind: "id",
196
+ range: rangeOf(node.loc)
197
+ });
198
+ return;
199
+ }
200
+ if (node.type === "PseudoClassSelector") {
201
+ const name = node.name.toLowerCase();
202
+ if (name === "global" || name === "local") {
203
+ if (node.children === null) {
204
+ local = name === "local";
205
+ return;
206
+ }
207
+ const raw = node.children.first;
208
+ if (name === "local" && raw?.type === "Raw" && raw.loc) collectSelectorList(raw.value, raw.loc.start, true, collector);
209
+ return;
210
+ }
211
+ visitNestedSelectors(node.children, local, collector);
212
+ return;
213
+ }
214
+ if (node.type === "PseudoElementSelector") {
215
+ if (node.name.toLowerCase().startsWith("view-transition-")) {
216
+ collectViewTransitionClasses(node, local, collector);
217
+ return;
218
+ }
219
+ visitNestedSelectors(node.children, local, collector);
220
+ }
221
+ });
222
+ }
223
+ function visitNestedSelectors(children, local, collector) {
224
+ children?.forEach((child) => {
225
+ if (child.type === "SelectorList") visitSelectorList(child, local, collector);
226
+ else if (child.type === "Selector") visitSelector(child, local, collector);
227
+ else if (child.type === "Nth" && child.selector) visitSelectorList(child.selector, local, collector);
228
+ });
229
+ }
230
+ /**
231
+ * `::view-transition-group(.card)` names a view-transition class, which both
232
+ * bundlers scope and export like a class selector.
233
+ */
234
+ function collectViewTransitionClasses(node, local, collector) {
235
+ const raw = node.children?.first;
236
+ if (!local || raw?.type !== "Raw" || !raw.loc) return;
237
+ const list = parseSelectorList(raw.value, raw.loc.start, collector);
238
+ if (!list) return;
239
+ walk(list, {
240
+ visit: "ClassSelector",
241
+ enter(classSelector) {
242
+ if (classSelector.loc) collector.identifiers.push({
243
+ name: ident.decode(classSelector.name),
244
+ kind: "view-transition-class",
245
+ range: rangeOf(classSelector.loc)
246
+ });
247
+ }
248
+ });
249
+ }
250
+ function collectScopePrelude(atRule, local, collector) {
251
+ const params = atRule.raws.params?.raw ?? atRule.params;
252
+ const base = paramsStart(atRule);
253
+ let prelude;
254
+ try {
255
+ prelude = parse(params, {
256
+ context: "atrulePrelude",
257
+ atrule: "scope",
258
+ positions: true,
259
+ line: base.line,
260
+ column: base.column
261
+ });
262
+ } catch (error) {
263
+ collector.diagnostics.push(syntaxDiagnostic(collector.file, error, base));
264
+ return;
265
+ }
266
+ collector.node = atRule;
267
+ walk(prelude, {
268
+ visit: "SelectorList",
269
+ enter(node) {
270
+ visitSelectorList(node, local, collector);
271
+ return walk.skip;
272
+ }
273
+ });
274
+ }
275
+ function collectKeyframesName(atRule, collector) {
276
+ const name = atRule.params.trim().replace(/^(["'])(.*)\1$/s, "$2");
277
+ if (name === "" || name.startsWith(":")) return;
278
+ const start = paramsStart(atRule);
279
+ collector.identifiers.push({
280
+ name: ident.decode(name),
281
+ kind: "keyframes",
282
+ range: {
283
+ start,
284
+ end: {
285
+ line: start.line,
286
+ column: start.column + atRule.params.length
287
+ }
288
+ }
289
+ });
290
+ }
291
+ /**
292
+ * Animation names are scoped wherever they appear, so `animation: spin 1s`
293
+ * exports `spin` even when this file declares no such keyframes.
294
+ */
295
+ function visitDeclaration(declaration, collector) {
296
+ const property = declaration.prop.toLowerCase();
297
+ if (!ANIMATION_PROPERTIES.has(property)) return;
298
+ let value;
299
+ try {
300
+ value = parse(declaration.value, {
301
+ context: "value",
302
+ positions: true
303
+ });
304
+ } catch {
305
+ return;
306
+ }
307
+ const range = rangeOfNode(declaration);
308
+ const match = lexer.matchProperty(property, value);
309
+ const isName = match.matched ? (node) => match.isType(node, "keyframes-name") : (node) => !ANIMATION_KEYWORDS.has(node.name.toLowerCase());
310
+ walk(value, { enter(node) {
311
+ if (node.type === "Function") return walk.skip;
312
+ if (node.type === "Identifier" && isName(node)) collector.identifiers.push({
313
+ name: ident.decode(node.name),
314
+ kind: "animation",
315
+ range
316
+ });
317
+ } });
318
+ }
319
+ function collectValueImport(atRule, collector) {
320
+ const params = (atRule.raws.params?.raw ?? atRule.params).trim();
321
+ const imported = /^.+?\s+from\s+(?:"([^"]*)"|'([^']*)')$/s.exec(params);
322
+ if (imported) collector.valueImports.push(imported[1] ?? imported[2] ?? "");
323
+ }
324
+ function collectComposes(declaration, className, collector) {
325
+ const range = rangeOfNode(declaration);
326
+ const value = declaration.value.trim();
327
+ const imported = /^(.+?)\s+from\s+(.+)$/s.exec(value);
328
+ if (!imported) {
329
+ collector.composes.push({
330
+ className,
331
+ names: splitNames(value),
332
+ from: { kind: "local" },
333
+ range
334
+ });
335
+ return;
336
+ }
337
+ const specifier = imported[2].trim();
338
+ const from = specifier === "global" ? { kind: "global" } : {
339
+ kind: "file",
340
+ specifier: specifier.replace(/^(["'])(.*)\1$/s, "$2")
341
+ };
342
+ collector.composes.push({
343
+ className,
344
+ names: splitNames(imported[1]),
345
+ from,
346
+ range
347
+ });
348
+ }
349
+ function splitNames(text) {
350
+ return text.split(/[\s,]+/).filter(Boolean).map((name) => ident.decode(name));
351
+ }
352
+ function startOf(node) {
353
+ const start = node.source?.start;
354
+ return start ? {
355
+ line: start.line,
356
+ column: start.column
357
+ } : {
358
+ line: 1,
359
+ column: 1
360
+ };
361
+ }
362
+ /** Where an at-rule's params begin: after `@name` and the whitespace that follows it. */
363
+ function paramsStart(atRule) {
364
+ const start = startOf(atRule);
365
+ const afterName = atRule.raws.afterName ?? "";
366
+ const lastBreak = afterName.lastIndexOf("\n");
367
+ if (lastBreak === -1) return {
368
+ line: start.line,
369
+ column: start.column + 1 + atRule.name.length + afterName.length
370
+ };
371
+ const breaks = afterName.split("\n").length - 1;
372
+ return {
373
+ line: start.line + breaks,
374
+ column: afterName.length - lastBreak
375
+ };
376
+ }
377
+ /**
378
+ * Where a declaration's value begins: after the property, the colon and
379
+ * anything between them. The offset indexes into the source.
380
+ */
381
+ function valueStart(declaration) {
382
+ const start = declaration.source?.start;
383
+ if (!start) return null;
384
+ const hack = /[*_]$/.test(declaration.raws.before ?? "") ? 1 : 0;
385
+ const offset = start.offset + hack + declaration.prop.length + (declaration.raws.between ?? "").length;
386
+ const position = declaration.source?.input.fromOffset(offset);
387
+ return position ? {
388
+ line: position.line,
389
+ column: position.col,
390
+ offset
391
+ } : null;
392
+ }
393
+ function rangeOfNode(node) {
394
+ const start = startOf(node);
395
+ const end = node.source?.end;
396
+ return {
397
+ start,
398
+ end: end ? {
399
+ line: end.line,
400
+ column: end.column + 1
401
+ } : start
402
+ };
403
+ }
404
+ function rangeOf(loc) {
405
+ return {
406
+ start: {
407
+ line: loc.start.line,
408
+ column: loc.start.column
409
+ },
410
+ end: {
411
+ line: loc.end.line,
412
+ column: loc.end.column
413
+ }
414
+ };
415
+ }
416
+ function syntaxDiagnostic(file, error, fallback) {
417
+ const parseError = error;
418
+ return {
419
+ file,
420
+ line: parseError.line ?? fallback.line,
421
+ column: parseError.column ?? fallback.column,
422
+ rule: "syntax",
423
+ message: parseError.message ?? String(error)
424
+ };
425
+ }
426
+ //#endregion
427
+ //#region src/config.ts
428
+ /** A mistake in the config or the files it names, which stops generating or checking. */
429
+ var ConfigError = class extends Error {
430
+ name = "ConfigError";
431
+ };
432
+ function defineConfig(config) {
433
+ return config;
434
+ }
435
+ /** Path of the config file in `cwd`, or null when there is none. */
436
+ function configFile(cwd) {
437
+ const configFileName = "better-css-modules.config";
438
+ for (const ext of [
439
+ ".ts",
440
+ ".mts",
441
+ ".cts",
442
+ ".js",
443
+ ".mjs",
444
+ ".cjs"
445
+ ]) {
446
+ const configPath = path.resolve(cwd, configFileName + ext);
447
+ if (fs.existsSync(configPath)) return configPath;
448
+ }
449
+ return null;
450
+ }
451
+ /**
452
+ * Load the config file `config` names, or the one in `cwd` when it names none,
453
+ * and resolve it. Without a config file the defaults apply, rooted at `cwd`.
454
+ */
455
+ async function loadConfig({ cwd = process.cwd(), config } = {}) {
456
+ const file = config === void 0 ? configFile(cwd) : path.resolve(cwd, config);
457
+ if (file === null) return resolveConfig({}, path.resolve(cwd));
458
+ const name = displayPath(file);
459
+ if (!fs.existsSync(file)) throw new ConfigError(`config file ${name} does not exist`);
460
+ let mod;
461
+ try {
462
+ mod = await createJiti(file, {
463
+ moduleCache: false,
464
+ interopDefault: false
465
+ }).evalModule(fs.readFileSync(file, "utf-8"), {
466
+ filename: file,
467
+ async: true,
468
+ forceTranspile: true
469
+ });
470
+ } catch (error) {
471
+ throw new ConfigError(`cannot load ${name}: ${(error instanceof Error ? error.message : String(error)).replace(/\s*\n\s*/g, " ")}`, { cause: error });
472
+ }
473
+ const exports = mod?.__esModule ? mod : { default: mod };
474
+ if (!("default" in exports)) throw new ConfigError(`${name} has no default export`);
475
+ return resolveConfig(exports.default, path.dirname(file), file);
476
+ }
477
+ /** Fill in the defaults of a config and check it; the one place both happen. */
478
+ function resolveConfig(config, root, file = null) {
479
+ const fail = (message) => {
480
+ throw new ConfigError(file === null ? message : `${displayPath(file)}: ${message}`);
481
+ };
482
+ if (typeof config !== "object" || config === null || Array.isArray(config)) return fail("the config must be an object");
483
+ const input = config;
484
+ const keys = [
485
+ "include",
486
+ "exclude",
487
+ "outDir",
488
+ "silent",
489
+ "namedExports",
490
+ "globalCss",
491
+ "layer"
492
+ ];
493
+ for (const key of Object.keys(input)) if (!keys.includes(key)) fail(`unknown key "${key}"`);
494
+ const strings = (key, fallback) => {
495
+ const value = input[key];
496
+ if (value === void 0) return fallback;
497
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) return fail(`"${key}" must be an array of strings`);
498
+ if (value.includes("")) fail(`"${key}" must not contain an empty string`);
499
+ return [...value];
500
+ };
501
+ const patterns = (key, fallback) => {
502
+ const value = strings(key, fallback);
503
+ for (const pattern of value) {
504
+ const glob = key === "include" && pattern.startsWith("!") ? pattern.slice(1) : pattern;
505
+ if (glob === "") fail(`"${key}" must not contain an empty string`);
506
+ if (path.isAbsolute(glob) || glob.split("/").includes("..")) fail(`"${key}" pattern "${pattern}" must be relative to the project root ${root}, without ".."`);
507
+ }
508
+ return value;
509
+ };
510
+ const string = (key) => {
511
+ const value = input[key];
512
+ if (value === void 0 || typeof value === "string") return value;
513
+ return fail(`"${key}" must be a string`);
514
+ };
515
+ const boolean = (key) => {
516
+ const value = input[key];
517
+ if (value === void 0) return false;
518
+ if (typeof value === "boolean") return value;
519
+ return fail(`"${key}" must be a boolean`);
520
+ };
521
+ const outDir = path.relative(root, path.resolve(root, string("outDir") ?? "__generated__"));
522
+ if (isOutside(outDir)) fail(`outDir "${input.outDir}" is outside the project root ${root}`);
523
+ const layer = string("layer");
524
+ return {
525
+ root,
526
+ file,
527
+ include: patterns("include", ["src/**/*.module.css"]),
528
+ exclude: patterns("exclude", []),
529
+ outDir: outDir.split(path.sep).join("/") || ".",
530
+ silent: boolean("silent"),
531
+ namedExports: boolean("namedExports"),
532
+ globalCss: strings("globalCss", []),
533
+ ...layer === void 0 ? {} : { layer }
534
+ };
535
+ }
536
+ /** Whether a path relative to the root leads out of it. */
537
+ function isOutside(relative) {
538
+ return relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
539
+ }
540
+ /** Paths in messages are relative to where the command runs, like those of diagnostics. */
541
+ function displayPath(file) {
542
+ return path.relative(process.cwd(), file);
543
+ }
544
+ //#endregion
545
+ //#region src/diagnostic.ts
546
+ /** `path:line:col error rule: message`, with the path relative to `cwd`. */
547
+ function formatDiagnostic(diagnostic, cwd) {
548
+ const { file, line, column, rule, message } = diagnostic;
549
+ return `${path.relative(cwd, file)}:${line}:${column} error ${rule}: ${message}`;
550
+ }
551
+ /** GitHub Actions workflow command that annotates the file in a pull request. */
552
+ function formatGitHubAnnotation(diagnostic, cwd) {
553
+ const { file, line, column, endLine, endColumn, rule, message } = diagnostic;
554
+ const properties = [
555
+ `file=${escapeProperty(path.relative(cwd, file))}`,
556
+ `line=${line}`,
557
+ `col=${column}`
558
+ ];
559
+ if (endLine !== void 0) properties.push(`endLine=${endLine}`);
560
+ if (endColumn !== void 0) properties.push(`endColumn=${endColumn}`);
561
+ properties.push(`title=${escapeProperty(rule)}`);
562
+ return `::error ${properties.join(",")}::${escapeData(message)}`;
563
+ }
564
+ function sortDiagnostics(diagnostics) {
565
+ return [...diagnostics].sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) || a.line - b.line || a.column - b.column);
566
+ }
567
+ function escapeData(value) {
568
+ return value.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
569
+ }
570
+ function escapeProperty(value) {
571
+ return escapeData(value).replaceAll(":", "%3A").replaceAll(",", "%2C");
572
+ }
573
+ //#endregion
574
+ //#region src/tokens.ts
575
+ const SIDES = [
576
+ "-top",
577
+ "-right",
578
+ "-bottom",
579
+ "-left",
580
+ "-block",
581
+ "-block-start",
582
+ "-block-end",
583
+ "-inline",
584
+ "-inline-start",
585
+ "-inline-end"
586
+ ];
587
+ /** `name` and its per-side longhands, physical and logical, with an optional suffix. */
588
+ function sides(name, part, suffix = "") {
589
+ return Object.fromEntries(["", ...SIDES].map((side) => [`${name}${side}${suffix}`, part]));
590
+ }
591
+ /**
592
+ * The categories of design tokens. A custom property belongs to a category by
593
+ * its name: `--<category>` itself or `--<category>-*`. This table is the single
594
+ * definition of what each category covers; the README lists it for users.
595
+ */
596
+ const tokenCategories = {
597
+ color: {
598
+ properties: {
599
+ color: "colors",
600
+ "background-color": "colors",
601
+ ...sides("border", "colors", "-color"),
602
+ "outline-color": "colors",
603
+ "text-decoration-color": "colors",
604
+ "text-emphasis-color": "colors",
605
+ "column-rule-color": "colors",
606
+ "caret-color": "colors",
607
+ "accent-color": "colors",
608
+ "scrollbar-color": "colors",
609
+ fill: "colors",
610
+ stroke: "colors",
611
+ "stop-color": "colors",
612
+ "flood-color": "colors",
613
+ "lighting-color": "colors",
614
+ "-webkit-text-fill-color": "colors",
615
+ "-webkit-text-stroke-color": "colors",
616
+ "-webkit-tap-highlight-color": "colors",
617
+ background: "layer-color",
618
+ ...sides("border", "layer-color"),
619
+ outline: "layer-color",
620
+ "text-decoration": "layer-color",
621
+ "text-emphasis": "layer-color",
622
+ "column-rule": "layer-color",
623
+ "-webkit-text-stroke": "layer-color",
624
+ "box-shadow": "shadow-color",
625
+ "text-shadow": "shadow-color",
626
+ "background-image": "gradient-colors",
627
+ "border-image": "gradient-colors",
628
+ "border-image-source": "gradient-colors"
629
+ },
630
+ keywords: ["currentcolor", "transparent"]
631
+ },
632
+ spacing: {
633
+ properties: {
634
+ ...sides("margin", "value"),
635
+ ...sides("padding", "value"),
636
+ ...sides("scroll-margin", "value"),
637
+ ...sides("scroll-padding", "value"),
638
+ inset: "value",
639
+ top: "value",
640
+ right: "value",
641
+ bottom: "value",
642
+ left: "value",
643
+ "inset-block": "value",
644
+ "inset-block-start": "value",
645
+ "inset-block-end": "value",
646
+ "inset-inline": "value",
647
+ "inset-inline-start": "value",
648
+ "inset-inline-end": "value",
649
+ gap: "value",
650
+ "row-gap": "value",
651
+ "column-gap": "value"
652
+ },
653
+ keywords: ["auto", "normal"],
654
+ percentages: true
655
+ },
656
+ radius: {
657
+ properties: {
658
+ "border-radius": "value",
659
+ "border-top-left-radius": "value",
660
+ "border-top-right-radius": "value",
661
+ "border-bottom-right-radius": "value",
662
+ "border-bottom-left-radius": "value",
663
+ "border-start-start-radius": "value",
664
+ "border-start-end-radius": "value",
665
+ "border-end-start-radius": "value",
666
+ "border-end-end-radius": "value"
667
+ },
668
+ keywords: [],
669
+ percentages: true
670
+ },
671
+ shadow: {
672
+ properties: {
673
+ "box-shadow": "shadows",
674
+ "text-shadow": "shadows"
675
+ },
676
+ keywords: ["none"]
677
+ },
678
+ "font-size": {
679
+ properties: {
680
+ "font-size": "value",
681
+ font: "font"
682
+ },
683
+ keywords: []
684
+ },
685
+ "font-weight": {
686
+ properties: {
687
+ "font-weight": "value",
688
+ font: "font"
689
+ },
690
+ keywords: ["normal"]
691
+ },
692
+ "line-height": {
693
+ properties: {
694
+ "line-height": "value",
695
+ font: "font"
696
+ },
697
+ keywords: ["normal"]
698
+ },
699
+ "z-index": {
700
+ properties: { "z-index": "value" },
701
+ keywords: ["auto"]
702
+ },
703
+ duration: {
704
+ properties: {
705
+ "transition-duration": "value",
706
+ "transition-delay": "value",
707
+ "animation-duration": "value",
708
+ "animation-delay": "value",
709
+ transition: "times",
710
+ animation: "times"
711
+ },
712
+ keywords: ["auto"]
713
+ },
714
+ breakpoint: {
715
+ properties: {},
716
+ keywords: []
717
+ }
718
+ };
719
+ /** The category a custom property name belongs to, or null for a name without a category prefix. */
720
+ function categoryOf(name) {
721
+ for (const category of Object.keys(tokenCategories)) if (name === `--${category}` || name.startsWith(`--${category}-`)) return category;
722
+ return null;
723
+ }
724
+ //#endregion
725
+ //#region src/project.ts
726
+ /** Globs no `include` pattern should reach: dependencies and the tool's own output. */
727
+ function defaultIgnore(config) {
728
+ const { outDir } = config;
729
+ return outDir === "." ? ["**/node_modules/**"] : ["**/node_modules/**", `${outDir}/**`];
730
+ }
731
+ /**
732
+ * The globs `include` and `exclude` stand for. A negated include pattern
733
+ * excludes, and an exclude pattern also excludes everything under the
734
+ * directories it names, as a glob's ignore list does with a directory.
735
+ */
736
+ function patternsOf(config) {
737
+ const negated = config.include.filter((pattern) => pattern.startsWith("!"));
738
+ const exclude = [
739
+ ...config.exclude,
740
+ ...negated.map((pattern) => pattern.slice(1)),
741
+ ...defaultIgnore(config)
742
+ ].flatMap((pattern) => {
743
+ const trimmed = pattern.replace(/\/+$/, "");
744
+ return trimmed.endsWith("/**") ? [trimmed] : [trimmed, `${trimmed}/**`];
745
+ });
746
+ return {
747
+ include: config.include.filter((pattern) => !negated.includes(pattern)),
748
+ exclude
749
+ };
750
+ }
751
+ /**
752
+ * A predicate telling whether an absolute path is one of the CSS Modules files
753
+ * the config includes. Files outside the root never match.
754
+ */
755
+ function createMatcher(config) {
756
+ const { root } = config;
757
+ const patterns = patternsOf(config);
758
+ const include = picomatch(patterns.include);
759
+ const exclude = picomatch(patterns.exclude, { dot: true });
760
+ return (file) => {
761
+ const relative = path.relative(root, path.resolve(root, file)).split(path.sep).join("/");
762
+ if (relative.startsWith("../") || path.isAbsolute(relative)) return false;
763
+ return include(relative) && !exclude(relative);
764
+ };
765
+ }
766
+ /** The CSS Modules files the config includes. */
767
+ async function findCssModules(config) {
768
+ const { include, exclude } = patternsOf(config);
769
+ return (await fg(include, {
770
+ cwd: config.root,
771
+ ignore: exclude,
772
+ absolute: true
773
+ })).sort();
774
+ }
775
+ /** Read and analyze one file. A stylesheet that does not parse yields its syntax diagnostic. */
776
+ async function loadCssModule(file) {
777
+ const source = await fs$1.readFile(file, "utf-8");
778
+ try {
779
+ const analysis = analyzeCss(source, file);
780
+ return {
781
+ analysis,
782
+ diagnostics: analysis.diagnostics
783
+ };
784
+ } catch (error) {
785
+ if (!(error instanceof CssSyntaxError)) throw error;
786
+ return {
787
+ analysis: null,
788
+ diagnostics: [{
789
+ file,
790
+ line: error.line ?? 1,
791
+ column: error.column ?? 1,
792
+ rule: "syntax",
793
+ message: error.reason
794
+ }]
795
+ };
796
+ }
797
+ }
798
+ async function loadCssModules(files) {
799
+ const result = {
800
+ modules: [],
801
+ diagnostics: []
802
+ };
803
+ for (const file of files) {
804
+ const { analysis, diagnostics } = await loadCssModule(file);
805
+ if (analysis) result.modules.push(analysis);
806
+ result.diagnostics.push(...diagnostics);
807
+ }
808
+ return result;
809
+ }
810
+ //#endregion
811
+ //#region src/global.ts
812
+ /**
813
+ * Whether a custom property declaration or `@property` rule may declare a new
814
+ * name: at a `:root` rule or as `@property`, under nothing but `@layer`, in a
815
+ * file imported without conditions. A rule for `:root, :host`, which design
816
+ * systems built with Tailwind compile to, counts as one for `:root`. Anywhere
817
+ * else it is a mode, which only overrides names declared there.
818
+ */
819
+ function declaresToken(node, conditional) {
820
+ if (conditional) return false;
821
+ let parent = node.parent;
822
+ if (node.type === "decl") {
823
+ if (parent?.type !== "rule" || !isRoot(parent)) return false;
824
+ parent = parent.parent;
825
+ }
826
+ for (; parent && parent.type !== "root"; parent = parent.parent) if (parent.type !== "atrule" || parent.name.toLowerCase() !== "layer") return false;
827
+ return true;
828
+ }
829
+ /** Whether every selector of the rule is `:root` or `:host`, and one is `:root`. */
830
+ function isRoot(rule) {
831
+ const selectors = rule.selectors.map((selector) => selector.trim().toLowerCase());
832
+ return selectors.includes(":root") && selectors.every((s) => s === ":root" || s === ":host");
833
+ }
834
+ /**
835
+ * Whether a node is or sits in an at-rule css-tree does not know, such as
836
+ * Tailwind's `@theme` or `@utility`. That is another tool's syntax, which
837
+ * the global CSS skips: it neither declares tokens nor is checked.
838
+ */
839
+ function isForeign(node) {
840
+ for (let current = node; current; current = current.parent) if (current.type === "atrule" && !lexer.getAtrule(current.name)) return true;
841
+ return false;
842
+ }
843
+ /** Collect the tokens of stylesheets already read, in cascade order. Pure. */
844
+ function globalCssFrom(files) {
845
+ const declarations = /* @__PURE__ */ new Map();
846
+ const registrations = /* @__PURE__ */ new Map();
847
+ for (const { file, root, conditional } of files) root.walk((node) => {
848
+ if (node.type === "decl" && node.prop.startsWith("--")) {
849
+ if (declaresToken(node, conditional)) declarations.set(node.prop, {
850
+ node,
851
+ file,
852
+ text: node.value
853
+ });
854
+ } else if (node.type === "atrule" && node.name.toLowerCase() === "property") {
855
+ const name = node.params.trim();
856
+ if (name.startsWith("--") && declaresToken(node, conditional)) registrations.set(name, {
857
+ node,
858
+ file,
859
+ text: initialValueOf(node)
860
+ });
861
+ }
862
+ });
863
+ const sources = new Map(declarations);
864
+ for (const [name, source] of registrations) if (!sources.has(name)) sources.set(name, source);
865
+ const values = resolveValues(new Map([...sources].map(([name, { text }]) => [name, text])));
866
+ const tokens = /* @__PURE__ */ new Map();
867
+ for (const [name, { node, file }] of sources) tokens.set(name, {
868
+ name,
869
+ category: categoryOf(name),
870
+ value: values.get(name) ?? "",
871
+ file,
872
+ node
873
+ });
874
+ return {
875
+ files,
876
+ tokens,
877
+ layers: layersOf(files)
878
+ };
879
+ }
880
+ /**
881
+ * The layers the global CSS declares at the top level of the cascade, in the
882
+ * order it takes them: by first mention, reading the listed stylesheets in
883
+ * turn and each import where it stands. `@layer` statements and blocks
884
+ * declare them, and so does `@import ... layer(name)`; the layers inside a
885
+ * stylesheet imported into a layer nest in it. A conditional import may not
886
+ * apply, so it declares nothing.
887
+ */
888
+ function layersOf(files) {
889
+ const byFile = new Map(files.map((sheet) => [sheet.file, sheet]));
890
+ const names = /* @__PURE__ */ new Set();
891
+ const read = /* @__PURE__ */ new Set();
892
+ const visit = (sheet) => {
893
+ if (read.has(sheet.file)) return;
894
+ read.add(sheet.file);
895
+ const imports = new Map(sheet.imports.map((imported) => [imported.rule, imported]));
896
+ sheet.root.each((node) => {
897
+ if (node.type !== "atrule") return;
898
+ if (node.name.toLowerCase() === "layer") {
899
+ for (const name of node.params.split(",")) if (name.trim() !== "") names.add(name.trim());
900
+ return;
901
+ }
902
+ const imported = imports.get(node);
903
+ if (!imported || imported.conditional) return;
904
+ const target = byFile.get(imported.file);
905
+ if (imported.layer === null && target) visit(target);
906
+ else if (imported.layer) names.add(imported.layer);
907
+ });
908
+ };
909
+ for (const sheet of files) if (sheet.listed) visit(sheet);
910
+ return [...names];
911
+ }
912
+ function initialValueOf(atRule) {
913
+ return (atRule.nodes?.find((node) => node.type === "decl" && node.prop.toLowerCase() === "initial-value"))?.value ?? "";
914
+ }
915
+ /**
916
+ * The value of each token as text, with every var() of another token replaced
917
+ * by that token's value. A token in a cycle is invalid at computed-value time
918
+ * and stands for nothing, so a var() of it is left as written.
919
+ */
920
+ function resolveValues(texts) {
921
+ const values = /* @__PURE__ */ new Map();
922
+ const cyclic = /* @__PURE__ */ new Set();
923
+ const stack = [];
924
+ const substitute = (name) => {
925
+ const text = texts.get(name);
926
+ if (text === void 0) return null;
927
+ const index = stack.indexOf(name);
928
+ if (index !== -1) {
929
+ for (const member of stack.slice(index)) cyclic.add(member);
930
+ return null;
931
+ }
932
+ if (!values.has(name)) {
933
+ stack.push(name);
934
+ values.set(name, replaceVars(text, substitute));
935
+ stack.pop();
936
+ }
937
+ return cyclic.has(name) ? null : values.get(name) ?? null;
938
+ };
939
+ for (const name of texts.keys()) substitute(name);
940
+ return values;
941
+ }
942
+ /** Replace each var() whose custom property `substitute` gives a value for. */
943
+ function replaceVars(text, substitute) {
944
+ let value;
945
+ try {
946
+ value = parse(text, {
947
+ context: "value",
948
+ positions: true
949
+ });
950
+ } catch {
951
+ return text;
952
+ }
953
+ const replacements = [];
954
+ walk(value, (node) => {
955
+ if (node.type !== "Function" || node.name.toLowerCase() !== "var") return;
956
+ const [reference, , fallback] = node.children.toArray();
957
+ const replacement = reference?.type === "Identifier" ? substitute(reference.name) : null;
958
+ if (replacement !== null && node.loc) replacements.push({
959
+ start: node.loc.start.offset,
960
+ end: node.loc.end.offset,
961
+ text: replacement
962
+ });
963
+ else if (fallback?.type === "Raw" && fallback.loc) replacements.push({
964
+ start: fallback.loc.start.offset,
965
+ end: fallback.loc.end.offset,
966
+ text: replaceVars(fallback.value, substitute)
967
+ });
968
+ return walk.skip;
969
+ });
970
+ let result = text;
971
+ for (const { start, end, text: replacement } of replacements.reverse()) result = result.slice(0, start) + replacement + result.slice(end);
972
+ return result;
973
+ }
974
+ /**
975
+ * Read the global CSS a config lists, following `@import`, and collect its
976
+ * tokens. Throws when a stylesheet cannot be resolved or parsed, imports
977
+ * itself, or is also one of the CSS Modules files. `reading` receives each
978
+ * stylesheet just before it is read, also when the read then fails.
979
+ */
980
+ async function loadGlobalCss(config, reading) {
981
+ const loader = new Loader(config, reading);
982
+ for (const entry of config.globalCss) {
983
+ const file = loader.resolve(config.root, entry);
984
+ if (!file) fail(`cannot resolve "${entry}" listed in globalCss`);
985
+ await loader.load(file, false, []);
986
+ }
987
+ return globalCssFrom(loader.files);
988
+ }
989
+ var Loader = class {
990
+ reading;
991
+ files = [];
992
+ /** Each stylesheet read, with the stylesheets it imports without a condition of its own. */
993
+ read = /* @__PURE__ */ new Map();
994
+ root;
995
+ isModule;
996
+ entries = new ResolverFactory({
997
+ conditionNames: ["style", "default"],
998
+ extensions: []
999
+ });
1000
+ imports = this.entries.cloneWithOptions({
1001
+ conditionNames: ["style", "default"],
1002
+ extensions: [],
1003
+ preferRelative: true
1004
+ });
1005
+ constructor(config, reading) {
1006
+ this.reading = reading;
1007
+ this.root = realpathSync(config.root);
1008
+ this.isModule = createMatcher({
1009
+ ...config,
1010
+ root: this.root
1011
+ });
1012
+ }
1013
+ resolve(directory, specifier) {
1014
+ return this.entries.sync(directory, specifier).path ?? null;
1015
+ }
1016
+ async load(file, conditional, importers) {
1017
+ if (importers.includes(file)) fail(`${[...importers, file].map((f) => this.display(f)).join(" → ")} import each other`);
1018
+ if (this.read.has(file)) {
1019
+ if (!conditional) this.unconditional(file);
1020
+ return;
1021
+ }
1022
+ if (this.isModule(file)) fail(`${this.display(file)} is both a CSS module (include) and global CSS (globalCss)`);
1023
+ this.reading?.(file);
1024
+ let root;
1025
+ try {
1026
+ root = postcss.parse(await fs$1.readFile(file, "utf-8"), { from: file });
1027
+ } catch (error) {
1028
+ if (!(error instanceof CssSyntaxError)) throw error;
1029
+ fail(`${this.display(file)}:${error.line}:${error.column}: ${error.reason}`);
1030
+ }
1031
+ const entry = {
1032
+ file,
1033
+ root,
1034
+ checked: this.isOwn(file),
1035
+ conditional,
1036
+ listed: importers.length === 0,
1037
+ imports: []
1038
+ };
1039
+ const imports = [];
1040
+ this.read.set(file, {
1041
+ entry,
1042
+ imports
1043
+ });
1044
+ for (const node of root.nodes) {
1045
+ if (node.type !== "atrule" || node.name.toLowerCase() !== "import") continue;
1046
+ const prelude = readImport(node.params);
1047
+ if (!prelude) fail(`${this.at(file, node)}: cannot read @import ${node.params}`);
1048
+ const { url, layer, conditional: condition } = prelude;
1049
+ if (/^([a-z][a-z\d+.-]*:|\/\/)/i.test(url)) fail(`${this.at(file, node)}: global CSS cannot import ${url}`);
1050
+ const imported = this.imports.sync(path.dirname(file), url).path;
1051
+ if (!imported) fail(`${this.at(file, node)}: cannot resolve "${url}"`);
1052
+ entry.imports.push({
1053
+ rule: node,
1054
+ file: imported,
1055
+ conditional: condition,
1056
+ layer
1057
+ });
1058
+ if (!condition) imports.push(imported);
1059
+ await this.load(imported, conditional || condition, [...importers, file]);
1060
+ }
1061
+ this.files.push(entry);
1062
+ }
1063
+ /** Count a stylesheet read as a mode as unconditional after all, with what it imports. */
1064
+ unconditional(file) {
1065
+ const reading = this.read.get(file);
1066
+ if (!reading?.entry.conditional) return;
1067
+ reading.entry.conditional = false;
1068
+ for (const imported of reading.imports) this.unconditional(imported);
1069
+ }
1070
+ /** Inside the project and outside node_modules: the files the project can fix. */
1071
+ isOwn(file) {
1072
+ const relative = path.relative(this.root, file);
1073
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) && !relative.split(path.sep).includes("node_modules");
1074
+ }
1075
+ display(file) {
1076
+ return path.relative(process.cwd(), file);
1077
+ }
1078
+ at(file, atRule) {
1079
+ const start = atRule.source?.start;
1080
+ return `${this.display(file)}:${start?.line ?? 1}:${start?.column ?? 1}`;
1081
+ }
1082
+ };
1083
+ /** Read the prelude of an `@import`, or null when it is not one css-tree can read. */
1084
+ function readImport(params) {
1085
+ let prelude;
1086
+ try {
1087
+ prelude = parse(withoutForeignFunctions(params), {
1088
+ context: "atrulePrelude",
1089
+ atrule: "import",
1090
+ positions: true
1091
+ });
1092
+ } catch {
1093
+ return null;
1094
+ }
1095
+ const [target, ...rest] = prelude.type === "AtrulePrelude" ? prelude.children.toArray() : [];
1096
+ if (target?.type !== "String" && target?.type !== "Url" || !target.loc) return null;
1097
+ let layer = null;
1098
+ let conditional = false;
1099
+ for (const node of rest) {
1100
+ const name = node.type === "Function" || node.type === "Identifier" ? node.name.toLowerCase() : "";
1101
+ if (name === "layer") {
1102
+ const [named] = node.type === "Function" ? node.children.toArray() : [];
1103
+ layer = named?.type === "Layer" ? named.name : "";
1104
+ } else if (node.type === "MediaQueryList" && !isUnknownMediaType(node) || node.type === "Function" && name === "supports") conditional = true;
1105
+ }
1106
+ return {
1107
+ url: target.value,
1108
+ urlEnd: target.loc.end.offset,
1109
+ layer,
1110
+ conditional
1111
+ };
1112
+ }
1113
+ /**
1114
+ * Whether a media query list is only a media type CSS does not have, such as
1115
+ * Tailwind's `important`: a word that is not a condition, skipped like the
1116
+ * functions css-tree does not know.
1117
+ */
1118
+ function isUnknownMediaType(list) {
1119
+ const [query, ...others] = list.children.toArray();
1120
+ return others.length === 0 && query?.type === "MediaQuery" && query.modifier === null && query.condition === null && query.mediaType !== null && !MEDIA_TYPES.has(query.mediaType.toLowerCase());
1121
+ }
1122
+ const MEDIA_TYPES = /* @__PURE__ */ new Set([
1123
+ "all",
1124
+ "print",
1125
+ "screen",
1126
+ "tty",
1127
+ "tv",
1128
+ "projection",
1129
+ "handheld",
1130
+ "braille",
1131
+ "embossed",
1132
+ "aural",
1133
+ "speech"
1134
+ ]);
1135
+ /**
1136
+ * The prelude with each top-level function css-tree's grammar of `@import`
1137
+ * does not know, such as Tailwind's `source()`, blanked out: css-tree refuses
1138
+ * the whole prelude over one. Blanking keeps the offsets of the rest.
1139
+ */
1140
+ function withoutForeignFunctions(params) {
1141
+ let value;
1142
+ try {
1143
+ value = parse(params, {
1144
+ context: "value",
1145
+ positions: true
1146
+ });
1147
+ } catch {
1148
+ return params;
1149
+ }
1150
+ let text = params;
1151
+ if (value.type !== "Value") return text;
1152
+ value.children.forEach((node) => {
1153
+ if (node.type !== "Function" || IMPORT_FUNCTIONS.has(node.name.toLowerCase()) || !node.loc) return;
1154
+ const { start, end } = node.loc;
1155
+ text = text.slice(0, start.offset) + " ".repeat(end.offset - start.offset) + text.slice(end.offset);
1156
+ });
1157
+ return text;
1158
+ }
1159
+ const IMPORT_FUNCTIONS = /* @__PURE__ */ new Set(["layer", "supports"]);
1160
+ function fail(message) {
1161
+ throw new ConfigError(message);
1162
+ }
1163
+ //#endregion
1164
+ //#region src/layer.ts
1165
+ const COMPOSES_MESSAGE = "composes does not work inside a cascade layer: lightningcss rejects it, and postcss-modules leaves the rules composed from another file outside the layer; join the class names in JavaScript";
1166
+ /** The layer named `name`, which the global CSS must declare. */
1167
+ function resolveLayer(name, globalCss) {
1168
+ const order = globalCss.layers;
1169
+ if (!order.includes(name)) {
1170
+ const statement = `@layer ${[...order, name].join(", ")};`;
1171
+ throw new ConfigError(globalCss.files.length > 0 ? `layer "${name}" is not declared by the global CSS; declare it there in order, such as ${statement}` : `layer "${name}" needs global CSS that declares it; list one in globalCss with ${statement}`);
1172
+ }
1173
+ return {
1174
+ name,
1175
+ order
1176
+ };
1177
+ }
1178
+ /**
1179
+ * Put the contents of a CSS Modules file in `layer`, behind a statement that
1180
+ * declares every layer in order. Each module repeats the statement, so the
1181
+ * order holds whichever stylesheet the browser loads first.
1182
+ *
1183
+ * Meant to run before the bundler's CSS Modules transform. Throws postcss's
1184
+ * `CssSyntaxError` at a `composes`, which cannot be wrapped.
1185
+ */
1186
+ function wrapInLayer(source, file, layer) {
1187
+ const root = postcss.parse(source, { from: file });
1188
+ root.walkDecls(/^composes$/i, (declaration) => {
1189
+ throw declaration.error(COMPOSES_MESSAGE);
1190
+ });
1191
+ const charset = root.first && isAtRule(root.first, "charset") ? [root.first] : [];
1192
+ const imports = root.nodes.filter((node) => isAtRule(node, "import"));
1193
+ for (const rule of imports) importIntoLayer(rule, layer.name);
1194
+ const outside = /* @__PURE__ */ new Set([...charset, ...imports]);
1195
+ const fileStart = {
1196
+ offset: 0,
1197
+ line: 1,
1198
+ column: 1
1199
+ };
1200
+ const start = root.source && {
1201
+ input: root.source.input,
1202
+ start: fileStart,
1203
+ end: fileStart
1204
+ };
1205
+ const block = postcss.atRule({
1206
+ name: "layer",
1207
+ params: layer.name,
1208
+ source: start
1209
+ });
1210
+ block.append(root.nodes.filter((node) => !outside.has(node)));
1211
+ const statement = postcss.atRule({
1212
+ name: "layer",
1213
+ params: layer.order.join(", "),
1214
+ source: start
1215
+ });
1216
+ root.removeAll();
1217
+ root.append(...charset, statement, ...imports, block);
1218
+ for (const node of root.nodes) node.raws.before = node === root.first ? "" : "\n";
1219
+ Object.assign(block.raws, {
1220
+ between: " ",
1221
+ after: "\n"
1222
+ });
1223
+ if (block.first && !block.first.raws.before?.includes("\n")) block.first.raws.before = "\n";
1224
+ const result = root.toResult({
1225
+ to: file,
1226
+ map: {
1227
+ inline: false,
1228
+ annotation: false
1229
+ }
1230
+ });
1231
+ return {
1232
+ code: result.css,
1233
+ map: result.map.toString()
1234
+ };
1235
+ }
1236
+ /**
1237
+ * What the bundler plugins run on each stylesheet: it wraps the CSS Modules
1238
+ * files the config includes in the layer it names, and resolves to null for
1239
+ * any other file, or for every file when the config names no layer.
1240
+ *
1241
+ * `depend` receives each file of the global CSS it read, also when reading
1242
+ * one failed, before the layer is resolved, so that the bundler wraps the
1243
+ * module again once the file is fixed or the layer declared. The global CSS
1244
+ * is read again only after one of its files has changed, and a read that
1245
+ * failed is tried again on the next call.
1246
+ */
1247
+ function createLayerWrapper(config) {
1248
+ const matches = createMatcher({
1249
+ ...config,
1250
+ root: realpathSync(config.root)
1251
+ });
1252
+ let last;
1253
+ const read = () => {
1254
+ const stamps = /* @__PURE__ */ new Map();
1255
+ return {
1256
+ css: loadGlobalCss(config, (file) => stamps.set(file, modified(file))),
1257
+ stamps
1258
+ };
1259
+ };
1260
+ const unchanged = ({ css, stamps }) => css.then(() => [...stamps].every(([file, stamp]) => modified(file) === stamp), () => false);
1261
+ const current = async () => {
1262
+ const before = last;
1263
+ if (before && await unchanged(before)) return before;
1264
+ if (last === void 0 || last === before) last = read();
1265
+ return last;
1266
+ };
1267
+ return async (source, file, depend) => {
1268
+ if (config.layer === void 0 || !matches(file)) return null;
1269
+ const { css, stamps } = await current();
1270
+ const globalCss = await css.finally(() => {
1271
+ for (const dependency of stamps.keys()) depend(dependency);
1272
+ });
1273
+ return wrapInLayer(source, file, resolveLayer(config.layer, globalCss));
1274
+ };
1275
+ }
1276
+ function modified(file) {
1277
+ return statSync(file, { throwIfNoEntry: false })?.mtimeMs ?? null;
1278
+ }
1279
+ /** `@import url` becomes `@import url layer(name)`, unless it names a layer of its own. */
1280
+ function importIntoLayer(rule, name) {
1281
+ const prelude = readImport(rule.params);
1282
+ if (prelude?.layer !== null) return;
1283
+ const { params } = rule;
1284
+ rule.params = `${params.slice(0, prelude.urlEnd)} layer(${name})${params.slice(prelude.urlEnd)}`;
1285
+ }
1286
+ /**
1287
+ * Report what breaks when the plugins wrap the module in `layer`: an `@layer`
1288
+ * of its own, which would nest, and `composes`.
1289
+ */
1290
+ function checkLayer(root, file, layer, report) {
1291
+ const at = (node, keyword, rule, message) => {
1292
+ const start = node.source?.start ?? {
1293
+ line: 1,
1294
+ column: 1
1295
+ };
1296
+ report(node, [{
1297
+ file,
1298
+ line: start.line,
1299
+ column: start.column,
1300
+ endLine: start.line,
1301
+ endColumn: start.column + keyword.length,
1302
+ rule,
1303
+ message
1304
+ }]);
1305
+ };
1306
+ root.walkAtRules(/^layer$/i, (atRule) => {
1307
+ at(atRule, `@${atRule.name}`, "layer/nested", `the plugins already put this module in the "${layer.name}" layer, so this @layer nests inside it; leave the layer to the plugins`);
1308
+ });
1309
+ root.walkDecls(/^composes$/i, (declaration) => {
1310
+ at(declaration, declaration.prop, "layer/composes", COMPOSES_MESSAGE);
1311
+ });
1312
+ }
1313
+ function isAtRule(node, name) {
1314
+ return node.type === "atrule" && node.name.toLowerCase() === name;
1315
+ }
1316
+ //#endregion
1317
+ //#region src/dts.ts
1318
+ function quoteUnlessIdentifier(name) {
1319
+ return /^[a-zA-Z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
1320
+ }
1321
+ function defaultExportLines(keys) {
1322
+ const declare = "declare const ";
1323
+ const property = " readonly ";
1324
+ const exportDefault = "export default ";
1325
+ return [
1326
+ {
1327
+ text: `${declare}styles: {`,
1328
+ anchors: [{ column: 14 }]
1329
+ },
1330
+ ...keys.map((key) => ({
1331
+ text: `${property}${quoteUnlessIdentifier(key)}: string;`,
1332
+ anchors: [{
1333
+ column: 11,
1334
+ key
1335
+ }]
1336
+ })),
1337
+ {
1338
+ text: "};",
1339
+ anchors: []
1340
+ },
1341
+ {
1342
+ text: `${exportDefault}styles;`,
1343
+ anchors: [{ column: 15 }]
1344
+ }
1345
+ ];
1346
+ }
1347
+ function namedExportLines(keys) {
1348
+ const declare = "declare const ";
1349
+ const esModule = "export declare const ";
1350
+ return [...keys.filter((name) => name !== "default" && name !== "__esModule").flatMap((key, i) => {
1351
+ const local = `_${i}`;
1352
+ const exportAs = `export { ${local} as `;
1353
+ return [{
1354
+ text: `${declare}${local}: string;`,
1355
+ anchors: [{
1356
+ column: 14,
1357
+ key
1358
+ }]
1359
+ }, {
1360
+ text: `${exportAs}${quoteUnlessIdentifier(key)} };`,
1361
+ anchors: [{
1362
+ column: exportAs.length,
1363
+ key
1364
+ }]
1365
+ }];
1366
+ }), {
1367
+ text: `${esModule}__esModule: true;`,
1368
+ anchors: [{ column: 21 }]
1369
+ }];
1370
+ }
1371
+ /**
1372
+ * Where each key is first declared in the stylesheet, or, for a keyframes name
1373
+ * no @keyframes declares, where an animation first refers to it.
1374
+ */
1375
+ function firstOccurrences({ classes, identifiers }) {
1376
+ const declarations = earliest([...classes, ...identifiers.filter(({ kind }) => kind !== "animation")]);
1377
+ const references = earliest(identifiers.filter(({ kind }) => kind === "animation"));
1378
+ return new Map([...references, ...declarations]);
1379
+ }
1380
+ function earliest(occurrences) {
1381
+ const first = /* @__PURE__ */ new Map();
1382
+ for (const { name, range } of occurrences) {
1383
+ const seen = first.get(name);
1384
+ if (!seen || range.start.line < seen.line || range.start.line === seen.line && range.start.column < seen.column) first.set(name, range.start);
1385
+ }
1386
+ return first;
1387
+ }
1388
+ /**
1389
+ * Generate the `.d.ts` of a module, with its keys as properties of the default
1390
+ * export or as named exports, and the declaration map that ties each key to
1391
+ * where the stylesheet first declares it.
1392
+ */
1393
+ function generateDts(analysis, dtsPath, { namedExports }) {
1394
+ const lines = namedExports ? namedExportLines(analysis.exportNames) : defaultExportLines(analysis.exportNames);
1395
+ const first = firstOccurrences(analysis);
1396
+ const top = {
1397
+ line: 1,
1398
+ column: 1
1399
+ };
1400
+ const source = path.relative(path.dirname(dtsPath), analysis.file).split(path.sep).join("/");
1401
+ const map = new SourceMapGenerator({ file: path.basename(dtsPath) });
1402
+ const addMapping = (line, column, at) => map.addMapping({
1403
+ generated: {
1404
+ line,
1405
+ column
1406
+ },
1407
+ source,
1408
+ original: {
1409
+ line: at.line,
1410
+ column: at.column - 1
1411
+ }
1412
+ });
1413
+ addMapping(1, 0, top);
1414
+ lines.forEach(({ anchors }, index) => {
1415
+ for (const { column, key } of anchors) addMapping(index + 1, column, key === void 0 ? top : first.get(key) ?? top);
1416
+ });
1417
+ return {
1418
+ dts: `${lines.map((line) => `${line.text}\n`).join("")}${mapComment(dtsPath)}`,
1419
+ map: map.toString()
1420
+ };
1421
+ }
1422
+ /** The last line of every `.d.ts` the tool writes. */
1423
+ function mapComment(dtsPath) {
1424
+ return `//# sourceMappingURL=${path.basename(dtsPath)}.map\n`;
1425
+ }
1426
+ /**
1427
+ * Where the `.d.ts` for a CSS Modules file goes. Files outside the root are
1428
+ * refused instead of escaping `outDir`, because `rootDirs` could not map them anyway.
1429
+ */
1430
+ function dtsPathFor(cssFile, { root, outDir }) {
1431
+ const relative = path.relative(root, cssFile);
1432
+ if (isOutside(relative)) throw new Error(`${cssFile} is outside the project root ${root}; generated .d.ts files mirror paths relative to the root`);
1433
+ return path.join(root, outDir, `${relative}.d.ts`);
1434
+ }
1435
+ async function writeDts(analysis, options) {
1436
+ const dtsPath = dtsPathFor(analysis.file, options);
1437
+ const { dts, map } = generateDts(analysis, dtsPath, options);
1438
+ await fs$1.mkdir(path.dirname(dtsPath), { recursive: true });
1439
+ await writeIfChanged(`${dtsPath}.map`, map);
1440
+ await writeIfChanged(dtsPath, dts);
1441
+ return dtsPath;
1442
+ }
1443
+ async function writeIfChanged(file, content) {
1444
+ if (await fs$1.readFile(file, "utf-8").catch(() => null) !== content) await fs$1.writeFile(file, content, "utf-8");
1445
+ }
1446
+ /** Remove a .d.ts and its map, and tell whether there was a .d.ts. */
1447
+ async function removeDts(dtsPath) {
1448
+ const [removed] = await Promise.all([fs$1.rm(dtsPath).then(() => true, (error) => {
1449
+ if (isMissing(error)) return false;
1450
+ throw error;
1451
+ }), fs$1.rm(`${dtsPath}.map`, { force: true })]);
1452
+ return removed;
1453
+ }
1454
+ function isMissing(error) {
1455
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1456
+ }
1457
+ /**
1458
+ * Bring the `.d.ts` of one file in line with it after it was added, changed
1459
+ * or deleted. A stylesheet that does not parse (typically mid-edit) yields a
1460
+ * diagnostic and leaves the previous `.d.ts` in place.
1461
+ */
1462
+ async function regenerateDts(cssFile, options) {
1463
+ const loaded = await loadCssModule(cssFile).catch((error) => {
1464
+ if (isMissing(error)) return null;
1465
+ throw error;
1466
+ });
1467
+ if (!loaded) {
1468
+ const dtsPath = dtsPathFor(cssFile, options);
1469
+ return {
1470
+ generated: null,
1471
+ removed: await removeDts(dtsPath) ? dtsPath : null,
1472
+ diagnostics: []
1473
+ };
1474
+ }
1475
+ const { analysis, diagnostics } = loaded;
1476
+ return {
1477
+ generated: analysis && await writeDts(analysis, options),
1478
+ removed: null,
1479
+ diagnostics
1480
+ };
1481
+ }
1482
+ /**
1483
+ * Generate `.d.ts` files for every CSS Modules file the config includes, and
1484
+ * remove the ones it wrote for stylesheets it no longer includes.
1485
+ */
1486
+ async function generate(config) {
1487
+ const found = await findCssModules(config);
1488
+ const { modules, diagnostics } = await loadCssModules(found);
1489
+ const files = await Promise.all(modules.map((analysis) => writeDts(analysis, config)));
1490
+ const produced = new Set(found.map((file) => dtsPathFor(file, config)));
1491
+ const stale = (await outputsIn(config)).filter((dtsPath) => !produced.has(dtsPath));
1492
+ const written = await Promise.all(stale.map(wroteDts));
1493
+ const removed = stale.filter((_, index) => written[index]);
1494
+ await Promise.all(removed.map(removeDts));
1495
+ return {
1496
+ files,
1497
+ removed,
1498
+ diagnostics: sortDiagnostics(diagnostics)
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Whether the tool wrote a `.d.ts`, or left its map behind. With outDir at
1503
+ * the root, a `.d.ts` next to an excluded stylesheet may be hand-written.
1504
+ */
1505
+ async function wroteDts(dtsPath) {
1506
+ const dts = await fs$1.readFile(dtsPath, "utf-8").catch(() => null);
1507
+ return dts === null || dts.endsWith(mapComment(dtsPath));
1508
+ }
1509
+ /**
1510
+ * The `.d.ts` paths in outDir that this config could have produced, whether
1511
+ * the `.d.ts` or only its map is there. Only names an include pattern gives
1512
+ * are taken, because outDir may hold other files, or be the root itself.
1513
+ */
1514
+ async function outputsIn(config) {
1515
+ const patterns = config.include.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [`${pattern}.d.ts`, `${pattern}.d.ts.map`]);
1516
+ const outputs = await fg(patterns, {
1517
+ cwd: path.join(config.root, config.outDir),
1518
+ ignore: ["**/node_modules/**"],
1519
+ absolute: true
1520
+ });
1521
+ return [...new Set(outputs.map((file) => path.resolve(file.replace(/\.map$/, ""))))].sort();
1522
+ }
1523
+ //#endregion
1524
+ export { find as C, property as D, parse as E, walk as O, valueStart as S, lexer as T, sortDiagnostics as _, resolveLayer as a, loadConfig as b, loadGlobalCss as c, findCssModules as d, loadCssModules as f, formatGitHubAnnotation as g, formatDiagnostic as h, createLayerWrapper as i, createMatcher as l, tokenCategories as m, regenerateDts as n, declaresToken as o, categoryOf as p, checkLayer as r, isForeign as s, generate as t, defaultIgnore as u, ConfigError as v, generate$1 as w, paramsStart as x, defineConfig as y };