@ecopages/lightningcss-processor 0.0.0-stage → 0.7.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.
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Tailwind CSS v4 preset for the Lightning CSS Processor
3
+ * @module @ecopages/lightningcss-processor/presets/tailwind-v4
4
+ *
5
+ * Install the peers: pnpm add -D @tailwindcss/node @tailwindcss/oxide tailwindcss
6
+ */
7
+ import { rebaseStylesheetReferences, resolvePackageStylesheetPath, resolveProjectImportPath, } from '@ecopages/core/processor';
8
+ import { fileSystem } from '@ecopages/file-system';
9
+ import { path } from '@ecopages/file-system/path';
10
+ import { withReference } from './tailwind-reference.js';
11
+ /** The at-rules that make a stylesheet worth giving to Tailwind. */
12
+ const TAILWIND_AT_RULE = /@(?:import|reference|theme|variant|config|plugin|apply|tailwind)\b/u;
13
+ /**
14
+ * Tailwind's `Features` and `Polyfills` flags the preset reads.
15
+ *
16
+ * @remarks
17
+ * Tailwind declares them as ambient `const enum`s, which `verbatimModuleSyntax` cannot import, so the values are
18
+ * repeated here and a test pins them to the installed Tailwind.
19
+ */
20
+ export const TAILWIND_FLAGS = {
21
+ featuresNone: 0,
22
+ featuresUtilities: 16,
23
+ polyfillsAll: 3,
24
+ polyfillsAtProperty: 1,
25
+ };
26
+ let modules;
27
+ /**
28
+ * Loads Tailwind on first use.
29
+ *
30
+ * @remarks
31
+ * The peers are optional and the oxide scanner is a native module, so config finalization never loads them.
32
+ */
33
+ function loadTailwind() {
34
+ modules ??= Promise.all([import('@tailwindcss/node'), import('@tailwindcss/oxide')])
35
+ .then(([node, oxide]) => ({ node, oxide }))
36
+ .catch((error) => {
37
+ modules = undefined;
38
+ throw new Error('tailwindV4Preset needs its peers: pnpm add -D @tailwindcss/node @tailwindcss/oxide tailwindcss', { cause: error });
39
+ });
40
+ return modules;
41
+ }
42
+ /** The content sources a compiled stylesheet scans: the app root unless it says otherwise, plus its `@source`s. */
43
+ function scanSources(compiler, rootDir) {
44
+ const root = compiler.root === 'none'
45
+ ? []
46
+ : compiler.root === null
47
+ ? [{ base: rootDir, pattern: '**/*', negated: false }]
48
+ : [{ ...compiler.root, negated: false }];
49
+ return [...root, ...compiler.sources];
50
+ }
51
+ /** Whether `candidates` has a class name `known` lacks. */
52
+ function hasNewCandidate(candidates, known) {
53
+ return candidates.some((candidate) => !known.has(candidate));
54
+ }
55
+ /**
56
+ * Rescans the changed files of one stylesheet and tells whether they define a class name its last build lacks.
57
+ *
58
+ * @remarks
59
+ * A changed file the scanner already reads is rescanned alone. A file it has not seen, which matches one of its globs,
60
+ * is a new file, and only a fresh scan knows whether the scanner would read it (it skips ignored and binary files), so
61
+ * the scanner is replaced. A file that is gone or that no glob matches is ignored.
62
+ */
63
+ function rescan(scanner, candidates, changed, Oxide) {
64
+ const present = changed.filter((file) => fileSystem.exists(file));
65
+ const read = new Set(scanner.instance.files.map((file) => path.resolve(file)));
66
+ const unseen = present.filter((file) => !read.has(file) &&
67
+ scanner.instance.globs.some(({ base, pattern }) => path.isWithin(path.resolve(base), file) &&
68
+ path.matchesGlob(path.relative(path.resolve(base), file), pattern)));
69
+ if (unseen.length > 0) {
70
+ scanner.instance = new Oxide({ sources: scanner.sources });
71
+ return hasNewCandidate(scanner.instance.scan(), candidates);
72
+ }
73
+ const known = present.filter((file) => read.has(file));
74
+ if (known.length === 0)
75
+ return false;
76
+ scanner.instance.scanFiles(known.map((file) => ({ file, extension: path.extname(file).slice(1) })));
77
+ return hasNewCandidate(scanner.instance.scan(), candidates);
78
+ }
79
+ /**
80
+ * The stylesheets Tailwind reads in place of partials a plugin rewrites.
81
+ *
82
+ * @remarks
83
+ * Tailwind inlines an `@import` by reading the file itself, so the `transformSource` of a plugin cannot reach it. For
84
+ * each app partial that `transformSource` changes, the rewritten copy is written to a temporary folder of its own,
85
+ * with its `url()` references rebased onto that folder, and the resolver hands Tailwind the copy. A partial no plugin
86
+ * changes is left to Tailwind. The folder is made once per Processor and each partial keeps its own subfolder, so
87
+ * rebuilds overwrite the copies instead of adding files. Imports of a copy resolve from the folder of the partial it stands for.
88
+ */
89
+ class RewrittenPartials {
90
+ folder;
91
+ /** The folder of the copy of each partial. */
92
+ directories = new Map();
93
+ originByDirectory = new Map();
94
+ originByCopy = new Map();
95
+ transformSource;
96
+ constructor(transformSource) {
97
+ this.transformSource = transformSource;
98
+ }
99
+ /** Whether `base` is the folder of a copy. */
100
+ holdsCopy(base) {
101
+ return this.originByDirectory.has(base);
102
+ }
103
+ /** The folder an import is resolved from: the folder of the partial when `base` holds its copy. */
104
+ originOf(base) {
105
+ return this.originByDirectory.get(base) ?? base;
106
+ }
107
+ /** The partial a file Tailwind reported stands for, or the file itself. */
108
+ fileOf(dependency) {
109
+ return this.originByCopy.get(path.resolve(dependency)) ?? dependency;
110
+ }
111
+ /** The copy of `partial` a plugin rewrites, or `undefined` when no plugin changes it. */
112
+ async copyOf(partial) {
113
+ const source = fileSystem.readFileSync(partial);
114
+ const rewritten = await this.transformSource(source, partial);
115
+ if (rewritten === source)
116
+ return undefined;
117
+ let directory = this.directories.get(partial);
118
+ if (!directory) {
119
+ this.folder ??= fileSystem.mkdtemp(path.join(fileSystem.tempDir(), 'ecopages-lightningcss-'));
120
+ directory = path.join(this.folder, String(this.directories.size));
121
+ fileSystem.ensureDir(directory);
122
+ this.directories.set(partial, directory);
123
+ this.originByDirectory.set(directory, path.dirname(partial));
124
+ }
125
+ const copy = path.join(directory, path.basename(partial));
126
+ this.originByCopy.set(copy, partial);
127
+ fileSystem.write(copy, rebaseStylesheetReferences(rewritten, partial, copy));
128
+ return copy;
129
+ }
130
+ }
131
+ /**
132
+ * The file Tailwind reads for an `@import`: an app stylesheet a plugin rewrites, a tsconfig alias, or `undefined` to
133
+ * leave it to Tailwind's resolver.
134
+ */
135
+ async function resolveImport(id, base, rootDir, rewritten) {
136
+ const origin = rewritten?.originOf(base) ?? base;
137
+ const local = id.startsWith('.') ? path.resolve(origin, id) : undefined;
138
+ const aliased = local ? undefined : resolveProjectImportPath(rootDir, path.join(origin, 'index.css'), id);
139
+ const existing = [local, aliased].find((file) => file && fileSystem.exists(file));
140
+ if (existing)
141
+ return resolveExisting(existing, existing === aliased, base, rewritten);
142
+ if (local || !rewritten?.holdsCopy(base))
143
+ return undefined;
144
+ try {
145
+ return resolvePackageStylesheetPath(path.join(origin, 'index.css'), id);
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ }
151
+ /** The file Tailwind reads for an app stylesheet that exists: the copy a plugin rewrote, or the file when it must be named. */
152
+ async function resolveExisting(file, aliased, base, rewritten) {
153
+ const copy = file.endsWith('.css') ? await rewritten?.copyOf(file) : undefined;
154
+ if (copy)
155
+ return copy;
156
+ return aliased || rewritten?.holdsCopy(base) ? file : undefined;
157
+ }
158
+ /**
159
+ * Runs Tailwind v4 over each stylesheet before Lightning CSS, without PostCSS.
160
+ *
161
+ * @remarks
162
+ * Each stylesheet is compiled once and built for the class names oxide scans in the app. Scanning is per stylesheet,
163
+ * since each can declare its own `@source`s, and the scanner is kept so a change to a template rescans only that file.
164
+ */
165
+ function createTailwindPreprocessor(options) {
166
+ const referencePath = path.resolve(options.referencePath);
167
+ const stylesheets = new Map();
168
+ let partials;
169
+ return {
170
+ async transform(css, file, context) {
171
+ const entry = path.resolve(file);
172
+ const source = withReference(css, entry, referencePath);
173
+ if (!TAILWIND_AT_RULE.test(source)) {
174
+ stylesheets.delete(entry);
175
+ return { css };
176
+ }
177
+ const { node, oxide } = await loadTailwind();
178
+ const state = stylesheets.get(entry) ?? { candidates: new Set(), dependencies: new Set() };
179
+ stylesheets.set(entry, state);
180
+ const dependencies = new Set();
181
+ const rewritten = context.transformSource
182
+ ? (partials ??= new RewrittenPartials(context.transformSource))
183
+ : undefined;
184
+ try {
185
+ const compiler = await node.compile(source, {
186
+ base: path.dirname(entry),
187
+ from: entry,
188
+ shouldRewriteUrls: true,
189
+ polyfills: entry.endsWith('.module.css')
190
+ ? TAILWIND_FLAGS.polyfillsAll ^ TAILWIND_FLAGS.polyfillsAtProperty
191
+ : TAILWIND_FLAGS.polyfillsAll,
192
+ onDependency: (dependency) => dependencies.add(path.resolve(rewritten?.fileOf(dependency) ?? dependency)),
193
+ customCssResolver: (id, base) => resolveImport(id, base, context.rootDir, rewritten),
194
+ });
195
+ state.dependencies = dependencies;
196
+ if (compiler.features === TAILWIND_FLAGS.featuresNone) {
197
+ stylesheets.delete(entry);
198
+ return { css, dependencies: [...dependencies] };
199
+ }
200
+ let candidates = [];
201
+ if (compiler.features & TAILWIND_FLAGS.featuresUtilities) {
202
+ const sources = scanSources(compiler, context.rootDir);
203
+ if (JSON.stringify(state.scanner?.sources) !== JSON.stringify(sources)) {
204
+ state.scanner = { instance: new oxide.Scanner({ sources }), sources };
205
+ }
206
+ candidates = state.scanner.instance.scan();
207
+ }
208
+ else {
209
+ state.scanner = undefined;
210
+ }
211
+ const built = compiler.build(candidates);
212
+ state.candidates = new Set(candidates);
213
+ return { css: built, dependencies: [...dependencies] };
214
+ }
215
+ catch (error) {
216
+ state.dependencies = new Set([...state.dependencies, ...dependencies]);
217
+ throw error;
218
+ }
219
+ },
220
+ async invalidate(files) {
221
+ const changed = files.map((file) => path.resolve(file));
222
+ const { oxide } = await loadTailwind();
223
+ const stale = [];
224
+ for (const [entry, state] of stylesheets) {
225
+ if (changed.some((file) => state.dependencies.has(file) && !file.endsWith('.css'))) {
226
+ stale.push(entry);
227
+ }
228
+ else if (state.scanner && rescan(state.scanner, state.candidates, changed, oxide.Scanner)) {
229
+ stale.push(entry);
230
+ }
231
+ }
232
+ return stale;
233
+ },
234
+ };
235
+ }
236
+ /**
237
+ * Creates a Lightning CSS Processor config preset for Tailwind CSS v4.
238
+ *
239
+ * Tailwind runs inside the Processor, so the app needs no PostCSS. Each stylesheet goes through Tailwind, then through
240
+ * the Processor's own Lightning CSS steps: bundling, `targets`, minifying and CSS Modules. Stylesheets that use
241
+ * `@apply`, and CSS Modules, get an `@reference` to `referencePath` so the app's theme applies.
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
246
+ * import { tailwindV4Preset } from '@ecopages/lightningcss-processor/presets/tailwind-v4';
247
+ *
248
+ * lightningCssProcessorPlugin({
249
+ * ...tailwindV4Preset({ referencePath: path.resolve(import.meta.dirname, 'src/styles/tailwind.css') }),
250
+ * targets: ['chrome >= 111'],
251
+ * })
252
+ * ```
253
+ */
254
+ export function tailwindV4Preset(options) {
255
+ return { preprocessor: createTailwindPreprocessor(options) };
256
+ }