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