-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbuild-css.js
More file actions
344 lines (319 loc) · 9.72 KB
/
build-css.js
File metadata and controls
344 lines (319 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import {
readFileSync,
writeFileSync,
readdirSync,
existsSync,
mkdirSync,
statSync,
} from 'fs';
import path from 'path';
// eslint-disable-next-line import/no-extraneous-dependencies
import browserslist from 'browserslist';
import { bundleAsync, browserslistToTargets } from 'lightningcss';
import themeConfig from './config/themeConfig.js'; // merged BuddyX config (default -> config -> local)
},
/** Map relative entries to absolute paths using BuddyX paths.styles.srcDir. */
const preloadListAbs = preloadListRel.map( ( p ) =>
path.resolve( paths.styles.srcDir, p )
);
/**
* Concatenate all preload files into a single virtual snippet.
* Missing files are silently skipped to match legacy behavior.
* @return {string} Concatenated preload CSS snippet.
*/ function loadPreloadSnippet() {
let buf = '';
for ( const file of preloadListAbs ) {
try {
buf += readFileSync( file, 'utf8' ) + '\n';
} catch {
// ignore missing files
}
}
return buf;
}
const PRELOAD_SNIPPET = loadPreloadSnippet();
const VIRTUAL_ID = 'virtual:preload.css';
/**
* Process CSS content to replace theme URLs with actual paths.
*
* Handles both url('~theme/path') and var(--theme-assets-path)/path and converts
* them to proper absolute URLs with the theme path.
*
* @param {string} css - CSS content to process
* @return {string} - Processed CSS content
*/
function processThemeUrls( css ) {
const themeName = themeSlug;
// Replace ~theme/... (with or without quotes)
let processedCSS = css.replace(
/url\((['"]?)~theme\/([^'")]+)(['"]?)\)/g,
( match, openQuote, assetPath, closeQuote ) => {
const quote = openQuote || "'";
const endQuote = closeQuote || "'";
return `url(${ quote }/wp-content/themes/${ themeName }/${ assetPath }${ endQuote })`;
}
);
// Replace var(--theme-assets-path)/...
processedCSS = processedCSS.replace(
/var\(--theme-assets-path\)\/([^\s;)]+)/g,
( match, assetPath ) => {
return `url('/wp-content/themes/${ themeName }/assets/${ assetPath }')`;
}
);
return processedCSS;
}
/**
* Insert a snippet right after the top-level @import block (and optional @charset).
*
* @param {string} css - CSS content
* @param {string} snippet - Snippet to insert
* @return {string} - Modified CSS content
*/
function insertAfterTopImports( css, snippet ) {
const charsetRe = /^\s*@charset[^;]+;\s*/i;
let head = '';
let rest = css;
const cm = rest.match( charsetRe );
if ( cm ) {
head = cm[ 0 ];
rest = rest.slice( cm[ 0 ].length );
}
const importBlockRe = /^(?:\s*@import\s+(?:url\()?[^;]+;\s*)+/i;
const ib = rest.match( importBlockRe );
const importsBlock = ib ? ib[ 0 ] : '';
if ( ib ) {
rest = rest.slice( importsBlock.length );
}
return head + importsBlock + snippet + rest;
}
/**
* Ensure a single virtual import is present after the top-level imports (idempotent).
*
* @param {string} css - CSS content
* @return {string} - CSS with virtual import ensured
*/
function ensureVirtualImportInserted( css ) {
if (
css.includes( `@import "${ VIRTUAL_ID }"` ) ||
css.includes( `@import '${ VIRTUAL_ID }'` )
) {
return css;
}
return insertAfterTopImports( css, `@import "${ VIRTUAL_ID }";\n` );
}
/**
* Dev-only guard: fail fast if a file still contains a late @import.
*
* @param {string} css - CSS content
* @param {string} file - File path (for error messages)
* @throws {Error} If late @import is detected
*/
function assertNoLateImports( css, file ) {
if ( ! isDev ) {
return;
}
// Strip any number of leading block comments and whitespace
let s = css;
for (;;) {
const before = s;
s = s.replace( /^\s*\/\*[\s\S]*?\*\/\s*/m, '' );
s = s.replace( /^\s+/, '' );
if ( s === before ) {
break;
}
}
// Allowed at the very top: @charset, @layer, @import (any amount/order)
const top =
s.match(
/^((\s*@charset[^\n;]*;\s*|\s*@layer[^{;]*;\s*|\s*@import\s+[^\n;]*;\s*)*)/i
)?.[ 0 ] ?? '';
const rest = s.slice( top.length );
if ( /@import\s+[^;]+;/i.test( rest ) ) {
throw new Error(
`Late @import in ${ file } — must precede all other rules (except @charset/@layer).`
);
}
}
/**
* Recursively collect all CSS files (excluding partials starting with "_").
*
* @param {string} dir - Directory to search
* @return {string[]} - List of CSS file paths
*/
const getAllFiles = ( dir ) => {
const files = readdirSync( dir );
let filelist = [];
files.forEach( ( file ) => {
const filePath = path.join( dir, file );
const fileStat = statSync( filePath );
if ( fileStat.isDirectory() ) {
filelist = filelist.concat( getAllFiles( filePath ) );
} else if ( file.endsWith( '.css' ) && ! file.startsWith( '_' ) ) {
filelist.push( filePath );
}
} );
return filelist;
};
/**
* Process a single CSS file with LightningCSS bundler.
* - Targets are derived from Browserslist (env-aware)
* - Virtual preload import can be injected after top-level @import block (theme CSS only)
* - Source map is emitted and linked via sourceMappingURL in dev mode
*
* @param {string} filePath - Path to input CSS file
* @param {string} outputPath - Path to output CSS file
* @param {boolean} injectPreload - Whether to inject theme preload snippet (default: true)
* @return {Promise<void>}
*/
const processCSSFile = async ( filePath, outputPath, injectPreload = true ) => {
const entryAbs = path.resolve( filePath );
// Resolve Browserslist targets from project config (.browserslistrc / package.json)
const browserslistEnv =
process.env.BROWSERSLIST_ENV ||
( isDev ? 'development' : 'production' );
const browsers = browserslist( null, {
path: process.cwd(),
env: browserslistEnv,
} );
const targets = browserslistToTargets( browsers );
const result = await bundleAsync( {
filename: entryAbs,
minify: ! isDev,
sourceMap: isDev,
sourceMapIncludeSources: true, // embed original sources so DevTools can jump to them
drafts: { customMedia: true },
targets,
resolver: {
// Provide processed source per file so each keeps its identity in the map
read( readPath ) {
// Serve the virtual preload file
if ( readPath === VIRTUAL_ID ) {
return PRELOAD_SNIPPET || '';
}
// Read original file content
let css = readFileSync( readPath, 'utf8' );
// Validate import ordering (dev) without mutating sources
assertNoLateImports( css, readPath );
// Apply text-level transforms that should be visible as "original" in maps
css = replaceInlineCSS( css );
css = processThemeUrls( css );
// Inject the virtual preload import AFTER the top-level import block (theme CSS only)
if ( injectPreload && PRELOAD_SNIPPET ) {
css = ensureVirtualImportInserted( css );
}
return css;
},
resolve( specifier, from ) {
// Keep the virtual id as-is; resolve real paths relative to importer
if ( specifier === VIRTUAL_ID ) {
return VIRTUAL_ID;
}
return path.resolve( path.dirname( from ), specifier );
},
},
} );
if ( isDev && result.map ) {
try {
const mapJson = JSON.parse( result.map.toString() );
if (
! Array.isArray( mapJson.sources ) ||
mapJson.sources.length === 0
) {
// eslint-disable-next-line no-console
console.warn(
'[css] Warning: sourcemap has no sources for',
filePath
);
}
} catch ( err ) {
// eslint-disable-next-line no-console
console.warn(
'[css] Failed to parse sourcemap for',
filePath,
err
);
}
}
// Write CSS (and map) + append sourceMappingURL in one go
if ( result.map ) {
const mapFile = `${ outputPath }.map`;
writeFileSync( mapFile, result.map );
// Append a comment at the end of the CSS file that allows browsers to locate the corresponding map file.
const cssWithMap = Buffer.concat( [
result.code,
Buffer.from(
`\n/*# sourceMappingURL=${ path.basename( mapFile ) } */\n`
),
] );
writeFileSync( outputPath, cssWithMap );
} else {
writeFileSync( outputPath, result.code );
}
};
/**
* Process all CSS files in a directory (await all bundles).
*
* @param {string} dir - Source directory
* @param {string} destDir - Destination directory
* @return {Promise<void>}
*/
const processDirectory = async ( dir, destDir ) => {
const files = getAllFiles( dir );
const tasks = files.map( ( file ) => {
const relativePath = path.relative( dir, file );
const outputPath = path.join(
destDir,
relativePath.replace( '.css', '.min.css' )
);
const outputDir = path.dirname( outputPath );
ensureDirectoryExistence( outputDir );
return processCSSFile( file, outputPath );
} );
await Promise.all( tasks );
};
// Kick off both directories (top-level await wrapper for Node ESM)
( async () => {
// Theme-level CSS (inject preload snippet if configured)
await processDirectory( paths.styles.srcDir, paths.styles.dest );
await processDirectory(
paths.styles.editorSrcDir,
paths.styles.editorDest
);
// Block-level CSS: compile each block's style.css and editor.css into build/ (no theme preload injection)
const blocksDir = path.join(
paths.assetsDir || path.join( process.cwd(), 'assets' ),
'blocks'
);
try {
const slugs = readdirSync( blocksDir, {
withFileTypes: true,
} )
.filter( ( d ) => d.isDirectory() )
.map( ( d ) => d.name );
for ( const slug of slugs ) {
const blockDir = path.join( blocksDir, slug );
const outDir = path.join( blockDir, 'build' );
if ( ! existsSync( outDir ) ) {
mkdirSync( outDir, { recursive: true } );
}
const styleIn = path.join( blockDir, 'style.css' );
const editorIn = path.join( blockDir, 'editor.css' );
if ( existsSync( styleIn ) ) {
await processCSSFile(
styleIn,
path.join( outDir, 'style.css' ),
false
);
}
if ( existsSync( editorIn ) ) {
await processCSSFile(
editorIn,
path.join( outDir, 'editor.css' ),
false
);
}
}
} catch {
// no blocks or cannot read; ignore
}
} )();