@ecopages/postcss-processor 0.2.0-alpha.2 → 0.2.0-alpha.20

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/src/plugin.ts DELETED
@@ -1,354 +0,0 @@
1
- /**
2
- * PostCssProcessorPlugin
3
- * @module @ecopages/postcss-processor
4
- */
5
-
6
- import path from 'node:path';
7
- import type { IClientBridge } from '@ecopages/core';
8
- import { fileSystem } from '@ecopages/file-system';
9
- import { Processor, type ProcessorConfig } from '@ecopages/core/plugins/processor';
10
- import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
11
- import { Logger } from '@ecopages/logger';
12
- import type postcss from 'postcss';
13
- import { PostCssProcessor } from './postcss-processor';
14
- import { createCssLoaderPlugin } from './runtime/css-loader-plugin';
15
- import type { CssTransformInput } from './runtime/css-runtime-contract';
16
-
17
- const logger = new Logger('[@ecopages/postcss-processor]', {
18
- debug: process.env.ECOPAGES_LOGGER_DEBUG === 'true',
19
- });
20
-
21
- /**
22
- * Record of PostCSS plugins keyed by name
23
- */
24
- export type PluginsRecord = Record<string, postcss.AcceptedPlugin>;
25
-
26
- /**
27
- * Configuration for the PostCSS processor
28
- */
29
- export interface PostCssProcessorPluginConfig {
30
- /**
31
- * Regex filter to match files to process
32
- */
33
- filter?: RegExp;
34
- /**
35
- * Function to transform the contents of the file.
36
- * It can be handy to add a custom header or footer to the file.
37
- * Useful for injecting Tailwind v4 `@reference` directives.
38
- * @param contents The contents of the file
39
- * @param filePath The absolute path to the CSS file being processed
40
- * @returns The transformed contents
41
- */
42
- transformInput?: (contents: string | Buffer, filePath: string) => string | Promise<string>;
43
- /**
44
- * Function to transform the output CSS after PostCSS processing.
45
- * It can be handy to add a custom header or footer to the processed CSS.
46
- * @param css The processed CSS
47
- * @returns The transformed CSS
48
- */
49
- transformOutput?: (css: string) => Promise<string> | string;
50
- /**
51
- * Custom PostCSS plugins to use instead of the default ones
52
- * @default undefined (uses default plugins)
53
- */
54
- plugins?: PluginsRecord;
55
- }
56
-
57
- /**
58
- * PostCssProcessorPlugin
59
- * A Processor for transforming CSS files.
60
- */
61
- export class PostCssProcessorPlugin extends Processor<PostCssProcessorPluginConfig> {
62
- static DEFAULT_OPTIONS: Required<Pick<PostCssProcessorPluginConfig, 'filter'>> = {
63
- filter: /\.css$/,
64
- };
65
-
66
- private postcssPlugins: postcss.AcceptedPlugin[] = [];
67
- private readonly runtimeCssCache = new Map<string, string>();
68
-
69
- private getCssFilter(): RegExp {
70
- return this.options?.filter ?? PostCssProcessorPlugin.DEFAULT_OPTIONS.filter;
71
- }
72
-
73
- private resolveProcessedCssPath(filePath: string): string | null {
74
- if (!this.context) {
75
- return null;
76
- }
77
-
78
- const relativePath = path.relative(this.context.srcDir, filePath);
79
- if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
80
- return null;
81
- }
82
-
83
- return path.join(this.context.distDir, 'assets', relativePath);
84
- }
85
-
86
- private readProcessedCssFromDist(filePath: string): string | null {
87
- const outputPath = this.resolveProcessedCssPath(filePath);
88
- if (!outputPath || !fileSystem.exists(outputPath)) {
89
- return null;
90
- }
91
-
92
- return fileSystem.readFileAsBuffer(outputPath).toString('utf-8');
93
- }
94
-
95
- private async persistProcessedCss(filePath: string, css: string): Promise<void> {
96
- const outputPath = this.resolveProcessedCssPath(filePath);
97
- if (!outputPath) {
98
- return;
99
- }
100
-
101
- fileSystem.ensureDir(path.dirname(outputPath));
102
- fileSystem.write(outputPath, css);
103
- }
104
-
105
- private async prewarmRuntimeCssCache(): Promise<void> {
106
- if (!this.context) {
107
- return;
108
- }
109
-
110
- const sourceFiles = await fileSystem.glob(['**/*.{css,scss,sass,less}'], {
111
- cwd: this.context.srcDir,
112
- });
113
-
114
- for (const relativePath of sourceFiles) {
115
- const filePath = path.join(this.context.srcDir, relativePath);
116
- if (!this.matchesFileFilter(filePath)) {
117
- continue;
118
- }
119
-
120
- const rawContents = await fileSystem.readFile(filePath);
121
- let transformedInput = rawContents;
122
-
123
- if (this.options?.transformInput) {
124
- transformedInput = await this.options.transformInput(rawContents, filePath);
125
- }
126
-
127
- const processed = await this.process(transformedInput, filePath);
128
- this.runtimeCssCache.set(filePath, processed);
129
- await this.persistProcessedCss(filePath, processed);
130
- }
131
- }
132
-
133
- private transformCssSync(input: CssTransformInput): string {
134
- const cached = this.runtimeCssCache.get(input.filePath);
135
- if (cached) {
136
- return cached;
137
- }
138
-
139
- const persisted = this.readProcessedCssFromDist(input.filePath);
140
- if (persisted) {
141
- this.runtimeCssCache.set(input.filePath, persisted);
142
- return persisted;
143
- }
144
-
145
- const { contents } = input;
146
- return typeof contents === 'string' ? contents : contents.toString('utf-8');
147
- }
148
-
149
- private async transformCssAsync(input: CssTransformInput): Promise<string> {
150
- const { contents, filePath } = input;
151
- let transformed: string = typeof contents === 'string' ? contents : contents.toString('utf-8');
152
-
153
- if (this.options?.transformInput) {
154
- const result = this.options.transformInput(contents, filePath);
155
- transformed =
156
- typeof (result as unknown as Record<string, unknown>).then === 'function'
157
- ? await (result as Promise<string>)
158
- : (result as string);
159
- }
160
-
161
- const processed = await this.process(transformed, filePath);
162
- this.runtimeCssCache.set(filePath, processed);
163
- await this.persistProcessedCss(filePath, processed);
164
- return processed;
165
- }
166
-
167
- override matchesFileFilter(filepath: string): boolean {
168
- const filter = this.options?.filter ?? PostCssProcessorPlugin.DEFAULT_OPTIONS.filter;
169
- return filter.test(filepath);
170
- }
171
-
172
- constructor(
173
- config: Omit<ProcessorConfig<PostCssProcessorPluginConfig>, 'name' | 'description'> = {
174
- options: PostCssProcessorPlugin.DEFAULT_OPTIONS,
175
- },
176
- ) {
177
- super({
178
- name: 'ecopages-postcss-processor',
179
- description: 'A Processor for transforming CSS files using PostCSS.',
180
- capabilities: [
181
- {
182
- kind: 'stylesheet',
183
- extensions: ['*.css'],
184
- },
185
- ],
186
- watch: {
187
- paths: [],
188
- extensions: ['.css', '.scss', '.sass', '.less'],
189
- onChange: async ({ path, bridge }) => {
190
- await this.handleCssChange(path, bridge);
191
- },
192
- },
193
- ...config,
194
- });
195
- }
196
-
197
- /**
198
- * Handles CSS file changes during development.
199
- * Processes the file and broadcasts a css-update event for hot reloading.
200
- */
201
- private async handleCssChange(filePath: string, bridge: IClientBridge): Promise<void> {
202
- if (!this.context) return;
203
-
204
- try {
205
- let content = await fileSystem.readFile(filePath);
206
-
207
- if (this.options?.transformInput) {
208
- content = await this.options.transformInput(content, filePath);
209
- }
210
-
211
- const processed = await this.process(content, filePath);
212
- this.runtimeCssCache.set(filePath, processed);
213
- await this.persistProcessedCss(filePath, processed);
214
-
215
- bridge.cssUpdate(filePath);
216
-
217
- logger.debug(`Processed CSS: ${filePath}`);
218
- } catch (error) {
219
- const errorMessage = error instanceof Error ? error.message : String(error);
220
- logger.error(`Failed to process CSS: ${filePath}`, errorMessage);
221
- bridge.error(errorMessage);
222
- }
223
- }
224
-
225
- get buildPlugins(): EcoBuildPlugin[] {
226
- return [
227
- createCssLoaderPlugin({
228
- name: 'postcss-processor-build-loader',
229
- filter: this.getCssFilter(),
230
- transform: this.transformCssAsync.bind(this),
231
- }),
232
- ];
233
- }
234
-
235
- get plugins(): EcoBuildPlugin[] {
236
- return [
237
- createCssLoaderPlugin({
238
- name: 'postcss-processor-runtime-loader',
239
- filter: this.getCssFilter(),
240
- transform: this.transformCssSync.bind(this),
241
- }),
242
- ];
243
- }
244
-
245
- /**
246
- * Setup the PostCSS processor.
247
- */
248
- async setup(): Promise<void> {
249
- await this.collectPostcssPlugins();
250
- await this.prewarmRuntimeCssCache();
251
- }
252
-
253
- /**
254
- * Get the PostCSS plugins from the options or a config file.
255
- * Searches for postcss.config.{js,cjs,mjs,ts} in the root directory.
256
- */
257
- private async collectPostcssPlugins(): Promise<void> {
258
- if (!this.context) {
259
- throw new Error('Context must be set');
260
- }
261
-
262
- const configExtensions = ['js', 'cjs', 'mjs', 'ts'];
263
- let foundConfigPath: string | undefined;
264
- let loadedPlugins: postcss.AcceptedPlugin[] | undefined;
265
-
266
- for (const ext of configExtensions) {
267
- const configPath = path.join(this.context.rootDir, `postcss.config.${ext}`);
268
- if (fileSystem.exists(configPath)) {
269
- foundConfigPath = configPath;
270
- break;
271
- }
272
- }
273
-
274
- if (foundConfigPath) {
275
- try {
276
- logger.debug(`Loading PostCSS config from: ${foundConfigPath}`);
277
-
278
- const postcssConfigModule = await import(foundConfigPath);
279
- const postcssConfig = postcssConfigModule.default || postcssConfigModule;
280
-
281
- if (postcssConfig && typeof postcssConfig.plugins === 'object' && postcssConfig.plugins !== null) {
282
- if (Array.isArray(postcssConfig.plugins)) {
283
- loadedPlugins = postcssConfig.plugins;
284
- } else {
285
- loadedPlugins = Object.values(postcssConfig.plugins as PluginsRecord);
286
- }
287
- logger.debug(`Successfully loaded ${loadedPlugins?.length ?? 0} plugins from config file.`);
288
- } else {
289
- logger.warn(
290
- `PostCSS config file found (${foundConfigPath}), but no valid 'plugins' export detected.`,
291
- );
292
- }
293
- } catch (error: any) {
294
- logger.error(`Error loading PostCSS config from ${foundConfigPath}: ${error.message}`, error);
295
- loadedPlugins = undefined;
296
- }
297
- } else {
298
- logger.debug('No PostCSS config file found in root directory.');
299
- }
300
-
301
- if (loadedPlugins) {
302
- this.postcssPlugins = loadedPlugins;
303
- } else if (this.options?.plugins) {
304
- logger.debug('Using PostCSS plugins provided in processor options.');
305
- this.postcssPlugins = Object.values(this.options.plugins);
306
- } else {
307
- logger.warn(
308
- 'No PostCSS plugins configured. Use a preset like tailwindV3Preset() or tailwindV4Preset(), ' +
309
- 'provide plugins via options, or create a postcss.config file.',
310
- );
311
- this.postcssPlugins = [];
312
- }
313
-
314
- if (!this.postcssPlugins || this.postcssPlugins.length === 0) {
315
- logger.warn('No PostCSS plugins configured or loaded. CSS processing might be minimal.');
316
- this.postcssPlugins = [];
317
- }
318
- }
319
-
320
- /**
321
- * Process CSS content
322
- * @param fileAsString CSS content as string
323
- * @param filePath Optional file path for resolving relative imports
324
- * @returns Processed CSS
325
- */
326
- async process(fileAsString: string, filePath?: string): Promise<string> {
327
- return await PostCssProcessor.processStringOrBuffer(fileAsString, {
328
- filePath,
329
- plugins: this.postcssPlugins,
330
- transformOutput: this.options?.transformOutput,
331
- });
332
- }
333
-
334
- processSync(fileAsString: string, filePath?: string): string {
335
- return PostCssProcessor.processStringOrBufferSync(fileAsString, {
336
- filePath,
337
- plugins: this.postcssPlugins,
338
- transformOutput: this.options?.transformOutput,
339
- });
340
- }
341
-
342
- /**
343
- * Teardown the PostCSS processor.
344
- */
345
- async teardown(): Promise<void> {
346
- logger.debug('Tearing down PostCSS processor');
347
- }
348
- }
349
-
350
- export const postcssProcessorPlugin = (config?: PostCssProcessorPluginConfig): PostCssProcessorPlugin => {
351
- return new PostCssProcessorPlugin({
352
- options: config,
353
- });
354
- };
@@ -1,157 +0,0 @@
1
- /**
2
- * This module contains the PostCSS Processor
3
- * @module
4
- */
5
-
6
- import { existsSync, readFileSync } from 'node:fs';
7
- import { Logger } from '@ecopages/logger';
8
- import postcss from 'postcss';
9
-
10
- /**
11
- * PostCSS Processor Options
12
- */
13
- export type PostCssProcessorOptions = {
14
- plugins?: postcss.AcceptedPlugin[];
15
- /**
16
- * Optional file path for resolving relative imports
17
- */
18
- filePath?: string;
19
- /**
20
- * Optional callback to transform the output CSS
21
- * @param css The processed CSS
22
- * @returns The transformed CSS
23
- */
24
- transformOutput?: (css: string) => string | Promise<string>;
25
- };
26
-
27
- /**
28
- * ProcessPath
29
- * @param path string
30
- * @param options {@link PostCssProcessorOptions}
31
- * @returns string
32
- */
33
- export type ProcessPath = (path: string, options?: PostCssProcessorOptions) => Promise<string>;
34
-
35
- /**
36
- * ProcessStringOrBuffer
37
- * @param contents string | Buffer
38
- * @param options {@link PostCssProcessorOptions}
39
- * @returns string
40
- */
41
- export type ProcessStringOrBuffer = (contents: string | Buffer, options?: PostCssProcessorOptions) => Promise<string>;
42
-
43
- const appLogger = new Logger('[@ecopages/postcss-processor]');
44
-
45
- export function getFileAsBuffer(path: string): Buffer {
46
- try {
47
- if (!existsSync(path)) {
48
- throw new Error(`File: ${path} not found`);
49
- }
50
- return readFileSync(path);
51
- } catch (error) {
52
- const errorMessage = error instanceof Error ? error.message : String(error);
53
- throw new Error(`[ecopages] Error reading file: ${path}, ${errorMessage}`);
54
- }
55
- }
56
-
57
- const getPlugins = (options?: PostCssProcessorOptions): postcss.AcceptedPlugin[] => {
58
- if (!options || !options.plugins) return [];
59
- return Array.isArray(options.plugins) ? options.plugins : Object.values(options.plugins);
60
- };
61
-
62
- /**
63
- * It processes the given path using PostCSS
64
- * @param path string
65
- * @param options {@link PostCssProcessorOptions}
66
- * @returns string
67
- *
68
- * @example
69
- * ```ts
70
- * PostCssProcessor.processPath('path/to/file.css').then((processedCss) => {
71
- * console.log(processedCss);
72
- * });\n */
73
- const processPath: ProcessPath = async (path, options) => {
74
- const contents = getFileAsBuffer(path);
75
-
76
- return postcss(getPlugins(options))
77
- .process(contents, { from: path })
78
- .then((result) => result.css)
79
- .catch((error) => {
80
- appLogger.error('Error processing file with PostCssProcessor', error.message);
81
- return '';
82
- });
83
- };
84
-
85
- /**
86
- * It processes the given string or buffer using PostCSS
87
- * @param contents string | Buffer
88
- * @param options {@link PostCssProcessorOptions}
89
- * @returns string
90
- *
91
- * @example
92
- * ```ts
93
- * const css = `body { @apply bg-blue-500; }`;
94
- *
95
- * PostCssProcessor.processString(css).then((processedCss) => {
96
- * console.log(processedCss);
97
- * });
98
- * ```
99
- */
100
- const processStringOrBuffer: ProcessStringOrBuffer = async (contents, options) => {
101
- if (!contents) return '';
102
-
103
- return postcss(getPlugins(options))
104
- .process(contents, { from: options?.filePath })
105
- .then(async (result) => {
106
- let css = result.css;
107
- if (options?.transformOutput) {
108
- css = await options.transformOutput(css);
109
- }
110
- return css;
111
- })
112
- .catch((error) => {
113
- appLogger.error('Error processing string or buffer with PostCssProcessor', error.message);
114
- return '';
115
- });
116
- };
117
-
118
- export type ProcessStringOrBufferSync = (contents: string | Buffer, options?: PostCssProcessorOptions) => string;
119
-
120
- const processStringOrBufferSync: ProcessStringOrBufferSync = (contents, options) => {
121
- if (!contents) return '';
122
-
123
- try {
124
- const result = postcss(getPlugins(options)).process(contents, { from: options?.filePath });
125
- let css = result.css;
126
- if (options?.transformOutput) {
127
- const output = options.transformOutput(css);
128
- if (output instanceof Promise) {
129
- throw new Error('transformOutput must be synchronous when used with processStringOrBufferSync');
130
- }
131
- css = output;
132
- }
133
- return css;
134
- } catch (error) {
135
- if (error instanceof Error && error.message.includes('transformOutput must be synchronous')) {
136
- throw error;
137
- }
138
- appLogger.error('Error processing string or buffer with PostCssProcessor', (error as Error).message);
139
- return '';
140
- }
141
- };
142
-
143
- /**
144
- * PostCSS Processor
145
- * - {@link processPath} : It processes the given path using PostCSS
146
- * - {@link processStringOrBuffer}: It processes the given string or buffer using PostCSS
147
- * - {@link processStringOrBufferSync}: It processes the given string or buffer synchronously using PostCSS (requires all plugins to be sync)
148
- */
149
- export const PostCssProcessor: {
150
- processPath: ProcessPath;
151
- processStringOrBuffer: ProcessStringOrBuffer;
152
- processStringOrBufferSync: ProcessStringOrBufferSync;
153
- } = {
154
- processPath,
155
- processStringOrBuffer,
156
- processStringOrBufferSync,
157
- };
@@ -1,7 +0,0 @@
1
- /**
2
- * PostCSS Processor Presets
3
- * @module @ecopages/postcss-processor/presets
4
- */
5
-
6
- export { tailwindV3Preset } from './tailwind-v3';
7
- export { tailwindV4Preset, type TailwindV4PresetOptions } from './tailwind-v4';
@@ -1,61 +0,0 @@
1
- /**
2
- * Tailwind CSS v3 Preset for PostCSS Processor
3
- * @module @ecopages/postcss-processor/presets/tailwind-v3
4
- *
5
- * Requires: tailwindcss, postcss-import, autoprefixer, cssnano
6
- * Install: bun add tailwindcss postcss-import autoprefixer cssnano
7
- */
8
-
9
- import autoprefixer from 'autoprefixer';
10
- import browserslist from 'browserslist';
11
- import cssnano from 'cssnano';
12
- import type postcss from 'postcss';
13
- import postcssImport from 'postcss-import';
14
- import tailwindcss from 'tailwindcss';
15
- import tailwindcssNesting from 'tailwindcss/nesting/index.js';
16
- import type { PostCssProcessorPluginConfig } from '../plugin.ts';
17
-
18
- type PluginsRecord = Record<string, postcss.AcceptedPlugin>;
19
-
20
- /**
21
- * Creates a PostCSS processor config preset for Tailwind CSS v3.
22
- *
23
- * Features:
24
- * - Uses classic Tailwind v3 plugin stack
25
- * - Includes postcss-import, tailwindcss/nesting, tailwindcss, autoprefixer, cssnano
26
- *
27
- * @example
28
- * ```typescript
29
- * import { postcssProcessorPlugin } from '@ecopages/postcss-processor';
30
- * import { tailwindV3Preset } from '@ecopages/postcss-processor/presets';
31
- *
32
- * // Basic usage
33
- * postcssProcessorPlugin(tailwindV3Preset())
34
- *
35
- * // Extend with additional plugins
36
- * const preset = tailwindV3Preset();
37
- * postcssProcessorPlugin({
38
- * ...preset,
39
- * plugins: { ...preset.plugins, myPlugin: myPlugin() },
40
- * })
41
- * ```
42
- */
43
- export function tailwindV3Preset(): PostCssProcessorPluginConfig {
44
- // Check if browserslist config exists
45
- const browserslistConfig = browserslist.loadConfig({ path: process.cwd() });
46
- const autoprefixerOptions = browserslistConfig
47
- ? {}
48
- : {
49
- overrideBrowserslist: ['>0.3%', 'not ie 11', 'not dead', 'not op_mini all'],
50
- };
51
-
52
- const plugins: PluginsRecord = {
53
- 'postcss-import': postcssImport(),
54
- 'tailwindcss/nesting': tailwindcssNesting(),
55
- tailwindcss: tailwindcss(),
56
- autoprefixer: autoprefixer(autoprefixerOptions),
57
- cssnano: cssnano(),
58
- };
59
-
60
- return { plugins };
61
- }
@@ -1,113 +0,0 @@
1
- /**
2
- * Tailwind CSS v4 Preset for PostCSS Processor
3
- * @module @ecopages/postcss-processor/presets/tailwind-v4
4
- *
5
- * Requires: @tailwindcss/postcss, cssnano
6
- * Install: bun add @tailwindcss/postcss cssnano
7
- */
8
-
9
- import tailwindcss from '@tailwindcss/postcss';
10
- import autoprefixer from 'autoprefixer';
11
- import browserslist from 'browserslist';
12
- import cssnano from 'cssnano';
13
- import path from 'node:path';
14
- import postcssImport from 'postcss-import';
15
- import postcssNested from 'postcss-nested';
16
- import type { PostCssProcessorPluginConfig } from '../plugin.ts';
17
-
18
- /**
19
- * Options for Tailwind v4 preset
20
- */
21
- export interface TailwindV4PresetOptions {
22
- /**
23
- * Absolute path to the main Tailwind CSS file containing `@import "tailwindcss"`.
24
- * Used to calculate relative @reference paths for CSS files using @apply.
25
- */
26
- referencePath: string;
27
- }
28
-
29
- /**
30
- * Creates a PostCSS processor config preset for Tailwind CSS v4.
31
- *
32
- * Features:
33
- * - Uses `@tailwindcss/postcss` plugin (v4)
34
- * - Automatically injects `@reference` headers for `@apply` support
35
- * - Includes cssnano for CSS minification
36
- *
37
- * @example
38
- * ```typescript
39
- * import { postcssProcessorPlugin } from '@ecopages/postcss-processor';
40
- * import { tailwindV4Preset } from '@ecopages/postcss-processor/presets';
41
- *
42
- * // Basic usage
43
- * postcssProcessorPlugin(tailwindV4Preset({
44
- * referencePath: path.resolve(import.meta.dir, 'src/styles/tailwind.css'),
45
- * }))
46
- *
47
- * // Extend with additional plugins
48
- * const preset = tailwindV4Preset({ referencePath });
49
- * postcssProcessorPlugin({
50
- * ...preset,
51
- * plugins: { ...preset.plugins, myPlugin: myPlugin() },
52
- * })
53
- * ```
54
- */
55
- export function tailwindV4Preset(options: TailwindV4PresetOptions): PostCssProcessorPluginConfig {
56
- const { referencePath } = options;
57
-
58
- // Check if browserslist config exists
59
- const browserslistConfig = browserslist.loadConfig({ path: process.cwd() });
60
- const autoprefixerOptions = browserslistConfig
61
- ? {}
62
- : {
63
- overrideBrowserslist: ['>0.3%', 'not ie 11', 'not dead', 'not op_mini all'],
64
- };
65
-
66
- return {
67
- plugins: {
68
- 'postcss-import': postcssImport(),
69
- 'postcss-nested': postcssNested(),
70
- '@tailwindcss/postcss': tailwindcss(),
71
- autoprefixer: autoprefixer(autoprefixerOptions),
72
- cssnano: cssnano(),
73
- },
74
- transformInput: async (contents: string | Buffer, filePath: string): Promise<string> => {
75
- const css = contents instanceof Buffer ? contents.toString('utf-8') : (contents as string);
76
- const normalizedFilePath = path.resolve(filePath);
77
- const normalizedReferencePath = path.resolve(referencePath);
78
-
79
- /** Skip transformation for the main tailwind entry file */
80
- if (normalizedFilePath === normalizedReferencePath) {
81
- return css;
82
- }
83
-
84
- /** Skip if file already has an @reference directive */
85
- if (/^\s*@reference\s+/m.test(css)) {
86
- return css;
87
- }
88
-
89
- const relativePath = path.relative(path.dirname(filePath), referencePath);
90
-
91
- /** Skip if file already imports the referencePath */
92
- if (css.includes(`@import '${relativePath}'`) || css.includes(`@import "${relativePath}"`)) {
93
- return css;
94
- }
95
-
96
- /**
97
- * Replace `@import 'tailwindcss'` with an import to the referencePath.
98
- * This ensures custom theme variables are available for @apply directives.
99
- */
100
- const tailwindImportPattern = /^@import\s+['"]tailwindcss(?:\/[^'"]*)?['"];?\s*$/m;
101
- if (tailwindImportPattern.test(css)) {
102
- return css.replace(tailwindImportPattern, `@import '${relativePath}';`);
103
- }
104
-
105
- /** If file uses @apply but has no tailwind import, add @reference */
106
- if (css.includes('@apply')) {
107
- return `@reference "${relativePath}";\n\n${css}`;
108
- }
109
-
110
- return css;
111
- },
112
- };
113
- }