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