@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,474 @@
1
+ /**
2
+ * Opt-in Sass-style suffix nesting for the Lightning CSS Processor
3
+ * @module @ecopages/lightningcss-processor/plugins/suffix-nesting
4
+ */
5
+ import { tokenizeCss } from '@ecopages/core/processor';
6
+ import { StylesheetDiagnosticsError } from '../lightningcss-engine.js';
7
+ /** The at-rules whose bodies hold rules, so a rule inside them is expanded and a rule nested in a rule keeps working. */
8
+ const CONDITIONAL_AT_RULES = new Set(['media', 'supports', 'container', 'layer', 'document']);
9
+ /** The pseudo-classes whose selector list is one a suffix can be written in. */
10
+ const SELECTOR_LIST_PSEUDOS = new Set(['is', 'where', 'not']);
11
+ const isOpening = (char) => char === '(' || char === '[';
12
+ const isClosing = (char) => char === ')' || char === ']';
13
+ const depthAfter = (depth, char) => isOpening(char) ? depth + 1 : isClosing(char) ? Math.max(0, depth - 1) : depth;
14
+ /** The characters that end an item of a block or open and close a block. */
15
+ const STRUCTURAL = new Set(['{', ';', '}']);
16
+ /** The offset of the first token from the token `from` that is not whitespace or a comment, or `end`. */
17
+ function skipTrivia(tokens, from, end) {
18
+ for (let index = from; index < tokens.length && tokens[index].start < end; index++) {
19
+ const type = tokens[index].type;
20
+ if (type !== 'space' && type !== 'comment')
21
+ return tokens[index].start;
22
+ }
23
+ return end;
24
+ }
25
+ /** Reads a stylesheet as nested blocks. */
26
+ class BlockParser {
27
+ position = 0;
28
+ css;
29
+ tokens;
30
+ constructor(css, tokens) {
31
+ this.css = css;
32
+ this.tokens = tokens;
33
+ }
34
+ /** The top-level nodes, or `undefined` when the braces do not balance, which Lightning CSS reports. */
35
+ parse() {
36
+ return this.body(false);
37
+ }
38
+ body(nested) {
39
+ const nodes = [];
40
+ const item = { start: this.tokens[this.position]?.start ?? this.css.length, first: this.position };
41
+ let parentheses = 0;
42
+ while (this.position < this.tokens.length) {
43
+ const token = this.tokens[this.position];
44
+ const char = token.type === 'punct' ? this.css[token.start] : '';
45
+ const structural = parentheses === 0 && STRUCTURAL.has(char);
46
+ parentheses = depthAfter(parentheses, char);
47
+ if (structural) {
48
+ const step = this.structural(char, token, nodes, item, nested);
49
+ if (step === 'fail')
50
+ return undefined;
51
+ if (step === 'close')
52
+ return nodes;
53
+ if (step === 'continue')
54
+ continue;
55
+ }
56
+ this.position += 1;
57
+ }
58
+ if (nested)
59
+ return undefined;
60
+ if (item.start < this.css.length)
61
+ nodes.push({ kind: 'text', start: item.start, end: this.css.length });
62
+ return nodes;
63
+ }
64
+ structural(char, token, nodes, item, nested) {
65
+ if (char === ';') {
66
+ nodes.push({ kind: 'text', start: item.start, end: token.end });
67
+ item.start = token.end;
68
+ item.first = this.position + 1;
69
+ return 'advance';
70
+ }
71
+ if (char === '}') {
72
+ if (!nested)
73
+ return 'fail';
74
+ if (item.start < token.start)
75
+ nodes.push({ kind: 'text', start: item.start, end: token.start });
76
+ this.position += 1;
77
+ return 'close';
78
+ }
79
+ if (/^--[^\s:]*\s*:/u.test(this.css.slice(item.start, token.start).trimStart())) {
80
+ return this.skipBraces() ? 'advance' : 'fail';
81
+ }
82
+ const preludeStart = skipTrivia(this.tokens, item.first, token.start);
83
+ this.position += 1;
84
+ const children = this.body(true);
85
+ if (!children)
86
+ return 'fail';
87
+ const end = this.tokens[this.position - 1].end;
88
+ nodes.push({
89
+ kind: 'block',
90
+ start: item.start,
91
+ preludeStart,
92
+ preludeEnd: token.start,
93
+ bodyStart: token.end,
94
+ end,
95
+ children,
96
+ });
97
+ item.start = end;
98
+ item.first = this.position;
99
+ return 'continue';
100
+ }
101
+ /** Moves to the `}` that closes the `{` at the current position, which a custom property value holds as text. */
102
+ skipBraces() {
103
+ let depth = 0;
104
+ for (; this.position < this.tokens.length; this.position++) {
105
+ const token = this.tokens[this.position];
106
+ if (token.type !== 'punct')
107
+ continue;
108
+ if (this.css[token.start] === '{')
109
+ depth += 1;
110
+ if (this.css[token.start] === '}' && --depth === 0)
111
+ return true;
112
+ }
113
+ return false;
114
+ }
115
+ }
116
+ /** The selectors of a selector list: split at the commas outside parentheses, brackets, strings and comments. */
117
+ function splitSelectorList(list) {
118
+ const entries = [];
119
+ let current = '';
120
+ let depth = 0;
121
+ for (const token of tokenizeCss(list)) {
122
+ const text = list.slice(token.start, token.end);
123
+ if (token.type === 'comment')
124
+ continue;
125
+ if (token.type === 'punct') {
126
+ if (isOpening(text))
127
+ depth += 1;
128
+ else if (isClosing(text))
129
+ depth = Math.max(0, depth - 1);
130
+ else if (text === ',' && depth === 0) {
131
+ entries.push(current.trim());
132
+ current = '';
133
+ continue;
134
+ }
135
+ }
136
+ current += text;
137
+ }
138
+ entries.push(current.trim());
139
+ return entries;
140
+ }
141
+ /** Whether the `(` at `index` opens the selector list of `:is()`, `:where()` or `:not()`. */
142
+ function opensSelectorList(entry, tokens, index) {
143
+ const name = tokens[index - 1];
144
+ return (entry[tokens[index].start] === '(' &&
145
+ name?.type === 'word' &&
146
+ entry[name.start - 1] === ':' &&
147
+ SELECTOR_LIST_PSEUDOS.has(entry.slice(name.start, name.end).toLowerCase()));
148
+ }
149
+ /** The index of the last token of the suffix the `&` at `index` spells, or `undefined` when it spells none. */
150
+ function suffixEnd(entry, tokens, index) {
151
+ const first = tokens[index + 1];
152
+ if (first?.type !== 'word' || !/^[-_]/u.test(entry.slice(first.start, first.end)))
153
+ return undefined;
154
+ let last = index + 1;
155
+ while (tokens[last + 1] && (tokens[last + 1].type === 'word' || tokens[last + 1].type === 'escape'))
156
+ last += 1;
157
+ return last;
158
+ }
159
+ /**
160
+ * The suffixes `entry` spells with a `&`, at the start of a compound selector or inside `:is()`, `:where()` and `:not()`.
161
+ *
162
+ * @remarks
163
+ * A `&` followed by a name that does not start with `-` or `_`, such as `&div`, is not a suffix.
164
+ */
165
+ function suffixOccurrences(entry) {
166
+ const tokens = tokenizeCss(entry);
167
+ const found = [];
168
+ const listed = [];
169
+ for (let index = 0; index < tokens.length; index++) {
170
+ const token = tokens[index];
171
+ const char = token.type === 'punct' ? entry[token.start] : '';
172
+ if (isOpening(char))
173
+ listed.push(opensSelectorList(entry, tokens, index));
174
+ else if (isClosing(char))
175
+ listed.pop();
176
+ else if (char === '&' && listed.every(Boolean)) {
177
+ const last = suffixEnd(entry, tokens, index);
178
+ if (last === undefined)
179
+ continue;
180
+ found.push({
181
+ start: token.start,
182
+ end: tokens[last].end,
183
+ suffix: entry.slice(token.end, tokens[last].end),
184
+ });
185
+ index = last;
186
+ }
187
+ }
188
+ return found;
189
+ }
190
+ /** Whether `entry` still has a `&` that is not part of a suffix, or sits where a suffix cannot be expanded. */
191
+ function hasPlainNesting(entry, occurrences) {
192
+ const starts = new Set(occurrences.map((occurrence) => occurrence.start));
193
+ return tokenizeCss(entry).some((token) => token.type === 'punct' && entry[token.start] === '&' && !starts.has(token.start));
194
+ }
195
+ /** Whether `entry` is one compound selector: no combinator and no whitespace outside parentheses and brackets. */
196
+ function isCompound(entry) {
197
+ let depth = 0;
198
+ for (const token of tokenizeCss(entry)) {
199
+ const text = entry.slice(token.start, token.end);
200
+ if (token.type === 'punct' && isOpening(text))
201
+ depth += 1;
202
+ else if (token.type === 'punct' && isClosing(text))
203
+ depth = Math.max(0, depth - 1);
204
+ else if (depth === 0 && (token.type === 'space' || (token.type === 'punct' && '>+~'.includes(text))))
205
+ return false;
206
+ }
207
+ return true;
208
+ }
209
+ /** Whether a name can be appended to `compound`: its last simple selector is a class, an id, a type or `&`. */
210
+ function acceptsSuffix(compound) {
211
+ let last;
212
+ let depth = 0;
213
+ let first = true;
214
+ for (const token of tokenizeCss(compound)) {
215
+ const text = compound.slice(token.start, token.end);
216
+ if (token.type === 'punct' && isOpening(text)) {
217
+ if (depth === 0 && text === '[')
218
+ last = 'other';
219
+ depth += 1;
220
+ }
221
+ else if (token.type === 'punct' && isClosing(text)) {
222
+ depth = Math.max(0, depth - 1);
223
+ }
224
+ else if (depth === 0) {
225
+ if (token.type === 'punct')
226
+ last = text === '.' || text === '#' || text === '&' ? 'name' : 'other';
227
+ else if (first)
228
+ last = 'name';
229
+ }
230
+ first = false;
231
+ }
232
+ return last === 'name';
233
+ }
234
+ /**
235
+ * Rewrites Sass-style suffix nesting into native nesting.
236
+ *
237
+ * @remarks
238
+ * Every failure is collected and thrown together, so one build names every offending rule.
239
+ */
240
+ class SuffixExpander {
241
+ tokens;
242
+ lineStarts = [0];
243
+ errors = [];
244
+ css;
245
+ file;
246
+ constructor(css, file) {
247
+ this.css = css;
248
+ this.file = file;
249
+ this.tokens = tokenizeCss(css);
250
+ for (let index = 0; index < css.length; index++)
251
+ if (css[index] === '\n')
252
+ this.lineStarts.push(index + 1);
253
+ }
254
+ expand() {
255
+ const nodes = new BlockParser(this.css, this.tokens).parse();
256
+ return nodes ? this.renderNodes(nodes, false) : this.css;
257
+ }
258
+ locate(offset) {
259
+ let line = this.lineStarts.length - 1;
260
+ while (this.lineStarts[line] > offset)
261
+ line -= 1;
262
+ return `${this.file}:${line + 1}:${offset - this.lineStarts[line] + 1}`;
263
+ }
264
+ fail(offset, message) {
265
+ this.errors.push(`${this.locate(offset)} ${message}`);
266
+ }
267
+ text(node) {
268
+ return node.kind === 'text' ? this.css.slice(node.start, node.end) : this.raw(node);
269
+ }
270
+ /** A block exactly as written. */
271
+ raw(node) {
272
+ return this.css.slice(node.start, node.end);
273
+ }
274
+ atRuleName(node) {
275
+ return /^@([\w-]+)/u.exec(this.css.slice(node.preludeStart, node.preludeEnd))?.[1]?.toLowerCase();
276
+ }
277
+ isAtRule(node) {
278
+ return this.css[node.preludeStart] === '@';
279
+ }
280
+ isConditional(node) {
281
+ return CONDITIONAL_AT_RULES.has(this.atRuleName(node) ?? '');
282
+ }
283
+ parts(node) {
284
+ const prelude = this.css.slice(node.preludeStart, node.preludeEnd);
285
+ return {
286
+ leading: this.css.slice(node.start, node.preludeStart),
287
+ prelude,
288
+ entries: splitSelectorList(prelude),
289
+ children: node.children,
290
+ };
291
+ }
292
+ /** The nodes of the top level or of the body of an at-rule, with every rule expanded. */
293
+ renderNodes(nodes, nested) {
294
+ let output = '';
295
+ for (const node of nodes) {
296
+ if (node.kind === 'text') {
297
+ output += this.text(node);
298
+ }
299
+ else if (!this.isAtRule(node)) {
300
+ output += this.renderRule(this.parts(node), nested);
301
+ }
302
+ else if (this.isConditional(node)) {
303
+ output += `${this.css.slice(node.start, node.bodyStart)}${this.renderNodes(node.children, nested)}}`;
304
+ }
305
+ else {
306
+ output += this.raw(node);
307
+ }
308
+ }
309
+ return output;
310
+ }
311
+ /** A rule followed by the rules moved out of it. */
312
+ renderRule(rule, nested) {
313
+ const parts = this.walkBody(rule.children, rule.entries, nested);
314
+ const head = `${rule.prelude}{`;
315
+ let output = '';
316
+ parts.forEach((part, index) => {
317
+ if (part.kind === 'hoisted')
318
+ output += part.text;
319
+ else if (index === 0)
320
+ output += `${rule.leading}${head}${part.text}}`;
321
+ else if (part.text.trim() !== '')
322
+ output += `\n\n${head}${part.text}}`;
323
+ });
324
+ return output;
325
+ }
326
+ /**
327
+ * Walks the body of a rule and moves each suffix nesting rule out, after the part of the body that precedes it.
328
+ *
329
+ * @remarks
330
+ * The moved rule sits next to the rule it came from, so it keeps its place in the cascade; the declarations that
331
+ * follow it stay in the rule, in a second piece, so they still come after it.
332
+ */
333
+ walkBody(children, parents, nested) {
334
+ const parts = [];
335
+ let current = '';
336
+ const flush = () => {
337
+ parts.push({ kind: 'body', text: current });
338
+ current = '';
339
+ };
340
+ for (const child of children) {
341
+ if (child.kind === 'text') {
342
+ current += this.text(child);
343
+ }
344
+ else if (this.isAtRule(child)) {
345
+ if (!this.isConditional(child)) {
346
+ current += this.raw(child);
347
+ continue;
348
+ }
349
+ const head = this.css.slice(child.start, child.bodyStart);
350
+ const inner = this.walkBody(child.children, parents, nested);
351
+ inner.forEach((part, index) => {
352
+ if (part.kind === 'body') {
353
+ if (inner.length === 1 || index === 0 || part.text.trim() !== '')
354
+ current += `${index === 0 ? head : `\n\n${head.trimStart()}`}${part.text}}`;
355
+ }
356
+ else {
357
+ flush();
358
+ parts.push({ kind: 'hoisted', text: `\n\n${head.trimStart()}${part.text}\n}` });
359
+ }
360
+ });
361
+ }
362
+ else {
363
+ const rule = this.parts(child);
364
+ const found = rule.entries.map(suffixOccurrences);
365
+ const withSuffix = found.filter((occurrences) => occurrences.length > 0).length;
366
+ if (withSuffix === 0) {
367
+ current += this.renderRule(rule, true);
368
+ }
369
+ else if (withSuffix < rule.entries.length) {
370
+ this.fail(child.preludeStart, `\`${rule.prelude.trim()}\` mixes suffix nesting with other selectors; give each its own rule.`);
371
+ current += this.raw(child);
372
+ }
373
+ else {
374
+ const entries = this.expandEntries(child, rule, found, parents, nested);
375
+ if (!entries) {
376
+ current += this.raw(child);
377
+ continue;
378
+ }
379
+ flush();
380
+ const expanded = {
381
+ leading: '\n\n',
382
+ prelude: `${entries.join(', ')} `,
383
+ entries,
384
+ children: rule.children,
385
+ };
386
+ parts.push({ kind: 'hoisted', text: this.renderRule(expanded, nested) });
387
+ }
388
+ }
389
+ }
390
+ flush();
391
+ return parts;
392
+ }
393
+ /** The selectors a suffix nesting rule stands for, or `undefined` after reporting why it cannot be expanded. */
394
+ expandEntries(child, rule, found, parents, nested) {
395
+ const location = child.preludeStart;
396
+ for (const parent of parents) {
397
+ if (parent === '&') {
398
+ this.fail(location, `\`${rule.prelude.trim()}\` cannot be expanded: its parent is a bare \`&\`, which has no name to append to. Write the rule in the parent that has the selector.`);
399
+ return undefined;
400
+ }
401
+ if (!isCompound(parent)) {
402
+ this.fail(location, `\`${rule.prelude.trim()}\` cannot be expanded: its parent \`${parent}\` is not a simple compound selector, since it has a combinator or whitespace. Write the full selector instead.`);
403
+ return undefined;
404
+ }
405
+ if (!acceptsSuffix(parent)) {
406
+ this.fail(location, `\`${rule.prelude.trim()}\` cannot be expanded: a suffix can only follow a class, an id or a type selector, and \`${parent}\` ends in something else. Write the full selector instead.`);
407
+ return undefined;
408
+ }
409
+ }
410
+ const expanded = [];
411
+ for (const [index, entry] of rule.entries.entries()) {
412
+ const occurrences = found[index];
413
+ if (hasPlainNesting(entry, occurrences)) {
414
+ this.fail(location, `\`${entry}\` mixes a suffix with another \`&\`. Write the full selector instead.`);
415
+ return undefined;
416
+ }
417
+ if (nested && occurrences.some((occurrence) => occurrence.start !== 0)) {
418
+ this.fail(location, `\`${entry}\` writes a suffix away from the start of the selector inside a rule that is itself nested. Write the full selector instead.`);
419
+ return undefined;
420
+ }
421
+ for (const parent of parents) {
422
+ let output = '';
423
+ let from = 0;
424
+ for (const occurrence of occurrences) {
425
+ output += `${entry.slice(from, occurrence.start)}${parent}${occurrence.suffix}`;
426
+ from = occurrence.end;
427
+ }
428
+ expanded.push(`${output}${entry.slice(from)}`);
429
+ }
430
+ }
431
+ return expanded;
432
+ }
433
+ }
434
+ /**
435
+ * Rewrites Sass-style suffix nesting into native nesting before Lightning CSS parses the stylesheet.
436
+ *
437
+ * @param css - Stylesheet source.
438
+ * @param file - Name of the stylesheet, which the errors carry.
439
+ * @throws StylesheetDiagnosticsError listing every rule that cannot be expanded, with file, line and column.
440
+ */
441
+ export function expandSuffixNesting(css, file) {
442
+ if (!/&[-_]/u.test(css))
443
+ return css;
444
+ const expander = new SuffixExpander(css, file);
445
+ const expanded = expander.expand();
446
+ if (expander.errors.length > 0)
447
+ throw new StylesheetDiagnosticsError(expander.errors.join('\n'));
448
+ return expanded;
449
+ }
450
+ /**
451
+ * A plugin for the Lightning CSS Processor that supports Sass-style suffix nesting: `&--x`, `&__x` and `&-x`.
452
+ *
453
+ * @remarks
454
+ * Native CSS nesting cannot concatenate selectors, so Lightning CSS fails a stylesheet that writes `&--primary`. This
455
+ * plugin rewrites each such rule before Lightning CSS parses the stylesheet, into a rule written out with the parent
456
+ * selectors, next to the rule it came from: `.button, a.button { &--primary { ... } }` becomes
457
+ * `.button--primary, a.button--primary { ... }` after `.button, a.button`. Nested rules and pseudo-classes inside it keep
458
+ * working. A parent that is not one compound selector per entry, such as `.card .title`, fails with the file, line and
459
+ * column, instead of a guess.
460
+ *
461
+ * @example
462
+ * ```typescript
463
+ * import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
464
+ * import { suffixNesting } from '@ecopages/lightningcss-processor/plugins/suffix-nesting';
465
+ *
466
+ * lightningCssProcessorPlugin({ plugins: [suffixNesting()] });
467
+ * ```
468
+ */
469
+ export function suffixNesting() {
470
+ return {
471
+ name: 'suffix-nesting',
472
+ transformSource: expandSuffixNesting,
473
+ };
474
+ }
@@ -0,0 +1,40 @@
1
+ import type { StylesheetInvalidation } from '@ecopages/core/processor';
2
+ /** What a {@link LightningCssPreprocessor} returns for one stylesheet. */
3
+ export interface PreprocessedStylesheet {
4
+ /** The CSS Lightning CSS reads in place of the source. */
5
+ css: string;
6
+ /** Absolute paths of the other files the preprocessor read; see `StylesheetTransformResult.dependencies`. */
7
+ dependencies?: readonly string[];
8
+ }
9
+ /** What the Processor gives {@link LightningCssPreprocessor.transform}. */
10
+ export interface LightningCssPreprocessorContext {
11
+ /** The app root. */
12
+ rootDir: string;
13
+ /** Runs the `transformSource` of the plugins over a stylesheet the stage reads itself. */
14
+ transformSource?: (css: string, file: string) => Promise<string>;
15
+ }
16
+ /**
17
+ * A stage that rewrites every stylesheet before the Lightning CSS Processor bundles, lowers and minifies it.
18
+ *
19
+ * @remarks
20
+ * It runs inside the Processor, so a stylesheet the stage fails on fails as one Lightning CSS rejects: a build stops
21
+ * and development keeps the last good output until a save fixes it.
22
+ */
23
+ export interface LightningCssPreprocessor {
24
+ /**
25
+ * Rewrites one stylesheet.
26
+ *
27
+ * @param css - Stylesheet source.
28
+ * @param file - Absolute path of the stylesheet, or the `processingOrigin` of a content dependency.
29
+ * @param context - `rootDir` is the app root. `transformSource` is the `transformSource` of the Processor's
30
+ * `plugins`, set only when a plugin has one: a stage that reads other stylesheets itself, as Tailwind does for
31
+ * its `@import`s, runs it over each of them so a plugin sees every stylesheet that reaches Lightning CSS.
32
+ */
33
+ transform(css: string, file: string, context: LightningCssPreprocessorContext): Promise<PreprocessedStylesheet>;
34
+ /**
35
+ * Names the stylesheets a change to other files makes stale; see `Processor.invalidateStylesheets`.
36
+ *
37
+ * @param files - The changed paths that are not stylesheets.
38
+ */
39
+ invalidate?(files: readonly string[]): StylesheetInvalidation | Promise<StylesheetInvalidation>;
40
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Adds `@reference` after the `@charset`, `@layer` and `@import` statements that open the stylesheet.
3
+ *
4
+ * @remarks
5
+ * An `@import` is inlined only when every statement before it is an `@import`, a `@charset` or an empty `@layer`, so a
6
+ * `@reference` placed first would leave the stylesheet's imports unresolved. A leading byte order mark stays first.
7
+ */
8
+ export declare function insertReference(css: string, referencePath: string): string;
9
+ /**
10
+ * Gives a stylesheet the theme of the Tailwind entry, so `@apply` finds the utilities of the app.
11
+ *
12
+ * @remarks
13
+ * The entry itself, and a stylesheet that already references or imports the entry, stay as written. An
14
+ * `@import "tailwindcss"` becomes an import of the entry so the app's theme applies. Any other stylesheet that uses
15
+ * `@apply`, and every CSS Module, gets an `@reference`, which emits nothing of the entry.
16
+ */
17
+ export declare function withReference(css: string, file: string, referencePath: string): string;
@@ -0,0 +1,101 @@
1
+ import { path } from '@ecopages/file-system/path';
2
+ /** A stylesheet Lightning CSS scopes as a CSS Module. */
3
+ const CSS_MODULE_FILE = /\.module\.css$/iu;
4
+ const TAILWIND_IMPORT = /^@import\s+['"]tailwindcss(?:\/[^'"]*)?['"];?\s*$/mu;
5
+ /** The index just past the statement that starts at `from`: its `;`, skipping strings and parentheses, or the end. */
6
+ function statementEnd(css, from) {
7
+ let depth = 0;
8
+ for (let index = from; index < css.length; index++) {
9
+ const char = css[index];
10
+ if (char === '"' || char === "'") {
11
+ index = quotedEnd(css, index);
12
+ }
13
+ else if (char === '(') {
14
+ depth++;
15
+ }
16
+ else if (char === ')') {
17
+ depth = Math.max(0, depth - 1);
18
+ }
19
+ else if (char === ';' && depth === 0) {
20
+ return index + 1;
21
+ }
22
+ else if (char === '{' && depth === 0) {
23
+ return -1;
24
+ }
25
+ }
26
+ return css.length;
27
+ }
28
+ /** The index of the quote that closes the string opened at `from`. */
29
+ function quotedEnd(css, from) {
30
+ for (let index = from + 1; index < css.length; index++) {
31
+ if (css[index] === '\\')
32
+ index++;
33
+ else if (css[index] === css[from])
34
+ return index;
35
+ }
36
+ return css.length;
37
+ }
38
+ /** The index just past the comments, `@charset`, `@import` and `@layer` order statements that open `css`. */
39
+ function leadingStatementsEnd(css) {
40
+ let end = 0;
41
+ let index = 0;
42
+ while (index < css.length) {
43
+ if (/\s/u.test(css[index])) {
44
+ index++;
45
+ }
46
+ else if (css.startsWith('/*', index)) {
47
+ const close = css.indexOf('*/', index + 2);
48
+ end = index = close === -1 ? css.length : close + 2;
49
+ }
50
+ else if (css[index] === '@') {
51
+ const name = /^@([\w-]+)/u.exec(css.slice(index, index + 32))?.[1]?.toLowerCase();
52
+ if (name !== 'charset' && name !== 'import' && name !== 'layer')
53
+ break;
54
+ const close = statementEnd(css, index);
55
+ if (close === -1)
56
+ break;
57
+ end = index = close;
58
+ }
59
+ else {
60
+ break;
61
+ }
62
+ }
63
+ return end;
64
+ }
65
+ /**
66
+ * Adds `@reference` after the `@charset`, `@layer` and `@import` statements that open the stylesheet.
67
+ *
68
+ * @remarks
69
+ * An `@import` is inlined only when every statement before it is an `@import`, a `@charset` or an empty `@layer`, so a
70
+ * `@reference` placed first would leave the stylesheet's imports unresolved. A leading byte order mark stays first.
71
+ */
72
+ export function insertReference(css, referencePath) {
73
+ const statement = `@reference "${referencePath}";`;
74
+ const bom = css.startsWith('') ? '' : '';
75
+ const body = css.slice(bom.length);
76
+ const end = leadingStatementsEnd(body);
77
+ if (end === 0)
78
+ return `${bom}${statement}\n\n${body}`;
79
+ return `${bom}${body.slice(0, end)}\n${statement}${body.slice(end)}`;
80
+ }
81
+ /**
82
+ * Gives a stylesheet the theme of the Tailwind entry, so `@apply` finds the utilities of the app.
83
+ *
84
+ * @remarks
85
+ * The entry itself, and a stylesheet that already references or imports the entry, stay as written. An
86
+ * `@import "tailwindcss"` becomes an import of the entry so the app's theme applies. Any other stylesheet that uses
87
+ * `@apply`, and every CSS Module, gets an `@reference`, which emits nothing of the entry.
88
+ */
89
+ export function withReference(css, file, referencePath) {
90
+ if (path.resolve(file) === referencePath)
91
+ return css;
92
+ if (/^\s*@reference\s+/mu.test(css))
93
+ return css;
94
+ if (css.includes(`@import '${referencePath}'`) || css.includes(`@import "${referencePath}"`))
95
+ return css;
96
+ if (TAILWIND_IMPORT.test(css))
97
+ return css.replace(TAILWIND_IMPORT, `@import '${referencePath}';`);
98
+ if (CSS_MODULE_FILE.test(file) || css.includes('@apply'))
99
+ return insertReference(css, referencePath);
100
+ return css;
101
+ }
@@ -0,0 +1,47 @@
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 type { LightningCssProcessorPluginConfig } from '../plugin.js';
8
+ /** Options for the Tailwind v4 preset. */
9
+ export interface TailwindV4PresetOptions {
10
+ /**
11
+ * Absolute path to the main Tailwind CSS file containing `@import "tailwindcss"`.
12
+ * Used to add `@reference` to the CSS files and CSS Modules that use `@apply`.
13
+ */
14
+ referencePath: string;
15
+ }
16
+ /**
17
+ * Tailwind's `Features` and `Polyfills` flags the preset reads.
18
+ *
19
+ * @remarks
20
+ * Tailwind declares them as ambient `const enum`s, which `verbatimModuleSyntax` cannot import, so the values are
21
+ * repeated here and a test pins them to the installed Tailwind.
22
+ */
23
+ export declare const TAILWIND_FLAGS: {
24
+ readonly featuresNone: 0;
25
+ readonly featuresUtilities: 16;
26
+ readonly polyfillsAll: 3;
27
+ readonly polyfillsAtProperty: 1;
28
+ };
29
+ /**
30
+ * Creates a Lightning CSS Processor config preset for Tailwind CSS v4.
31
+ *
32
+ * Tailwind runs inside the Processor, so the app needs no PostCSS. Each stylesheet goes through Tailwind, then through
33
+ * the Processor's own Lightning CSS steps: bundling, `targets`, minifying and CSS Modules. Stylesheets that use
34
+ * `@apply`, and CSS Modules, get an `@reference` to `referencePath` so the app's theme applies.
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * import { lightningCssProcessorPlugin } from '@ecopages/lightningcss-processor';
39
+ * import { tailwindV4Preset } from '@ecopages/lightningcss-processor/presets/tailwind-v4';
40
+ *
41
+ * lightningCssProcessorPlugin({
42
+ * ...tailwindV4Preset({ referencePath: path.resolve(import.meta.dirname, 'src/styles/tailwind.css') }),
43
+ * targets: ['chrome >= 111'],
44
+ * })
45
+ * ```
46
+ */
47
+ export declare function tailwindV4Preset(options: TailwindV4PresetOptions): LightningCssProcessorPluginConfig;