@ecopages/lightningcss-processor 0.0.0-stage → 0.6.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.
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/package.json +76 -4
- package/src/bundle-stylesheet.d.ts +35 -0
- package/src/bundle-stylesheet.js +243 -0
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/src/lightningcss-engine.d.ts +151 -0
- package/src/lightningcss-engine.js +191 -0
- package/src/plugin.d.ts +54 -0
- package/src/plugin.js +96 -0
- package/src/plugins/suffix-nesting.d.ts +33 -0
- package/src/plugins/suffix-nesting.js +474 -0
- package/src/preprocessor.d.ts +40 -0
- package/src/preprocessor.js +1 -0
- package/src/presets/tailwind-reference.d.ts +17 -0
- package/src/presets/tailwind-reference.js +101 -0
- package/src/presets/tailwind-v4.d.ts +47 -0
- package/src/presets/tailwind-v4.js +256 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-present Andrea Zanenghi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ecopages/lightningcss-processor
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A stylesheet Processor for Ecopages that runs [Lightning CSS](https://lightningcss.dev): it bundles `@import`, lowers modern CSS for the browsers you target, and minifies. It is a native package with no PostCSS plugins to configure.
|
|
4
|
+
|
|
5
|
+
## When to pick it
|
|
6
|
+
|
|
7
|
+
- Pick this package for plain CSS: nesting, `color-mix()`, `@import` with `layer()`, `supports()` and media conditions, lowered for your browser targets in one step.
|
|
8
|
+
- Pick this package with the [Tailwind v4 preset](#tailwind-v4) to run Tailwind v4 with Lightning CSS targets, bundling and CSS Modules, and no PostCSS.
|
|
9
|
+
- Pick [`@ecopages/postcss-processor`](../postcss-processor) when your setup is built on PostCSS plugins, and for Tailwind v3.
|
|
10
|
+
|
|
11
|
+
An app has one stylesheet Processor, so this one replaces the PostCSS Processor; it does not run after it.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
bun add @ecopages/lightningcss-processor
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
// eco.config.ts
|
|
23
|
+
import { defineConfig } from '@ecopages/core/config';
|
|
24
|
+
import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
|
|
25
|
+
|
|
26
|
+
export default defineConfig({
|
|
27
|
+
processors: [lightningCssProcessorPlugin({ targets: ['chrome >= 90', 'safari >= 15'] })],
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Tailwind v4
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
bun add -d @tailwindcss/node @tailwindcss/oxide tailwindcss
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
// eco.config.ts
|
|
39
|
+
import path from 'node:path';
|
|
40
|
+
import { defineConfig } from '@ecopages/core/config';
|
|
41
|
+
import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
|
|
42
|
+
import { tailwindV4Preset } from '@ecopages/lightningcss-processor/presets/tailwind-v4';
|
|
43
|
+
|
|
44
|
+
export default defineConfig({
|
|
45
|
+
processors: [
|
|
46
|
+
lightningCssProcessorPlugin({
|
|
47
|
+
...tailwindV4Preset({ referencePath: path.resolve(import.meta.dirname, 'src/styles/tailwind.css') }),
|
|
48
|
+
targets: ['chrome >= 111', 'safari >= 16.4'],
|
|
49
|
+
}),
|
|
50
|
+
],
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`referencePath` is the stylesheet that contains `@import "tailwindcss";`. Tailwind runs inside the Processor, so the app needs no PostCSS, and its output goes through the options below. The peers are optional: an app that does not use the preset never installs them. A stylesheet that uses `@apply`, and every CSS Module, gets an `@reference` to `referencePath`. In development, a saved template that uses a new class rebuilds the stylesheets that scan it.
|
|
55
|
+
|
|
56
|
+
## Options
|
|
57
|
+
|
|
58
|
+
| Option | Description |
|
|
59
|
+
| :-------------- | :---------------------------------------------------------------------------------------------------- |
|
|
60
|
+
| `targets` | Browserslist queries, a string or an array. Unset, nothing is lowered. |
|
|
61
|
+
| `minify` | Minify the CSS. On in production, off otherwise. |
|
|
62
|
+
| `drafts` | Draft syntax, such as `{ customMedia: true }`. |
|
|
63
|
+
| `nonStandard` | Non-standard syntax, such as `{ deepSelectorCombinator: true }`. |
|
|
64
|
+
| `include` | Names of Lightning CSS `Features` to compile even when `targets` support them, such as `['Nesting']`. |
|
|
65
|
+
| `exclude` | Names of `Features` to leave as written even when `targets` do not support them. |
|
|
66
|
+
| `visitor` | A Lightning CSS visitor, run over every stylesheet. |
|
|
67
|
+
| `plugins` | [Plugins](#plugins) that rewrite the source or visit the rules of every stylesheet, in order. |
|
|
68
|
+
| `errorRecovery` | Drop a rule Lightning CSS cannot parse with a warning, instead of failing the stylesheet. |
|
|
69
|
+
| `filter` | Regex that picks the stylesheets to process. Default `/\.css$/`. |
|
|
70
|
+
| `cssModules` | `{ pattern }`: how scoped class names are built. Default `'[hash]_[local]'`. |
|
|
71
|
+
|
|
72
|
+
## Plugins
|
|
73
|
+
|
|
74
|
+
A plugin is `{ name, transformSource?(css, file), visitor? }`. `transformSource` rewrites a stylesheet before Lightning CSS parses it, and before the Tailwind preset runs, so what it writes can use `@apply`. `visitor` is a Lightning CSS `Visitor`, composed with the `visitor` option. Plugins run in the order of the array, on every stylesheet: the entry, each imported partial (including the ones the Tailwind preset inlines) and every CSS Module.
|
|
75
|
+
|
|
76
|
+
Lightning CSS stays standard by default: Sass-style suffix nesting (`&--primary`, `&__element`) fails the build. If you like that style, opt in with `suffixNesting()`:
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
|
|
80
|
+
import { suffixNesting } from '@ecopages/lightningcss-processor/plugins/suffix-nesting';
|
|
81
|
+
|
|
82
|
+
lightningCssProcessorPlugin({
|
|
83
|
+
...tailwindV4Preset({ referencePath }),
|
|
84
|
+
targets: ['chrome >= 111', 'safari >= 16.4'],
|
|
85
|
+
plugins: [suffixNesting()],
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`suffixNesting()` rewrites `&--x`, `&__x` and `&-x` into native nesting before parsing. `.button, a.button { &--primary { ... } }` becomes `.button--primary, a.button--primary { ... }`, written after the rule it came from, so rules nested in it, such as `&:hover svg`, and the order of the cascade keep working. It also expands inside `:is()`, `:where()` and `:not()`, and in an `@media` that sits in the parent. Every parent selector must be one compound selector ending in a class, id or type; a parent such as `.card .title` fails the build with the file, line, column and selector, instead of a guess. Anything a plugin leaves invalid still fails, so a typo is not dropped silently.
|
|
90
|
+
|
|
91
|
+
## Behaviour
|
|
92
|
+
|
|
93
|
+
- A `*.module.css` file is a CSS Module: `import styles from './button.module.css'` gives the component a map of local class names to scoped ones, the same on the server and in the browser, and the scoped CSS reaches the Page like any component stylesheet. Names hash the path relative to the app, so they match across folders. `composes ... from` bundles the other file. Only the default export is provided.
|
|
94
|
+
- The native binding loads on the first stylesheet, never while the config is read.
|
|
95
|
+
- `@import` is bundled by Lightning CSS. A relative path, a tsconfig alias or a package resolves as core resolves it, and the `layer()`, `supports()` and media conditions stay. For a stylesheet imported twice, the last import wins. An import that closes a cycle is skipped with a warning.
|
|
96
|
+
- A root-relative or remote `@import` stays external and moves to the top of the output. An `@import` of a missing file, of a dotfile or of a file that is not `.css` is left as written with a warning that names the importing file. Creating the missing file rebuilds the stylesheet in development.
|
|
97
|
+
- The relative `url()` references of an imported partial are rewritten to name the same file from the importing stylesheet. Core then copies what they name by file type, as it does for any stylesheet.
|
|
98
|
+
- An error throws with the file, line and column, so `ecopages build` fails; `ecopages dev` shows the error and keeps the last good output until a save fixes it. Warnings are logged with their location, once per stylesheet.
|
|
99
|
+
- Importing one partial under two different `layer()` names fails in Lightning CSS, where core inlines both.
|
|
100
|
+
- Editing a nested partial rebuilds the stylesheets that import it.
|
|
101
|
+
|
|
102
|
+
See the [developer page](https://ecopages.app/dev/lightningcss-processor) for the design.
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/lightningcss-processor",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.1",
|
|
4
|
+
"description": "Lightning CSS stylesheet processor for Ecopages: bundles @import, lowers for browser targets and minifies",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"lightningcss",
|
|
7
|
+
"processor",
|
|
8
|
+
"css"
|
|
9
|
+
],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": "^24.22.0 || >=26.0.0"
|
|
13
|
+
},
|
|
14
|
+
"main": "./src/index.js",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"types": "./src/index.d.ts",
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/ecopages/ecopages.git",
|
|
23
|
+
"directory": "packages/processors/lightningcss-processor"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@ecopages/file-system": "0.6.1",
|
|
27
|
+
"@ecopages/logger": "^0.2.3",
|
|
28
|
+
"browserslist": "^4.28.2",
|
|
29
|
+
"lightningcss": "1.33.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@ecopages/core": "0.6.1",
|
|
33
|
+
"@tailwindcss/node": ">=4",
|
|
34
|
+
"@tailwindcss/oxide": ">=4",
|
|
35
|
+
"tailwindcss": ">=4"
|
|
36
|
+
},
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"default": "./src/index.js",
|
|
40
|
+
"types": "./src/index.d.ts"
|
|
41
|
+
},
|
|
42
|
+
"./plugin": {
|
|
43
|
+
"default": "./src/plugin.js",
|
|
44
|
+
"types": "./src/plugin.d.ts"
|
|
45
|
+
},
|
|
46
|
+
"./presets/tailwind-v4": {
|
|
47
|
+
"default": "./src/presets/tailwind-v4.js",
|
|
48
|
+
"types": "./src/presets/tailwind-v4.d.ts"
|
|
49
|
+
},
|
|
50
|
+
"./plugins/suffix-nesting": {
|
|
51
|
+
"default": "./src/plugins/suffix-nesting.js",
|
|
52
|
+
"types": "./src/plugins/suffix-nesting.d.ts"
|
|
53
|
+
},
|
|
54
|
+
"./plugin.ts": {
|
|
55
|
+
"default": "./src/plugin.js",
|
|
56
|
+
"types": "./src/plugin.d.ts"
|
|
57
|
+
},
|
|
58
|
+
"./presets/tailwind-v4.ts": {
|
|
59
|
+
"default": "./src/presets/tailwind-v4.js",
|
|
60
|
+
"types": "./src/presets/tailwind-v4.d.ts"
|
|
61
|
+
},
|
|
62
|
+
"./plugins/suffix-nesting.ts": {
|
|
63
|
+
"default": "./src/plugins/suffix-nesting.js",
|
|
64
|
+
"types": "./src/plugins/suffix-nesting.d.ts"
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"@tailwindcss/node": {
|
|
69
|
+
"optional": true
|
|
70
|
+
},
|
|
71
|
+
"@tailwindcss/oxide": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"tailwindcss": {
|
|
75
|
+
"optional": true
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { CSSModuleExports, Warning } from 'lightningcss';
|
|
2
|
+
import { type ResolvedLightningCssOptions } from './lightningcss-engine.js';
|
|
3
|
+
/** A stylesheet with its `@import`s inlined, and the files that took part. */
|
|
4
|
+
export type BundledStylesheet = {
|
|
5
|
+
/** The bundled CSS, as Lightning CSS wrote it; the hoisted `@import`s are not yet in it. */
|
|
6
|
+
code: Uint8Array;
|
|
7
|
+
/** The `@import` statements that stay external, in order, to put at the top of the output. */
|
|
8
|
+
hoisted: string[];
|
|
9
|
+
/** The warnings Lightning CSS raised. */
|
|
10
|
+
warnings: Warning[];
|
|
11
|
+
/** The partials read, and the `.css` files an `@import` named that do not exist yet. */
|
|
12
|
+
dependencies: string[];
|
|
13
|
+
/** The scoped class names of a CSS Module, by local name; absent for any other stylesheet. */
|
|
14
|
+
exports?: CSSModuleExports;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The file a stylesheet is scoped as, or `undefined` for a file of the app.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* A file of an installed package is scoped by its package name and the path inside the package (see
|
|
21
|
+
* `toPackageScopeFile`), whichever folder or package-manager layout it is installed in. The stylesheet itself is
|
|
22
|
+
* always read from its real path.
|
|
23
|
+
*/
|
|
24
|
+
export declare function packageScopeFile(file: string, rootDir: string): string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Bundles the `@import`s of an app stylesheet with Lightning CSS.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* `css` is the in-memory source of `file`, which may differ from the file on disk, and is bundled as given: the caller
|
|
30
|
+
* runs the `transformSource` of the plugins on it, and this function runs them on every partial it reads. A cycle of `@import`s and a
|
|
31
|
+
* stylesheet imported twice are handled by Lightning CSS: the last import of a stylesheet wins, as the specification says.
|
|
32
|
+
* Lightning CSS names the files of a package CSS Module by their scope file (see {@link packageScopeFile}), which
|
|
33
|
+
* is what its class names hash.
|
|
34
|
+
*/
|
|
35
|
+
export declare function bundleStylesheet(css: string, file: string, rootDir: string, options: ResolvedLightningCssOptions): Promise<BundledStylesheet>;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { isExternalReference, rebaseStylesheetReferences, resolvePackageStylesheetPath, resolveProjectImportPath, scanCss, splitReference, toPackageScopeFile, warnStylesheetOnce, } from '@ecopages/core/processor';
|
|
2
|
+
import { fileSystem } from '@ecopages/file-system';
|
|
3
|
+
import { path } from '@ecopages/file-system/path';
|
|
4
|
+
import { Logger } from '@ecopages/logger';
|
|
5
|
+
import { loadLightningCss, suffixNestingError, transformSourceWithPlugins, suffixNestingVisitor, } from './lightningcss-engine.js';
|
|
6
|
+
const logger = new Logger('[@ecopages/lightningcss-processor]');
|
|
7
|
+
/** A stylesheet Lightning CSS scopes as a CSS Module. */
|
|
8
|
+
const CSS_MODULE_FILE = /\.module\.css$/iu;
|
|
9
|
+
const COMPOSES_FROM = /\bcomposes\s*:[^;{}]*?\bfrom\s+(?:'([^']+)'|"([^"]+)")/giu;
|
|
10
|
+
/** The specifiers of the stylesheets `css` composes classes from, other than `global`, in order and once each. */
|
|
11
|
+
function composedStylesheets(css) {
|
|
12
|
+
const withoutComments = css.replace(/\/\*[\s\S]*?\*\//gu, '');
|
|
13
|
+
const specifiers = [...withoutComments.matchAll(COMPOSES_FROM)].map((match) => match[1] ?? match[2]);
|
|
14
|
+
return [...new Set(specifiers)];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The file a stylesheet is scoped as, or `undefined` for a file of the app.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* A file of an installed package is scoped by its package name and the path inside the package (see
|
|
21
|
+
* `toPackageScopeFile`), whichever folder or package-manager layout it is installed in. The stylesheet itself is
|
|
22
|
+
* always read from its real path.
|
|
23
|
+
*/
|
|
24
|
+
export function packageScopeFile(file, rootDir) {
|
|
25
|
+
return toPackageScopeFile(fileSystem.exists(file) ? fileSystem.realpath(file) : file, rootDir);
|
|
26
|
+
}
|
|
27
|
+
const resolutionKey = (importer, specifier) => `${importer}\0${specifier}`;
|
|
28
|
+
/**
|
|
29
|
+
* The state of bundling one stylesheet.
|
|
30
|
+
*
|
|
31
|
+
* @remarks
|
|
32
|
+
* `prepare` walks the imports depth first, in the order written, before Lightning CSS runs, so what is hoisted and
|
|
33
|
+
* which import closes a cycle do not depend on the order Lightning CSS reads files in. A relative `@import` resolves
|
|
34
|
+
* from the path as written, symlinks included, and a `url()` from the real directory, as core's scanner does for the
|
|
35
|
+
* same file. Lightning CSS only ever sees real paths.
|
|
36
|
+
*/
|
|
37
|
+
class StylesheetBundle {
|
|
38
|
+
dependencies = new Set();
|
|
39
|
+
/** The `@import` statements that stay external, in the order core hoists them. */
|
|
40
|
+
hoisted = [];
|
|
41
|
+
/** The prepared CSS of each file, by real path. */
|
|
42
|
+
scanned = new Map();
|
|
43
|
+
resolutions = new Map();
|
|
44
|
+
/** The real path of each file Lightning CSS was given a package scope file for. */
|
|
45
|
+
realByScope = new Map();
|
|
46
|
+
/** The real paths of the files being walked, innermost last. */
|
|
47
|
+
stack = [];
|
|
48
|
+
entry;
|
|
49
|
+
source;
|
|
50
|
+
rootDir;
|
|
51
|
+
cssModules;
|
|
52
|
+
plugins;
|
|
53
|
+
constructor(entry, source, rootDir, cssModules, plugins) {
|
|
54
|
+
this.entry = entry;
|
|
55
|
+
this.source = source;
|
|
56
|
+
this.rootDir = rootDir;
|
|
57
|
+
this.cssModules = cssModules;
|
|
58
|
+
this.plugins = plugins;
|
|
59
|
+
}
|
|
60
|
+
warn(message) {
|
|
61
|
+
warnStylesheetOnce(this.entry, this.source, `${this.entry}: ${message}`, (text) => logger.warn(text));
|
|
62
|
+
}
|
|
63
|
+
/** The file an `@import` of `importer` names, before any check of what it is. */
|
|
64
|
+
locate(specifier, importer) {
|
|
65
|
+
const { decoded } = splitReference(specifier);
|
|
66
|
+
const sibling = path.resolve(path.dirname(importer), decoded);
|
|
67
|
+
if (decoded.startsWith('.') || fileSystem.exists(sibling))
|
|
68
|
+
return sibling;
|
|
69
|
+
try {
|
|
70
|
+
return (resolveProjectImportPath(this.rootDir, importer, decoded) ??
|
|
71
|
+
resolvePackageStylesheetPath(importer, specifier));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Resolves an `@import` the way core does: relative to the importer, then a tsconfig alias, then a package.
|
|
79
|
+
*
|
|
80
|
+
* @remarks
|
|
81
|
+
* Only a `.css` file is inlined, never a dotfile, so an `@import` cannot publish another file. An `@import` that
|
|
82
|
+
* names nothing usable is left as written with a warning that names the importer, and a missing `.css` file is
|
|
83
|
+
* a dependency, so creating it rebuilds the stylesheet.
|
|
84
|
+
*/
|
|
85
|
+
resolveImport(specifier, importer) {
|
|
86
|
+
if (isExternalReference(specifier))
|
|
87
|
+
return undefined;
|
|
88
|
+
const located = this.locate(specifier, importer);
|
|
89
|
+
if (!located || !fileSystem.exists(located)) {
|
|
90
|
+
if (located && path.extname(located).toLowerCase() === '.css')
|
|
91
|
+
this.dependencies.add(path.resolve(located));
|
|
92
|
+
this.warn(`@import ${JSON.stringify(specifier)} in ${importer} names ${located ?? 'nothing that resolves'}, which does not exist, so it is left as written.`);
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
const real = fileSystem.realpath(located);
|
|
96
|
+
if (path.extname(real).toLowerCase() !== '.css' || path.basename(real).startsWith('.')) {
|
|
97
|
+
this.warn(`@import ${JSON.stringify(specifier)} in ${importer} names ${real}, which is not a stylesheet, so it is left as written.`);
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
return { located, real };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Prepares `file` for Lightning CSS: its `url()` references rebased onto the entry, and its `@import`s resolved, with
|
|
104
|
+
* each partial prepared where it is imported.
|
|
105
|
+
*
|
|
106
|
+
* @remarks
|
|
107
|
+
* The plugins rewrite the source of a partial first, as it is read. An external `@import` is taken out to be hoisted, since Lightning CSS fails on one that follows a bundled
|
|
108
|
+
* `@import`, where core hoists them all to the top of the output. An `@import` that closes a cycle is taken out
|
|
109
|
+
* with a warning, since Lightning CSS drops the CSS of every stylesheet in a cycle, where core inlines each once.
|
|
110
|
+
*/
|
|
111
|
+
async prepare(file = this.entry) {
|
|
112
|
+
const real = fileSystem.exists(file) ? fileSystem.realpath(file) : file;
|
|
113
|
+
if (this.scanned.has(real))
|
|
114
|
+
return;
|
|
115
|
+
this.scanned.set(real, '');
|
|
116
|
+
this.stack.push(real);
|
|
117
|
+
const isEntry = file === this.entry;
|
|
118
|
+
let css = isEntry ? this.source : fileSystem.readFileSync(file);
|
|
119
|
+
if (!isEntry) {
|
|
120
|
+
this.dependencies.add(file);
|
|
121
|
+
css = rebaseStylesheetReferences(await transformSourceWithPlugins(css, file, this.plugins), file, this.entry);
|
|
122
|
+
}
|
|
123
|
+
const composed = this.cssModules ? composedStylesheets(css) : [];
|
|
124
|
+
const decisions = new Map();
|
|
125
|
+
const imports = [];
|
|
126
|
+
scanCss(css, {
|
|
127
|
+
import: (statement) => {
|
|
128
|
+
imports.push(statement);
|
|
129
|
+
return undefined;
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
for (const [index, { statement, specifier }] of imports.entries()) {
|
|
133
|
+
const imported = this.resolveImport(specifier, file);
|
|
134
|
+
if (!imported) {
|
|
135
|
+
this.hoisted.push(statement);
|
|
136
|
+
decisions.set(index, '');
|
|
137
|
+
}
|
|
138
|
+
else if (this.stack.includes(imported.real)) {
|
|
139
|
+
this.warn(`@import ${JSON.stringify(specifier)} in ${file} names ${imported.real}, which imports ${file}, so it is skipped.`);
|
|
140
|
+
decisions.set(index, '');
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
this.resolutions.set(resolutionKey(real, specifier), imported.real);
|
|
144
|
+
await this.prepare(imported.located);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
let position = 0;
|
|
148
|
+
this.scanned.set(real, scanCss(css, { import: () => decisions.get(position++) }));
|
|
149
|
+
for (const specifier of composed)
|
|
150
|
+
await this.prepareComposed(specifier, file, real);
|
|
151
|
+
this.stack.pop();
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Prepares the stylesheet a `composes: name from 'specifier'` declaration of `file` names, which Lightning CSS reads
|
|
155
|
+
* and scopes with the rest of the bundle.
|
|
156
|
+
*
|
|
157
|
+
* @remarks
|
|
158
|
+
* It resolves as an `@import` does. A stylesheet that cannot be found fails the bundle, since leaving the
|
|
159
|
+
* declaration as written would export a class name that is not defined. One that closes a cycle is skipped, since
|
|
160
|
+
* the stylesheet being walked already defines its classes.
|
|
161
|
+
*/
|
|
162
|
+
async prepareComposed(specifier, file, real) {
|
|
163
|
+
const imported = this.resolveImport(specifier, file);
|
|
164
|
+
if (!imported)
|
|
165
|
+
throw new Error(`${file}: composes from ${JSON.stringify(specifier)} names no stylesheet.`);
|
|
166
|
+
this.resolutions.set(resolutionKey(real, specifier), imported.real);
|
|
167
|
+
if (!this.stack.includes(imported.real))
|
|
168
|
+
await this.prepare(imported.located);
|
|
169
|
+
}
|
|
170
|
+
/** The name Lightning CSS knows `real` by: its scope file for a file of a package, `real` itself otherwise. */
|
|
171
|
+
scopeOf(real) {
|
|
172
|
+
const scope = this.cssModules ? packageScopeFile(real, this.rootDir) : undefined;
|
|
173
|
+
if (!scope)
|
|
174
|
+
return real;
|
|
175
|
+
this.realByScope.set(scope, real);
|
|
176
|
+
return scope;
|
|
177
|
+
}
|
|
178
|
+
/** The real path of a file Lightning CSS names by {@link scopeOf}. */
|
|
179
|
+
realOf(file) {
|
|
180
|
+
const resolved = path.resolve(file);
|
|
181
|
+
return this.realByScope.get(resolved) ?? resolved;
|
|
182
|
+
}
|
|
183
|
+
read(file) {
|
|
184
|
+
const css = this.scanned.get(this.realOf(file));
|
|
185
|
+
if (css === undefined)
|
|
186
|
+
throw new Error(`${file} was not prepared before bundling.`);
|
|
187
|
+
return css;
|
|
188
|
+
}
|
|
189
|
+
resolve(specifier, originatingFile) {
|
|
190
|
+
const resolved = this.resolutions.get(resolutionKey(this.realOf(originatingFile), specifier));
|
|
191
|
+
if (!resolved) {
|
|
192
|
+
throw new Error(`${originatingFile}: @import ${JSON.stringify(specifier)} was not resolved before bundling.`);
|
|
193
|
+
}
|
|
194
|
+
return this.scopeOf(resolved);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Bundles the `@import`s of an app stylesheet with Lightning CSS.
|
|
199
|
+
*
|
|
200
|
+
* @remarks
|
|
201
|
+
* `css` is the in-memory source of `file`, which may differ from the file on disk, and is bundled as given: the caller
|
|
202
|
+
* runs the `transformSource` of the plugins on it, and this function runs them on every partial it reads. A cycle of `@import`s and a
|
|
203
|
+
* stylesheet imported twice are handled by Lightning CSS: the last import of a stylesheet wins, as the specification says.
|
|
204
|
+
* Lightning CSS names the files of a package CSS Module by their scope file (see {@link packageScopeFile}), which
|
|
205
|
+
* is what its class names hash.
|
|
206
|
+
*/
|
|
207
|
+
export async function bundleStylesheet(css, file, rootDir, options) {
|
|
208
|
+
const { bundleAsync, composeVisitors } = await loadLightningCss();
|
|
209
|
+
const entry = path.resolve(file);
|
|
210
|
+
const isCssModule = CSS_MODULE_FILE.test(entry);
|
|
211
|
+
const { cssModulesPattern, plugins, ...lightningOptions } = options;
|
|
212
|
+
const bundle = new StylesheetBundle(entry, css, rootDir, isCssModule, plugins);
|
|
213
|
+
await bundle.prepare();
|
|
214
|
+
const suffixNesting = [];
|
|
215
|
+
const visitors = [
|
|
216
|
+
...plugins.flatMap((plugin) => (plugin.visitor ? [plugin.visitor] : [])),
|
|
217
|
+
suffixNestingVisitor(suffixNesting),
|
|
218
|
+
...(lightningOptions.visitor ? [lightningOptions.visitor] : []),
|
|
219
|
+
];
|
|
220
|
+
const result = await bundleAsync({
|
|
221
|
+
...lightningOptions,
|
|
222
|
+
visitor: visitors.length === 1 ? visitors[0] : composeVisitors(visitors),
|
|
223
|
+
...(isCssModule ? { cssModules: { pattern: cssModulesPattern } } : {}),
|
|
224
|
+
filename: bundle.scopeOf(fileSystem.exists(entry) ? fileSystem.realpath(entry) : entry),
|
|
225
|
+
resolver: {
|
|
226
|
+
read: (source) => bundle.read(source),
|
|
227
|
+
resolve: (specifier, originatingFile) => bundle.resolve(specifier, originatingFile),
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
if (suffixNesting.length > 0) {
|
|
231
|
+
throw suffixNestingError(suffixNesting.map((rule) => ({ ...rule, file: bundle.realOf(rule.file) })));
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
code: result.code,
|
|
235
|
+
hoisted: bundle.hoisted,
|
|
236
|
+
warnings: result.warnings.map((warning) => ({
|
|
237
|
+
...warning,
|
|
238
|
+
loc: { ...warning.loc, filename: bundle.realOf(warning.loc.filename) },
|
|
239
|
+
})),
|
|
240
|
+
dependencies: [...bundle.dependencies].filter((dependency) => dependency !== entry),
|
|
241
|
+
...(result.exports ? { exports: result.exports } : {}),
|
|
242
|
+
};
|
|
243
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './plugin.js';
|
package/src/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './plugin.js';
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import type { CSSModuleExports, Features, TransformOptions, Visitor, Warning } from 'lightningcss';
|
|
2
|
+
/** The names of the Lightning CSS features `include` and `exclude` accept, such as `Nesting` or `ColorFunction`. */
|
|
3
|
+
export type LightningCssFeature = keyof typeof Features;
|
|
4
|
+
/**
|
|
5
|
+
* A plugin of the Lightning CSS Processor: a rewrite of the source before Lightning CSS parses it, a visitor, or both.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Plugins run in the order of the `plugins` option, on every stylesheet the Processor bundles: the entry, each
|
|
9
|
+
* imported partial and every CSS Module. A `preprocessor` that reads partials itself, as the Tailwind v4 preset does for
|
|
10
|
+
* the `@import`s it inlines, runs `transformSource` over them too, so a plugin sees them before the preprocessor does.
|
|
11
|
+
* The visitors are composed with Lightning CSS `composeVisitors`, ahead of the Processor's own check
|
|
12
|
+
* for invalid suffix nesting and the app's `visitor`, so a rule a plugin leaves invalid still fails the stylesheet.
|
|
13
|
+
*/
|
|
14
|
+
export interface LightningCssPlugin {
|
|
15
|
+
/** Names the plugin in errors. */
|
|
16
|
+
name: string;
|
|
17
|
+
/**
|
|
18
|
+
* Rewrites the source of one stylesheet before Lightning CSS parses it, and before the `preprocessor` runs, so the
|
|
19
|
+
* CSS it writes can use what the preprocessor handles, such as Tailwind's `@apply`.
|
|
20
|
+
*
|
|
21
|
+
* @param css - Stylesheet source.
|
|
22
|
+
* @param file - Absolute path of the stylesheet.
|
|
23
|
+
*/
|
|
24
|
+
transformSource?(css: string, file: string): string | Promise<string>;
|
|
25
|
+
/** Visits the rules and values of every stylesheet, as the `visitor` option does. */
|
|
26
|
+
visitor?: Visitor<never>;
|
|
27
|
+
}
|
|
28
|
+
/** The options of the Lightning CSS Processor. */
|
|
29
|
+
export interface LightningCssOptions {
|
|
30
|
+
/**
|
|
31
|
+
* Browserslist queries to lower the CSS for, such as `['chrome >= 90', 'safari >= 15']`. Unset, nothing is lowered.
|
|
32
|
+
*/
|
|
33
|
+
targets?: string | readonly string[];
|
|
34
|
+
/**
|
|
35
|
+
* Whether to minify the CSS.
|
|
36
|
+
* @default true in production, false otherwise
|
|
37
|
+
*/
|
|
38
|
+
minify?: boolean;
|
|
39
|
+
/** Enables the draft syntax Lightning CSS implements ahead of the specifications, such as custom media queries. */
|
|
40
|
+
drafts?: {
|
|
41
|
+
customMedia?: boolean;
|
|
42
|
+
};
|
|
43
|
+
/** Enables non-standard syntax, such as the `>>>` and `/deep/` combinators. */
|
|
44
|
+
nonStandard?: {
|
|
45
|
+
deepSelectorCombinator?: boolean;
|
|
46
|
+
};
|
|
47
|
+
/** Features to compile even when the `targets` support them. */
|
|
48
|
+
include?: readonly LightningCssFeature[];
|
|
49
|
+
/** Features to leave as written even when the `targets` do not support them. */
|
|
50
|
+
exclude?: readonly LightningCssFeature[];
|
|
51
|
+
/** Visits the rules and values of every stylesheet; see the Lightning CSS transforms documentation. */
|
|
52
|
+
visitor?: Visitor<never>;
|
|
53
|
+
/**
|
|
54
|
+
* Whether a rule Lightning CSS cannot parse is dropped with a warning instead of failing the stylesheet.
|
|
55
|
+
* @default false
|
|
56
|
+
*/
|
|
57
|
+
errorRecovery?: boolean;
|
|
58
|
+
/** How `*.module.css` stylesheets are scoped. */
|
|
59
|
+
cssModules?: LightningCssModulesOptions;
|
|
60
|
+
/**
|
|
61
|
+
* Plugins that rewrite the source or visit the rules of every stylesheet, in order, such as `suffixNesting()`.
|
|
62
|
+
* @default []
|
|
63
|
+
*/
|
|
64
|
+
plugins?: readonly LightningCssPlugin[];
|
|
65
|
+
}
|
|
66
|
+
/** The options of the CSS Modules Lightning CSS scopes. */
|
|
67
|
+
export interface LightningCssModulesOptions {
|
|
68
|
+
/**
|
|
69
|
+
* How a scoped class name is built, from `[hash]`, `[local]` and `[name]`, which are the hash of the path
|
|
70
|
+
* relative to the app root, the class name as written and the file name without `.css`, such as `button-module`.
|
|
71
|
+
* @default '[hash]_[local]'
|
|
72
|
+
*/
|
|
73
|
+
pattern?: string;
|
|
74
|
+
}
|
|
75
|
+
/** The scoped class name pattern CSS Modules use unless the options set another. */
|
|
76
|
+
export declare const DEFAULT_CSS_MODULES_PATTERN = "[hash]_[local]";
|
|
77
|
+
/** A failure that already names every file and position it concerns, which {@link toStylesheetError} leaves as it is. */
|
|
78
|
+
export declare class StylesheetDiagnosticsError extends Error {
|
|
79
|
+
name: string;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A selector that writes a name straight after `&`: Sass-style suffix nesting such as `&--primary`, or a type selector
|
|
83
|
+
* such as `&div`, which a browser does not accept either.
|
|
84
|
+
*/
|
|
85
|
+
export type SuffixNestingRule = {
|
|
86
|
+
file: string;
|
|
87
|
+
line: number;
|
|
88
|
+
column: number;
|
|
89
|
+
selector: string;
|
|
90
|
+
kind: 'suffix' | 'type';
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Loads the native Lightning CSS binding on first use.
|
|
94
|
+
*
|
|
95
|
+
* @remarks
|
|
96
|
+
* Config finalization constructs the Processor but must not load a native module, so a build that never reaches a
|
|
97
|
+
* stylesheet, or a tool that only reads the config, never pays for it.
|
|
98
|
+
*/
|
|
99
|
+
export declare function loadLightningCss(): Promise<typeof import('lightningcss')>;
|
|
100
|
+
/** What every Lightning CSS call of a Processor shares, resolved once from its options. */
|
|
101
|
+
export type ResolvedLightningCssOptions = Pick<TransformOptions<never>, 'projectRoot' | 'targets' | 'minify' | 'drafts' | 'nonStandard' | 'include' | 'exclude' | 'visitor' | 'errorRecovery'> & {
|
|
102
|
+
/** The `pattern` of the CSS Modules this Processor scopes. */
|
|
103
|
+
cssModulesPattern: string;
|
|
104
|
+
/** The plugins of this Processor, in order. */
|
|
105
|
+
plugins: readonly LightningCssPlugin[];
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Resolves the options of a Processor for an app rooted at `rootDir`.
|
|
109
|
+
*
|
|
110
|
+
* @remarks
|
|
111
|
+
* Unset options are left out, not passed as `undefined`: the native binding rejects an explicit `undefined`. `projectRoot` makes the hashes Lightning CSS derives from a path relative to the app, so they match across machines and folders; it is the real path of `rootDir`, since Lightning CSS reads the real path of each stylesheet.
|
|
112
|
+
*/
|
|
113
|
+
export declare function resolveLightningCssOptions(options: LightningCssOptions | undefined, rootDir: string): Promise<ResolvedLightningCssOptions>;
|
|
114
|
+
/**
|
|
115
|
+
* Runs the `transformSource` of each plugin over `css`, in order.
|
|
116
|
+
*
|
|
117
|
+
* @remarks
|
|
118
|
+
* A failure that is not a {@link StylesheetDiagnosticsError} is rethrown naming the plugin, so a plugin author's
|
|
119
|
+
* exception does not surface as a bare message.
|
|
120
|
+
*/
|
|
121
|
+
export declare function transformSourceWithPlugins(css: string, file: string, plugins: readonly LightningCssPlugin[]): Promise<string>;
|
|
122
|
+
/** Logs the warnings of the stylesheet `entry`, once per message until its `source` changes, each with its location. */
|
|
123
|
+
export declare function logWarnings(warnings: readonly Warning[], entry: string, source: string): void;
|
|
124
|
+
/**
|
|
125
|
+
* Replaces a failure with an error that names the file and, when it has one, the position, keeping the original as its cause.
|
|
126
|
+
*
|
|
127
|
+
* @remarks
|
|
128
|
+
* Only a Lightning CSS failure has a numeric `loc.line` and `loc.column`; Tailwind's `loc` is a tuple and its message already locates the error.
|
|
129
|
+
*/
|
|
130
|
+
export declare function toStylesheetError(error: unknown, file: string): Error;
|
|
131
|
+
/**
|
|
132
|
+
* The class map core serves for a CSS Module: each local name, sorted, mapped to its scoped name followed by the
|
|
133
|
+
* scoped names it composes, separated by spaces.
|
|
134
|
+
*
|
|
135
|
+
* @remarks
|
|
136
|
+
* A name composed from the global scope stays as written. Sorting keeps the output the same whichever order the
|
|
137
|
+
* rules were written in.
|
|
138
|
+
*/
|
|
139
|
+
export declare function serializeExports(exports: CSSModuleExports): Record<string, string>;
|
|
140
|
+
/**
|
|
141
|
+
* Collects the rules that write Sass-style suffix nesting, such as `.button { &--primary {} }`.
|
|
142
|
+
*
|
|
143
|
+
* @remarks
|
|
144
|
+
* Native CSS nesting cannot concatenate selectors, so `&--primary` is the nesting selector followed by the element
|
|
145
|
+
* `--primary`. Lightning CSS parses it without a warning: it keeps it as written, which a browser drops, or lowers it
|
|
146
|
+
* to `--primary.button`, which matches nothing. Neither reaches the build output as a failure, so the visitor finds
|
|
147
|
+
* the rule at parse time.
|
|
148
|
+
*/
|
|
149
|
+
export declare function suffixNestingVisitor(rules: SuffixNestingRule[]): Visitor<never>;
|
|
150
|
+
/** The error for the rules {@link suffixNestingVisitor} collected, one line per selector with its file, line and column. */
|
|
151
|
+
export declare function suffixNestingError(rules: readonly SuffixNestingRule[]): StylesheetDiagnosticsError;
|