@better-css-modules/core 0.2.0 → 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.
@@ -192,6 +192,7 @@ declare const RULES: {
192
192
  readonly "pure/important": "either";
193
193
  readonly "pure/at-rule": "either";
194
194
  readonly "pure/value": "either";
195
+ readonly "pure/scope": "either";
195
196
  readonly "tokens/unknown": "either";
196
197
  readonly "tokens/internal": "either";
197
198
  readonly "tokens/declaration": "either";
@@ -83,10 +83,12 @@ function analyzeCss(source, file) {
83
83
  function unique(names) {
84
84
  return [...new Set(names)].sort();
85
85
  }
86
- function walkContainer(container, local, collector) {
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) {
87
88
  container.each((node) => {
88
89
  if (node.type === "rule") visitRule(node, local, collector);
89
90
  else if (node.type === "atrule") visitAtRule(node, local, collector);
91
+ else if (node.type === "decl" && node.prop.toLowerCase() === "composes") collectComposes(node, composing, collector);
90
92
  else if (node.type === "decl" && local) visitDeclaration(node, collector);
91
93
  });
92
94
  }
@@ -101,10 +103,7 @@ function visitRule(rule, local, collector) {
101
103
  collector.node = rule;
102
104
  singleClass = collectSelectorList(selector, startOf(rule), local, collector);
103
105
  }
104
- rule.each((child) => {
105
- if (child.type === "decl" && child.prop.toLowerCase() === "composes") collectComposes(child, singleClass, collector);
106
- });
107
- walkContainer(rule, blockLocal, collector);
106
+ walkContainer(rule, blockLocal, collector, rule.parent?.type === "root" ? singleClass : null);
108
107
  }
109
108
  function visitAtRule(atRule, local, collector) {
110
109
  const name = atRule.name.toLowerCase();
@@ -138,12 +137,42 @@ function parseSelectorList(text, base, collector) {
138
137
  line: base.line,
139
138
  column: base.column
140
139
  });
141
- return node.type === "SelectorList" ? node : null;
140
+ if (node.type !== "SelectorList") return null;
141
+ collector.diagnostics.push(...checkSelectorEnds(node, base, collector.file));
142
+ return node;
142
143
  } catch (error) {
143
144
  collector.diagnostics.push(syntaxDiagnostic(collector.file, error, base));
144
145
  return null;
145
146
  }
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
+ }
147
176
  function visitSelectorList(list, local, collector) {
148
177
  list.children.forEach((selector) => {
149
178
  if (selector.type === "Selector") visitSelector(selector, local, collector);
@@ -1216,7 +1245,10 @@ function wrapInLayer(source, file, layer) {
1216
1245
  * failed is tried again on the next call.
1217
1246
  */
1218
1247
  function createLayerWrapper(config) {
1219
- const matches = createMatcher(config);
1248
+ const matches = createMatcher({
1249
+ ...config,
1250
+ root: realpathSync(config.root)
1251
+ });
1220
1252
  let last;
1221
1253
  const read = () => {
1222
1254
  const stamps = /* @__PURE__ */ new Map();
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Diagnostic, c as RuleId, d as ConfigError, f as ResolvedConfig, l as TokenCategory, m as loadConfig, n as generate, o as formatDiagnostic, p as defineConfig, s as formatGitHubAnnotation, t as GenerateResult, u as Config } from "./dts-BjIczsCF.mjs";
1
+ import { a as Diagnostic, c as RuleId, d as ConfigError, f as ResolvedConfig, l as TokenCategory, m as loadConfig, n as generate, o as formatDiagnostic, p as defineConfig, s as formatGitHubAnnotation, t as GenerateResult, u as Config } from "./dts-BLFmeUu6.mjs";
2
2
  import "postcss";
3
3
  //#region src/check.d.ts
4
4
  interface CheckResult {
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as find, D as property, E as parse, O as walk$1, S as valueStart, T as lexer, _ as sortDiagnostics, a as resolveLayer, b as loadConfig, c as loadGlobalCss, d as findCssModules, f as loadCssModules, g as formatGitHubAnnotation, h as formatDiagnostic, m as tokenCategories, o as declaresToken, p as categoryOf, r as checkLayer, s as isForeign, t as generate, u as defaultIgnore, v as ConfigError, w as generate$1, x as paramsStart, y as defineConfig } from "./dts-BWBpx_ii.mjs";
1
+ import { C as find, D as property, E as parse, O as walk$1, S as valueStart, T as lexer, _ as sortDiagnostics, a as resolveLayer, b as loadConfig, c as loadGlobalCss, d as findCssModules, f as loadCssModules, g as formatGitHubAnnotation, h as formatDiagnostic, m as tokenCategories, o as declaresToken, p as categoryOf, r as checkLayer, s as isForeign, t as generate, u as defaultIgnore, v as ConfigError, w as generate$1, x as paramsStart, y as defineConfig } from "./dts-YHloeOKZ.mjs";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { ResolverFactory } from "oxc-resolver";
@@ -168,6 +168,7 @@ const RULES = {
168
168
  "pure/important": "either",
169
169
  "pure/at-rule": "either",
170
170
  "pure/value": "either",
171
+ "pure/scope": "either",
171
172
  "tokens/unknown": "either",
172
173
  "tokens/internal": "either",
173
174
  "tokens/declaration": "either",
@@ -276,6 +277,8 @@ const GLOBAL_AT_RULES = /* @__PURE__ */ new Set([
276
277
  "view-transition",
277
278
  "color-profile"
278
279
  ]);
280
+ const ROOT_AT_CLASS = "write @scope (&) in the rule of its root class";
281
+ const UNROOTED = `an @scope without a root selector is rooted at the parent of the stylesheet's <style> or <link>; ${ROOT_AT_CLASS}`;
279
282
  /**
280
283
  * Check one CSS Module against the pure rules, handing the diagnostics of each
281
284
  * rule, at-rule and declaration to `report` with the node they belong to.
@@ -284,6 +287,8 @@ function checkPure(root, file, report) {
284
287
  walkContainer(root, {
285
288
  nested: false,
286
289
  scoped: false,
290
+ unrooted: false,
291
+ nestedScope: false,
287
292
  local: true
288
293
  }, {
289
294
  file,
@@ -309,6 +314,7 @@ function visitRule(rule, context, checker) {
309
314
  walkContainer(rule, {
310
315
  ...context,
311
316
  nested: true,
317
+ nestedScope: false,
312
318
  local
313
319
  }, checker);
314
320
  }
@@ -330,8 +336,9 @@ function visitAtRule(atRule, context, checker) {
330
336
  if (atRule.nodes) walkContainer(atRule, inner, checker);
331
337
  }
332
338
  /**
333
- * The root of an @scope is local when its selectors have a local subject, or,
334
- * without one, when the @scope is nested in a style rule: that rule is the root.
339
+ * The root of an @scope is local when its selectors have a local subject.
340
+ * Without a root selector, the root is the parent of the stylesheet's owner
341
+ * node, also when the @scope is nested in a style rule or another @scope.
335
342
  */
336
343
  function visitScope(atRule, context, checker) {
337
344
  const text = atRule.raws.params?.raw ?? atRule.params;
@@ -357,16 +364,20 @@ function visitScope(atRule, context, checker) {
357
364
  };
358
365
  for (const list of [root, scope?.limit]) if (list?.type === "SelectorList") scanList(list, context.local, false, text, scan);
359
366
  checker.report(atRule, [...scan.globals.map((found) => globalDiagnostic(found, checker.file)), ...scan.ids.map((found) => idDiagnostic(found, checker.file))]);
360
- const rooted = root ? hasLocalSubjects(root, context.local, context.nested) : context.nested;
367
+ const unrooted = !scope?.root;
368
+ const rooted = root !== null && hasLocalSubjects(root, context.local, context.nested);
361
369
  return {
362
370
  ...context,
363
- scoped: context.scoped || rooted
371
+ scoped: !unrooted && (context.scoped || rooted),
372
+ unrooted,
373
+ nestedScope: context.nested
364
374
  };
365
375
  }
366
376
  function checkSelectorList(list, text, context, file) {
367
377
  const diagnostics = [];
368
378
  list.children.forEach((selector) => {
369
379
  if (selector.type !== "Selector") return;
380
+ if (selector.children.last?.type === "Combinator") return;
370
381
  const scan = {
371
382
  local: false,
372
383
  globals: [],
@@ -374,15 +385,21 @@ function checkSelectorList(list, text, context, file) {
374
385
  };
375
386
  scanSelector(selector, context.local, false, text, scan);
376
387
  if (!context.nested && !scan.local) {
377
- const hint = context.scoped ? ", and bundlers do not count the root of a top-level @scope; nest the @scope inside the rule of its root class" : "; every selector of a CSS Module needs one";
378
- diagnostics.push(diagnosticAt$1({
379
- node: selector,
380
- text
381
- }, file, "pure/selector", (written) => `${written} has no local class${hint}`));
388
+ if (scan.globals.length === 0) {
389
+ const hint = context.scoped ? `, and bundlers do not count the root of a top-level @scope; ${ROOT_AT_CLASS}` : context.unrooted ? `, and ${UNROOTED}` : "; every selector of a CSS Module needs one";
390
+ diagnostics.push(diagnosticAt$1({
391
+ node: selector,
392
+ text
393
+ }, file, "pure/selector", (written) => `${written} has no local class${hint}`));
394
+ }
382
395
  } else if (!context.scoped) {
383
396
  const subject = subjectOf(selector, context.local);
384
- if (!isLocalCompound(subject, context.nested) && !isReportedElsewhere(subject)) diagnostics.push(subjectDiagnostic(subject, text, file));
397
+ if (subject.length > 0 && !isLocalCompound(subject, context.nested) && !isReportedElsewhere(subject)) diagnostics.push(subjectDiagnostic(subject, text, context.unrooted, file));
385
398
  }
399
+ if (context.nestedScope && find(selector, isScopePseudoClass) && !find(selector, isNesting)) diagnostics.push(scopeDiagnostic({
400
+ node: selector,
401
+ text
402
+ }, file));
386
403
  diagnostics.push(...scan.globals.map((found) => globalDiagnostic(found, file)), ...scan.ids.map((found) => idDiagnostic(found, file)));
387
404
  });
388
405
  return diagnostics;
@@ -488,11 +505,17 @@ function hasLocalSubjects(list, local, nested) {
488
505
  function isReportedElsewhere(parts) {
489
506
  return parts.some(({ node, local }) => !local || find(node, (child) => child.type === "IdSelector" || child.type === "PseudoClassSelector" && child.name.toLowerCase() === "global") !== null);
490
507
  }
508
+ function isScopePseudoClass(node) {
509
+ return node.type === "PseudoClassSelector" && node.name.toLowerCase() === "scope";
510
+ }
511
+ function isNesting(node) {
512
+ return node.type === "NestingSelector";
513
+ }
491
514
  function isScoping(node) {
492
515
  const name = node.name.toLowerCase();
493
516
  return name === "global" || name === "local";
494
517
  }
495
- function subjectDiagnostic(parts, text, file) {
518
+ function subjectDiagnostic(parts, text, unrooted, file) {
496
519
  const first = parts[0].node.loc;
497
520
  const last = parts[parts.length - 1].node.loc;
498
521
  const written = first && last ? text.slice(first.start.offset, last.end.offset) : "";
@@ -503,11 +526,14 @@ function subjectDiagnostic(parts, text, file) {
503
526
  endLine: last?.end.line,
504
527
  endColumn: last?.end.column,
505
528
  rule: "pure/subject",
506
- message: `${written} is not a local class; give the element a class of its own, or style markup the component does not write inside @scope`
529
+ message: unrooted ? `${written} is not a local class, and ${UNROOTED}` : `${written} is not a local class; give the element a class of its own, or style markup the component does not write inside @scope (&)`
507
530
  };
508
531
  }
509
532
  function globalDiagnostic(found, file) {
510
- return diagnosticAt$1(found, file, "pure/global", (written) => `${written} reaches outside this module; a mode overrides tokens in the global CSS, and markup the component does not write is styled inside @scope`);
533
+ return diagnosticAt$1(found, file, "pure/global", (written) => `${written} reaches outside this module; a mode overrides tokens in the global CSS, and markup the component does not write is styled inside @scope (&)`);
534
+ }
535
+ function scopeDiagnostic(found, file) {
536
+ return diagnosticAt$1(found, file, "pure/scope", (written) => `lightningcss (Turbopack) rewrites ${written} to & ${written} in an @scope nested in a rule, which matches nothing; write ${written.replace(/:scope\b/gi, "&")}`);
511
537
  }
512
538
  function idDiagnostic(found, file) {
513
539
  return diagnosticAt$1(found, file, "pure/id", (written) => `${written} is an id; its specificity defeats overrides from outside the component, so use a class`);
@@ -1833,6 +1859,7 @@ var Resolvers = class {
1833
1859
  references: "auto"
1834
1860
  } } : {}
1835
1861
  });
1862
+ if (tsconfig) checkTsconfig(resolver, tsconfig);
1836
1863
  this.byTsconfig.set(tsconfig, resolver);
1837
1864
  }
1838
1865
  return resolver;
@@ -1848,6 +1875,17 @@ var Resolvers = class {
1848
1875
  return found;
1849
1876
  }
1850
1877
  };
1878
+ /**
1879
+ * The resolver reads the tsconfig at its first resolution, and one it cannot
1880
+ * read (an `extends` that does not resolve, a syntax error) fails every
1881
+ * resolution after it, relative imports included, which would leave every
1882
+ * module unused. Resolving the tsconfig itself, a file that exists, fails for
1883
+ * that reason only.
1884
+ */
1885
+ function checkTsconfig(resolver, tsconfig) {
1886
+ const { error } = resolver.sync(path.dirname(tsconfig), `./${path.basename(tsconfig)}`);
1887
+ if (error) throw new ConfigError(`${relative(process.cwd(), tsconfig)} cannot be read, so imports cannot be resolved: ${error}`);
1888
+ }
1851
1889
  //#endregion
1852
1890
  //#region src/check.ts
1853
1891
  const CSS_WIDE_KEYWORDS = /* @__PURE__ */ new Set([
@@ -1953,7 +1991,8 @@ async function check(config) {
1953
1991
  if (files.length === 0) throw new ConfigError(`include matches no files in the project root ${config.root}: ${config.include.join(", ")}`);
1954
1992
  const globalCss = await loadGlobalCss(config);
1955
1993
  const layer = config.layer === void 0 ? void 0 : resolveLayer(config.layer, globalCss);
1956
- const { modules, diagnostics } = await loadCssModules(files.map((file) => fs.realpathSync(file)));
1994
+ const real = [...new Set(files.map((file) => fs.realpathSync(file)))];
1995
+ const { modules, diagnostics } = await loadCssModules(real);
1957
1996
  const usage = await analyzeUsage(modules, config);
1958
1997
  const found = [
1959
1998
  ...diagnostics,
@@ -1963,7 +2002,7 @@ async function check(config) {
1963
2002
  const declared = new Set([...globalCss.tokens.values()].map(({ category }) => category));
1964
2003
  return {
1965
2004
  diagnostics: sortDiagnostics(found),
1966
- modules: files.length,
2005
+ modules: real.length,
1967
2006
  tokens: Object.keys(tokenCategories).filter((category) => declared.has(category))
1968
2007
  };
1969
2008
  }
@@ -1978,8 +2017,8 @@ async function check(config) {
1978
2017
  * arithmetic on its tokens pass. Anywhere in the file a token name the global
1979
2018
  * CSS does not declare is reported, and so is a name it declares without a
1980
2019
  * category prefix, which is internal to it. A module cannot declare either kind
1981
- * of name. `composes` outside a rule of a single local class is reported,
1982
- * which bundlers reject. With a layer, what wrapping the module in it would
2020
+ * of name. `composes` outside a top-level rule of a single local class is
2021
+ * reported, which lightningcss rejects. With a layer, what wrapping the module in it would
1983
2022
  * break is reported too. The usage problems found about the module are
1984
2023
  * passed in, so that its disable comments apply to them as well. Pure: reads
1985
2024
  * nothing but its arguments.
@@ -2001,7 +2040,7 @@ function checkCss(analysis, globalCss, layer, usage = []) {
2001
2040
  endLine: range.end.line,
2002
2041
  endColumn: range.end.column,
2003
2042
  rule: "invalid-composes",
2004
- message: "composes is only allowed in a rule whose selector is a single local class"
2043
+ message: "composes is only allowed in a top-level rule whose selector is a single local class"
2005
2044
  }))]);
2006
2045
  }
2007
2046
  /**
@@ -2316,8 +2355,9 @@ function checkTimes(nodes, scope) {
2316
2355
  }
2317
2356
  /**
2318
2357
  * Report a `var()` of a custom property that is not a token of the category.
2319
- * A name of the category the global CSS does not declare, and outside the
2320
- * global CSS an internal name, are left to `checkReferences`.
2358
+ * A name of the category the global CSS does not declare is left to
2359
+ * `checkReferences`, and so is an internal name outside the global CSS, which
2360
+ * uses its internal names freely.
2321
2361
  */
2322
2362
  function checkToken(node, scope, inShorthand = false) {
2323
2363
  const name = node.children.first;
@@ -2325,8 +2365,7 @@ function checkToken(node, scope, inShorthand = false) {
2325
2365
  const { category, hint } = scope.restriction;
2326
2366
  const own = categoryOf(name.name);
2327
2367
  if (own === category) return;
2328
- const { tokens, global } = scope.context;
2329
- if (own === null && !global && tokens.has(name.name)) return;
2368
+ if (own === null && scope.context.tokens.has(name.name)) return;
2330
2369
  report(scope, node, node, inShorthand ? `${name.name} is taken for the ${category} of this shorthand and is not a ${category} token; ${hint}, or write the longhand` : `${name.name} is not a ${category} token; ${hint}`);
2331
2370
  }
2332
2371
  /** The components of the fallback of a `var()`, which css-tree keeps as raw text. */
@@ -1,4 +1,4 @@
1
- import { f as ResolvedConfig, i as createLayerWrapper, r as LayerConfig, t as GenerateResult } from "./dts-BjIczsCF.mjs";
1
+ import { f as ResolvedConfig, i as createLayerWrapper, r as LayerConfig, t as GenerateResult } from "./dts-BLFmeUu6.mjs";
2
2
  //#region src/watcher.d.ts
3
3
  /**
4
4
  * Run `generate` and print how many `.d.ts` files it wrote and which it
package/dist/internal.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { h as formatDiagnostic, i as createLayerWrapper, l as createMatcher, n as regenerateDts, t as generate } from "./dts-BWBpx_ii.mjs";
1
+ import { h as formatDiagnostic, i as createLayerWrapper, l as createMatcher, n as regenerateDts, t as generate } from "./dts-YHloeOKZ.mjs";
2
2
  import path from "node:path";
3
3
  import { watch } from "chokidar";
4
4
  //#region src/watcher.ts
@@ -70,7 +70,8 @@ function createSync(config) {
70
70
  */
71
71
  function startWatcher(config, { persistent = true } = {}) {
72
72
  const { root } = config;
73
- const baseDirs = [...new Set(config.include.map(extractBaseDir))];
73
+ const included = config.include.filter((pattern) => !pattern.startsWith("!"));
74
+ const baseDirs = [...new Set(included.map(extractBaseDir))];
74
75
  const sync = createSync(config);
75
76
  const outDir = path.resolve(root, config.outDir);
76
77
  const ignored = (watched) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-css-modules/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Analysis, type generation, unused-class detection, token checks, watcher and config for better-css-modules",
5
5
  "keywords": [
6
6
  "css-modules",