@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.
@@ -0,0 +1,191 @@
1
+ import { isProductionRuntime, warnStylesheetOnce } from '@ecopages/core/processor';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { Logger } from '@ecopages/logger';
4
+ import browserslist from 'browserslist';
5
+ const logger = new Logger('[@ecopages/lightningcss-processor]');
6
+ /** The scoped class name pattern CSS Modules use unless the options set another. */
7
+ export const DEFAULT_CSS_MODULES_PATTERN = '[hash]_[local]';
8
+ /** A failure that already names every file and position it concerns, which {@link toStylesheetError} leaves as it is. */
9
+ export class StylesheetDiagnosticsError extends Error {
10
+ name = 'StylesheetDiagnosticsError';
11
+ }
12
+ let engine;
13
+ /**
14
+ * Loads the native Lightning CSS binding on first use.
15
+ *
16
+ * @remarks
17
+ * Config finalization constructs the Processor but must not load a native module, so a build that never reaches a
18
+ * stylesheet, or a tool that only reads the config, never pays for it.
19
+ */
20
+ export function loadLightningCss() {
21
+ engine ??= import('lightningcss').catch((error) => {
22
+ engine = undefined;
23
+ throw error;
24
+ });
25
+ return engine;
26
+ }
27
+ /** The Lightning CSS `targets` for browserslist `queries`, or `undefined` to lower nothing. */
28
+ async function resolveTargets(queries) {
29
+ if (!queries || queries.length === 0)
30
+ return undefined;
31
+ const { browserslistToTargets } = await loadLightningCss();
32
+ return browserslistToTargets(browserslist(typeof queries === 'string' ? queries : [...queries]));
33
+ }
34
+ /** Combines feature names into the bit flags Lightning CSS takes. */
35
+ async function toFeatureFlags(names) {
36
+ if (!names || names.length === 0)
37
+ return undefined;
38
+ const { Features } = await loadLightningCss();
39
+ return names.reduce((flags, name) => flags | Features[name], 0);
40
+ }
41
+ /** `values` without the keys set to `undefined`. */
42
+ function withoutUndefined(values) {
43
+ return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined));
44
+ }
45
+ /** The options a Processor resolves to a value when they are unset. */
46
+ function resolvedDefaults(options) {
47
+ return {
48
+ cssModulesPattern: options?.cssModules?.pattern ?? DEFAULT_CSS_MODULES_PATTERN,
49
+ plugins: options?.plugins ?? [],
50
+ };
51
+ }
52
+ /**
53
+ * Resolves the options of a Processor for an app rooted at `rootDir`.
54
+ *
55
+ * @remarks
56
+ * 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.
57
+ */
58
+ export async function resolveLightningCssOptions(options, rootDir) {
59
+ return {
60
+ projectRoot: fileSystem.exists(rootDir) ? fileSystem.realpath(rootDir) : rootDir,
61
+ ...resolvedDefaults(options),
62
+ minify: options?.minify ?? isProductionRuntime(),
63
+ ...withoutUndefined({
64
+ drafts: options?.drafts,
65
+ nonStandard: options?.nonStandard,
66
+ visitor: options?.visitor,
67
+ errorRecovery: options?.errorRecovery,
68
+ targets: await resolveTargets(options?.targets),
69
+ include: await toFeatureFlags(options?.include),
70
+ exclude: await toFeatureFlags(options?.exclude),
71
+ }),
72
+ };
73
+ }
74
+ /**
75
+ * Runs the `transformSource` of each plugin over `css`, in order.
76
+ *
77
+ * @remarks
78
+ * A failure that is not a {@link StylesheetDiagnosticsError} is rethrown naming the plugin, so a plugin author's
79
+ * exception does not surface as a bare message.
80
+ */
81
+ export async function transformSourceWithPlugins(css, file, plugins) {
82
+ let transformed = css;
83
+ for (const plugin of plugins) {
84
+ if (!plugin.transformSource)
85
+ continue;
86
+ try {
87
+ transformed = await plugin.transformSource(transformed, file);
88
+ }
89
+ catch (error) {
90
+ if (error instanceof StylesheetDiagnosticsError)
91
+ throw error;
92
+ throw new Error(`plugin ${plugin.name}: ${error instanceof Error ? error.message : String(error)}`, {
93
+ cause: error,
94
+ });
95
+ }
96
+ }
97
+ return transformed;
98
+ }
99
+ /** Logs the warnings of the stylesheet `entry`, once per message until its `source` changes, each with its location. */
100
+ export function logWarnings(warnings, entry, source) {
101
+ for (const { message, loc } of warnings) {
102
+ warnStylesheetOnce(entry, source, `${loc.filename || entry}:${loc.line}:${loc.column} ${message}`, (text) => logger.warn(text));
103
+ }
104
+ }
105
+ /**
106
+ * Replaces a failure with an error that names the file and, when it has one, the position, keeping the original as its cause.
107
+ *
108
+ * @remarks
109
+ * 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.
110
+ */
111
+ export function toStylesheetError(error, file) {
112
+ if (error instanceof StylesheetDiagnosticsError)
113
+ return error;
114
+ if (!(error instanceof Error))
115
+ return new Error(`${file}: ${String(error)}`);
116
+ const { fileName = file, loc, message } = error;
117
+ return new Error(`${fileName}${typeof loc?.line === 'number' && typeof loc.column === 'number' ? `:${loc.line}:${loc.column}` : ''} ${message}`, { cause: error });
118
+ }
119
+ /**
120
+ * The class map core serves for a CSS Module: each local name, sorted, mapped to its scoped name followed by the
121
+ * scoped names it composes, separated by spaces.
122
+ *
123
+ * @remarks
124
+ * A name composed from the global scope stays as written. Sorting keeps the output the same whichever order the
125
+ * rules were written in.
126
+ */
127
+ export function serializeExports(exports) {
128
+ return Object.fromEntries(Object.keys(exports)
129
+ .sort()
130
+ .map((local) => {
131
+ const { name, composes } = exports[local];
132
+ return [local, [name, ...composes.map((composed) => composed.name)].join(' ')];
133
+ }));
134
+ }
135
+ /** Every `&` and the name a selector writes straight after it, such as `&--primary`; empty for valid nesting. */
136
+ function suffixNestingOf(selector) {
137
+ const found = [];
138
+ for (let index = 0; index < selector.length; index++) {
139
+ const component = selector[index];
140
+ const next = selector[index + 1];
141
+ if (component.type === 'nesting' && next?.type === 'type') {
142
+ found.push({ selector: `&${next.name}`, kind: /^[-_]/u.test(next.name) ? 'suffix' : 'type' });
143
+ }
144
+ if (component.type === 'pseudo-class' && 'selectors' in component && component.selectors) {
145
+ for (const inner of component.selectors) {
146
+ if (Array.isArray(inner))
147
+ found.push(...suffixNestingOf(inner));
148
+ }
149
+ }
150
+ }
151
+ return found;
152
+ }
153
+ /**
154
+ * Collects the rules that write Sass-style suffix nesting, such as `.button { &--primary {} }`.
155
+ *
156
+ * @remarks
157
+ * Native CSS nesting cannot concatenate selectors, so `&--primary` is the nesting selector followed by the element
158
+ * `--primary`. Lightning CSS parses it without a warning: it keeps it as written, which a browser drops, or lowers it
159
+ * to `--primary.button`, which matches nothing. Neither reaches the build output as a failure, so the visitor finds
160
+ * the rule at parse time.
161
+ */
162
+ export function suffixNestingVisitor(rules) {
163
+ let sources = [];
164
+ return {
165
+ StyleSheet(stylesheet) {
166
+ sources = stylesheet.sources;
167
+ },
168
+ Rule: {
169
+ style(rule) {
170
+ const { loc, selectors } = rule.value;
171
+ for (const selector of selectors) {
172
+ for (const found of suffixNestingOf(selector)) {
173
+ rules.push({
174
+ file: sources[loc.source_index] ?? '',
175
+ line: loc.line + 1,
176
+ column: loc.column,
177
+ ...found,
178
+ });
179
+ }
180
+ }
181
+ },
182
+ },
183
+ };
184
+ }
185
+ /** The error for the rules {@link suffixNestingVisitor} collected, one line per selector with its file, line and column. */
186
+ export function suffixNestingError(rules) {
187
+ const lines = rules.map(({ file, line, column, selector, kind }) => kind === 'type'
188
+ ? `${file}:${line}:${column} \`${selector}\` puts a type selector after \`&\`, which is not valid CSS; a type selector can only start a compound selector, so write \`${selector.slice(1)}&\`.`
189
+ : `${file}:${line}:${column} \`${selector}\` is Sass-style suffix nesting; native CSS nesting cannot concatenate selectors, so write the full selector explicitly, such as \`.button${selector.slice(1)}\` for \`.button { ${selector} {} }\`, or add the suffixNesting() plugin from @ecopages/lightningcss-processor/plugins/suffix-nesting.`);
190
+ return new StylesheetDiagnosticsError(lines.join('\n'));
191
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * LightningCssProcessorPlugin
3
+ * @module @ecopages/lightningcss-processor
4
+ */
5
+ import { Processor, type ProcessorConfig, type StylesheetInvalidation, type StylesheetTransformResult } from '@ecopages/core/processor';
6
+ import { type LightningCssOptions } from './lightningcss-engine.js';
7
+ import type { LightningCssPreprocessor } from './preprocessor.js';
8
+ export type { LightningCssPreprocessor, LightningCssPreprocessorContext, PreprocessedStylesheet, } from './preprocessor.js';
9
+ export type { LightningCssFeature, LightningCssModulesOptions, LightningCssOptions, LightningCssPlugin, } from './lightningcss-engine.js';
10
+ /** Configuration for the Lightning CSS Processor. */
11
+ export interface LightningCssProcessorPluginConfig extends LightningCssOptions {
12
+ /**
13
+ * Regex filter to match the stylesheets to process.
14
+ * @default /\.css$/
15
+ */
16
+ filter?: RegExp;
17
+ /**
18
+ * A stage that runs on every stylesheet before Lightning CSS, such as the Tailwind v4 preset.
19
+ *
20
+ * @remarks
21
+ * Presets set it; most apps never write one.
22
+ */
23
+ preprocessor?: LightningCssPreprocessor;
24
+ }
25
+ /**
26
+ * A stylesheet Processor that runs Lightning CSS: it lowers the CSS for the browsers in `targets` and minifies it.
27
+ *
28
+ * @remarks
29
+ * An app has one stylesheet Processor, so this one replaces the PostCSS Processor instead of running after it. The
30
+ * native binding loads on the first stylesheet, never while the config is finalized. A stylesheet Lightning CSS
31
+ * rejects throws an error naming the file and the position, so a build fails and development keeps the last good
32
+ * output until a save fixes it.
33
+ */
34
+ export declare class LightningCssProcessorPlugin extends Processor<LightningCssProcessorPluginConfig> {
35
+ static DEFAULT_OPTIONS: Required<Pick<LightningCssProcessorPluginConfig, 'filter'>>;
36
+ private resolvedOptions?;
37
+ constructor(config?: Omit<ProcessorConfig<LightningCssProcessorPluginConfig>, 'name'>);
38
+ /**
39
+ * @remarks
40
+ * Core's development stylesheet service prewarms and rebuilds the app's stylesheets, and the native binding loads
41
+ * on the first transform.
42
+ */
43
+ setup(): Promise<void>;
44
+ /**
45
+ * Names the stylesheets the preprocessor rebuilds for the changed files that are not stylesheets.
46
+ *
47
+ * @remarks
48
+ * Without a preprocessor nothing but a stylesheet's own `@import`s changes its output, and core rebuilds those from
49
+ * the transform's `dependencies`.
50
+ */
51
+ invalidateStylesheets(files: readonly string[]): StylesheetInvalidation | Promise<StylesheetInvalidation>;
52
+ transformStylesheet(css: string, file: string): Promise<StylesheetTransformResult>;
53
+ }
54
+ export declare const lightningCssProcessorPlugin: (config?: LightningCssProcessorPluginConfig) => LightningCssProcessorPlugin;
package/src/plugin.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * LightningCssProcessorPlugin
3
+ * @module @ecopages/lightningcss-processor
4
+ */
5
+ import { Processor, } from '@ecopages/core/processor';
6
+ import { bundleStylesheet, packageScopeFile } from './bundle-stylesheet.js';
7
+ import { logWarnings, resolveLightningCssOptions, serializeExports, toStylesheetError, transformSourceWithPlugins, } from './lightningcss-engine.js';
8
+ /**
9
+ * A stylesheet Processor that runs Lightning CSS: it lowers the CSS for the browsers in `targets` and minifies it.
10
+ *
11
+ * @remarks
12
+ * An app has one stylesheet Processor, so this one replaces the PostCSS Processor instead of running after it. The
13
+ * native binding loads on the first stylesheet, never while the config is finalized. A stylesheet Lightning CSS
14
+ * rejects throws an error naming the file and the position, so a build fails and development keeps the last good
15
+ * output until a save fixes it.
16
+ */
17
+ export class LightningCssProcessorPlugin extends Processor {
18
+ static DEFAULT_OPTIONS = {
19
+ filter: /\.css$/,
20
+ };
21
+ resolvedOptions;
22
+ constructor(config = {
23
+ options: LightningCssProcessorPlugin.DEFAULT_OPTIONS,
24
+ }) {
25
+ const filter = config.options?.filter ?? LightningCssProcessorPlugin.DEFAULT_OPTIONS.filter;
26
+ super({
27
+ name: 'ecopages-lightningcss-processor',
28
+ ...config,
29
+ capabilities: [
30
+ ...(config.capabilities ?? []).filter((capability) => capability.kind !== 'stylesheet'),
31
+ {
32
+ kind: 'stylesheet',
33
+ extensions: ['*.css'],
34
+ filter,
35
+ cssModules: true,
36
+ },
37
+ ],
38
+ });
39
+ }
40
+ /**
41
+ * @remarks
42
+ * Core's development stylesheet service prewarms and rebuilds the app's stylesheets, and the native binding loads
43
+ * on the first transform.
44
+ */
45
+ async setup() { }
46
+ /**
47
+ * Names the stylesheets the preprocessor rebuilds for the changed files that are not stylesheets.
48
+ *
49
+ * @remarks
50
+ * Without a preprocessor nothing but a stylesheet's own `@import`s changes its output, and core rebuilds those from
51
+ * the transform's `dependencies`.
52
+ */
53
+ invalidateStylesheets(files) {
54
+ return this.options?.preprocessor?.invalidate?.(files) ?? [];
55
+ }
56
+ async transformStylesheet(css, file) {
57
+ if (!this.context) {
58
+ throw new Error('Context must be set');
59
+ }
60
+ this.resolvedOptions ??= resolveLightningCssOptions(this.options, this.context.rootDir).catch((error) => {
61
+ this.resolvedOptions = undefined;
62
+ throw error;
63
+ });
64
+ try {
65
+ const options = await this.resolvedOptions;
66
+ const hasSourcePlugin = options.plugins.some((plugin) => plugin.transformSource);
67
+ const source = await transformSourceWithPlugins(css, file, options.plugins);
68
+ const preprocessed = packageScopeFile(file, this.context.rootDir)
69
+ ? undefined
70
+ : await this.options?.preprocessor?.transform(source, file, {
71
+ rootDir: this.context.rootDir,
72
+ ...(hasSourcePlugin
73
+ ? {
74
+ transformSource: (text, name) => transformSourceWithPlugins(text, name, options.plugins),
75
+ }
76
+ : {}),
77
+ });
78
+ const bundled = await bundleStylesheet(preprocessed?.css ?? source, file, this.context.rootDir, options);
79
+ logWarnings(bundled.warnings, file, css);
80
+ const bundledCss = Buffer.from(bundled.code).toString();
81
+ return {
82
+ css: bundled.hoisted.length > 0 ? `${bundled.hoisted.join('\n')}\n${bundledCss}` : bundledCss,
83
+ dependencies: [...new Set([...(preprocessed?.dependencies ?? []), ...bundled.dependencies])],
84
+ ...(bundled.exports ? { exports: serializeExports(bundled.exports) } : {}),
85
+ };
86
+ }
87
+ catch (error) {
88
+ throw toStylesheetError(error, file);
89
+ }
90
+ }
91
+ }
92
+ export const lightningCssProcessorPlugin = (config) => {
93
+ return new LightningCssProcessorPlugin({
94
+ options: config,
95
+ });
96
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Opt-in Sass-style suffix nesting for the Lightning CSS Processor
3
+ * @module @ecopages/lightningcss-processor/plugins/suffix-nesting
4
+ */
5
+ import type { LightningCssPlugin } from '../lightningcss-engine.js';
6
+ /**
7
+ * Rewrites Sass-style suffix nesting into native nesting before Lightning CSS parses the stylesheet.
8
+ *
9
+ * @param css - Stylesheet source.
10
+ * @param file - Name of the stylesheet, which the errors carry.
11
+ * @throws StylesheetDiagnosticsError listing every rule that cannot be expanded, with file, line and column.
12
+ */
13
+ export declare function expandSuffixNesting(css: string, file: string): string;
14
+ /**
15
+ * A plugin for the Lightning CSS Processor that supports Sass-style suffix nesting: `&--x`, `&__x` and `&-x`.
16
+ *
17
+ * @remarks
18
+ * Native CSS nesting cannot concatenate selectors, so Lightning CSS fails a stylesheet that writes `&--primary`. This
19
+ * plugin rewrites each such rule before Lightning CSS parses the stylesheet, into a rule written out with the parent
20
+ * selectors, next to the rule it came from: `.button, a.button { &--primary { ... } }` becomes
21
+ * `.button--primary, a.button--primary { ... }` after `.button, a.button`. Nested rules and pseudo-classes inside it keep
22
+ * working. A parent that is not one compound selector per entry, such as `.card .title`, fails with the file, line and
23
+ * column, instead of a guess.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
28
+ * import { suffixNesting } from '@ecopages/lightningcss-processor/plugins/suffix-nesting';
29
+ *
30
+ * lightningCssProcessorPlugin({ plugins: [suffixNesting()] });
31
+ * ```
32
+ */
33
+ export declare function suffixNesting(): LightningCssPlugin;