@eightshift/frontend-libs-tailwind 3.5.0 → 4.0.0-beta.2

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.
@@ -27,6 +27,7 @@ const addClasses = (value, breakpoints, output, isResponsive = false) => {
27
27
 
28
28
  if (Array.isArray(value)) {
29
29
  value.forEach((item) => addClasses(item, breakpoints, output, isResponsive));
30
+
30
31
  return;
31
32
  }
32
33
 
@@ -52,6 +53,7 @@ const addClasses = (value, breakpoints, output, isResponsive = false) => {
52
53
  .forEach((token) => {
53
54
  if (isResponsiveToken(token, breakpoints)) {
54
55
  output.add(token);
56
+
55
57
  return;
56
58
  }
57
59
 
@@ -71,12 +73,14 @@ const collectTailwindClasses = (value, allowedKeys, breakpoints, output) => {
71
73
 
72
74
  if (Array.isArray(value)) {
73
75
  value.forEach((item) => collectTailwindClasses(item, allowedKeys, breakpoints, output));
76
+
74
77
  return;
75
78
  }
76
79
 
77
80
  Object.entries(value).forEach(([key, item]) => {
78
81
  if (allowedKeys.has(key)) {
79
82
  addClasses(item, breakpoints, output, value.responsive === true);
83
+
80
84
  return;
81
85
  }
82
86
 
@@ -104,62 +108,37 @@ const runPreprocess = ({ projectDir, breakpoints, manifestGlob, outputFrontend,
104
108
 
105
109
  matches.forEach((filePath) => {
106
110
  const result = processManifest(filePath, breakpoints);
111
+
107
112
  result.frontend.forEach((cls) => frontend.add(cls));
108
113
  result.editor.forEach((cls) => editor.add(cls));
109
114
  });
110
115
 
116
+ fs.mkdirSync(path.dirname(outputFrontend), { recursive: true });
117
+ fs.mkdirSync(path.dirname(outputEditor), { recursive: true });
111
118
  fs.writeFileSync(outputFrontend, [...frontend].join(' '));
112
119
  fs.writeFileSync(outputEditor, [...editor].join(' '));
113
120
  };
114
121
 
115
122
  /**
116
- * Factory returning a webpack plugin that regenerates Tailwind class source
117
- * files before each build and on every manifest change in watch mode.
123
+ * Generate responsive Tailwind class source files without a bundler.
118
124
  *
119
- * @param {object} options
120
- * @param {string} options.projectDir Absolute path to the project root.
121
- * @param {string[]} [options.breakpoints] Tailwind breakpoint prefixes to expand. Defaults to `['sm', 'md']`.
122
- * @param {string} [options.manifestGlob] Glob (relative to `projectDir`) used to find manifests. Defaults to `src/**\/manifest.json`.
123
- * @param {{ frontend?: string, editor?: string }} [options.output] Override absolute output paths.
125
+ * @param {object} options Compiler options.
126
+ * @param {string} options.projectDir Absolute project directory.
127
+ * @param {string[]} [options.breakpoints] Responsive breakpoint prefixes.
128
+ * @param {string} [options.manifestGlob] Manifest glob relative to the project.
129
+ * @param {{ frontend?: string, editor?: string }} [options.output] Output paths.
130
+ * @returns {void}
124
131
  */
125
- export const esTwResponsiveCompiler = ({ projectDir, breakpoints = DEFAULT_BREAKPOINTS, manifestGlob = DEFAULT_MANIFEST_GLOB, output = {} } = {}) => {
132
+ export const generateResponsiveClasses = ({ projectDir, breakpoints = DEFAULT_BREAKPOINTS, manifestGlob = DEFAULT_MANIFEST_GLOB, output = {} } = {}) => {
126
133
  if (!projectDir) {
127
- throw new Error('esTwResponsiveCompiler: `projectDir` is required.');
134
+ throw new Error('generateResponsiveClasses: `projectDir` is required.');
128
135
  }
129
136
 
130
- const config = {
137
+ runPreprocess({
131
138
  projectDir,
132
139
  breakpoints,
133
140
  manifestGlob,
134
141
  outputFrontend: output.frontend ?? path.resolve(projectDir, 'es-tw-frontend-classes.txt'),
135
142
  outputEditor: output.editor ?? path.resolve(projectDir, 'es-tw-editor-classes.txt'),
136
- };
137
-
138
- const run = (label) => {
139
- console.log(`🔄 ${label}`);
140
- try {
141
- runPreprocess(config);
142
- console.log('✅ Done!');
143
- } catch (error) {
144
- console.error('❌ Failed. ', error);
145
- }
146
- };
147
-
148
- return {
149
- apply(compiler) {
150
- compiler.hooks.beforeRun.tap('EsTwResponsiveCompiler', () => {
151
- run('Generating Tailwind manifest class sources');
152
- });
153
-
154
- compiler.hooks.watchRun.tapAsync('EsTwResponsiveCompiler', ({ modifiedFiles }, callback) => {
155
- const manifestChanged = modifiedFiles && [...modifiedFiles].some((file) => file.includes('manifest.json'));
156
-
157
- if (manifestChanged) {
158
- run('A manifest was modified, re-running Tailwind manifest class generation');
159
- }
160
-
161
- callback();
162
- });
163
- },
164
- };
143
+ });
165
144
  };
package/bun/ssr.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+
4
+ /** Discover SSR entries by their block/component directory name. */
5
+ export async function discoverSsrEntries({ root, pattern = 'src/**/assets-ssr/ssr.{js,mjs}' }) {
6
+ if (typeof root !== 'string' || !root || typeof pattern !== 'string' || !pattern) {
7
+ throw new TypeError('Expected root and a valid SSR glob pattern');
8
+ }
9
+
10
+ const entries = new Map();
11
+
12
+ for await (const file of new Bun.Glob(pattern).scan({ cwd: resolve(root), onlyFiles: true })) {
13
+ const name = basename(dirname(dirname(file)));
14
+
15
+ if (entries.has(name)) {
16
+ throw new Error(`Duplicate SSR entry name: ${name}`);
17
+ }
18
+
19
+ entries.set(name, resolve(root, file));
20
+ }
21
+
22
+ if (!entries.size) {
23
+ throw new Error('No SSR entries found.');
24
+ }
25
+
26
+ return new Map([...entries].sort(([a], [b]) => a.localeCompare(b)));
27
+ }
28
+
29
+ /** Treat CSS imports as source text, matching the theme SSR build. */
30
+ export function ssrCssAsText() {
31
+ return {
32
+ name: 'css-as-source',
33
+ setup(build) {
34
+ build.onLoad({ filter: /\.css$/ }, async ({ path }) => ({ contents: await readFile(path, 'utf8'), loader: 'text' }));
35
+ },
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Build discovered SSR entries as individual Node CJS bundles. Paths are
41
+ * relative to root unless absolute. Caller plugins run before the CSS plugin;
42
+ * pass cssAsText: false to disable it. write: false returns in-memory outputs.
43
+ */
44
+ export async function buildSsr({ root, outdir, pattern, mode = 'development', plugins = [], cssAsText = true, write = true }) {
45
+ if (typeof root !== 'string' || !root || typeof outdir !== 'string' || !outdir || !['development', 'production'].includes(mode) || !Array.isArray(plugins) || typeof cssAsText !== 'boolean' || typeof write !== 'boolean') {
46
+ throw new TypeError('Invalid SSR build options');
47
+ }
48
+
49
+ const directory = resolve(root, outdir);
50
+ const entries = await discoverSsrEntries({ root, pattern });
51
+ const outputs = [];
52
+
53
+ for (const [name, entrypoint] of entries) {
54
+ const result = await Bun.build({
55
+ entrypoints: [entrypoint],
56
+ outdir: directory,
57
+ write: false,
58
+ naming: `${name}.js`,
59
+ target: 'node',
60
+ format: 'cjs',
61
+ splitting: false,
62
+ minify: mode === 'production',
63
+ sourcemap: 'none',
64
+ loader: { '.js': 'jsx' },
65
+ define: { 'process.env.NODE_ENV': JSON.stringify(mode) },
66
+ plugins: [...plugins, ...(cssAsText ? [ssrCssAsText()] : [])],
67
+ });
68
+
69
+ if (!result.success) {
70
+ throw new AggregateError(result.logs, `SSR build failed: ${name}`);
71
+ }
72
+
73
+ if (result.outputs.length !== 1 || result.outputs[0].kind !== 'entry-point') {
74
+ throw new Error(`Unexpected SSR output count or kind for ${name}: ${result.outputs.length}`);
75
+ }
76
+
77
+ outputs.push({ name, entrypoint, path: resolve(directory, `${name}.js`), output: result.outputs[0], logs: result.logs });
78
+ }
79
+
80
+ if (write) {
81
+ await mkdir(directory, { recursive: true });
82
+
83
+ for (const { path, output } of outputs) {
84
+ await writeFile(path, await output.arrayBuffer());
85
+ }
86
+ }
87
+
88
+ return { entries, outputs };
89
+ }
@@ -0,0 +1,481 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { link, mkdir, readFile, unlink } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { defineBuild } from './index.mjs';
6
+ import { clearBuildDirectory } from './build.mjs';
7
+ import { generateThemeDiscovery, generateThemeImporters, themeDiscoveryPlugin } from './theme-discovery.mjs';
8
+ import { processEightshiftCss } from './eightshift-css.mjs';
9
+ import { flattenAssets, packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
10
+ import { editorWorkerPlugin } from './media.mjs';
11
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
12
+ import { processCss } from './css.mjs';
13
+ import { buildSsr as buildDefaultSsr } from './ssr.mjs';
14
+
15
+ /**
16
+ * Define a conventional theme build. extraCss may be a hook or an array of
17
+ * { files, output?, keys?, href? }; package files use the `package:` prefix.
18
+ * Omitted output names use a content hash. Keys attach CSS to frontend importers.
19
+ * SSR is built when conventional entries exist; ssr: false disables it.
20
+ * optimizeImports controls Bun's package barrel optimization for browser builds.
21
+ * UI Components is optimized by default; pass [] to disable the explicit default.
22
+ * watch: false disables watching; an object overrides the safe watch defaults.
23
+ */
24
+ export function defineThemeBuild({
25
+ root,
26
+ publicPrefix: configuredPublicPrefix,
27
+ buildSsr,
28
+ createPlugins = () => [],
29
+ frontendStyles = [],
30
+ optimizeImports = ['@eightshift/ui-components'],
31
+ extraCss = async () => {},
32
+ aliases = {},
33
+ requireEditorWorker = false,
34
+ media = {},
35
+ watch = {},
36
+ entries,
37
+ editor,
38
+ responsive = {},
39
+ css,
40
+ discovery,
41
+ ssr,
42
+ publish,
43
+ } = {}) {
44
+ if (typeof root !== 'string' || !root) {
45
+ throw new TypeError('root must be a non-empty string');
46
+ }
47
+
48
+ if (typeof createPlugins !== 'function') {
49
+ throw new TypeError('createPlugins must be a function');
50
+ }
51
+
52
+ if (!Array.isArray(optimizeImports) || optimizeImports.some((name) => typeof name !== 'string' || !name.trim())) {
53
+ throw new TypeError('optimizeImports must be an array of package names');
54
+ }
55
+
56
+ if (extraCss !== false && typeof extraCss !== 'function' && !Array.isArray(extraCss)) {
57
+ throw new TypeError('extraCss must be false, a function, or an array');
58
+ }
59
+
60
+ if (watch !== false && (!watch || typeof watch !== 'object' || Array.isArray(watch))) {
61
+ throw new TypeError('watch must be false or an object');
62
+ }
63
+
64
+ for (const [name, value] of Object.entries({ css, discovery, ssr, publish })) {
65
+ if (value !== undefined && value !== false && typeof value !== 'function') {
66
+ throw new TypeError(`${name} must be false or a function`);
67
+ }
68
+ }
69
+
70
+ if (buildSsr !== undefined && typeof buildSsr !== 'function') {
71
+ throw new TypeError('buildSsr must be a function');
72
+ }
73
+
74
+ if (ssr !== undefined && buildSsr !== undefined) {
75
+ throw new TypeError('Use either ssr or buildSsr, not both');
76
+ }
77
+
78
+ if (entries !== undefined && (!entries || typeof entries !== 'object' || Array.isArray(entries) || !Object.keys(entries).length)) {
79
+ throw new TypeError('entries must contain named entrypoints');
80
+ }
81
+
82
+ if (editor !== undefined && editor !== false && (!editor || typeof editor !== 'object' || Array.isArray(editor))) {
83
+ throw new TypeError('editor must be false or an object');
84
+ }
85
+
86
+ if (responsive !== false && (!responsive || typeof responsive !== 'object' || Array.isArray(responsive))) {
87
+ throw new TypeError('responsive must be false or an object');
88
+ }
89
+
90
+ if (responsive === false && css === undefined) {
91
+ throw new TypeError('Default CSS requires responsive generation; configure css or enable responsive');
92
+ }
93
+
94
+ if (publish === undefined && css === false) {
95
+ throw new TypeError('Default publication requires CSS; configure publish or css');
96
+ }
97
+
98
+ if (publish === undefined && editor === false) {
99
+ throw new TypeError('Default publication requires an editor; configure publish or editor');
100
+ }
101
+
102
+ if (publish === undefined && entries && (!entries.frontend || !entries.admin || !entries.editor || Object.keys(entries).length !== 3)) {
103
+ throw new TypeError('Default publication requires frontend, admin, and editor entries');
104
+ }
105
+
106
+ if (publish === undefined && editor && editor.entry !== 'editor') {
107
+ throw new TypeError('Default publication requires editor.entry to be editor');
108
+ }
109
+
110
+ if (!Array.isArray(frontendStyles)) {
111
+ throw new TypeError('frontendStyles must be an array');
112
+ }
113
+
114
+ const cssDefinitions = Array.isArray(extraCss) ? extraCss : [];
115
+ const cssNames = new Set();
116
+
117
+ for (const item of cssDefinitions) {
118
+ if (
119
+ !item ||
120
+ typeof item !== 'object' ||
121
+ (item.output !== undefined && (typeof item.output !== 'string' || !/^[\w.-]+\.css$/.test(item.output) || item.output.startsWith('.'))) ||
122
+ !Array.isArray(item.files) ||
123
+ !item.files.length ||
124
+ (item.keys !== undefined && (!Array.isArray(item.keys) || !item.keys.length || item.keys.some((key) => typeof key !== 'string' || !key))) ||
125
+ (item.href !== undefined && (typeof item.href !== 'string' || !item.href))
126
+ ) {
127
+ throw new TypeError('Invalid extraCss definition');
128
+ }
129
+
130
+ if (item.output && (cssNames.has(item.output) || ['applicationBlocksFrontend.css', 'applicationBlocksEditor.css', 'applicationAdmin.css'].includes(item.output))) {
131
+ throw new TypeError(`Duplicate CSS output: ${item.output}`);
132
+ }
133
+
134
+ if (item.output) {
135
+ cssNames.add(item.output);
136
+ }
137
+ }
138
+
139
+ if (discovery !== undefined && (frontendStyles.length || cssDefinitions.some(({ keys }) => keys))) {
140
+ throw new TypeError('frontend styles require default discovery');
141
+ }
142
+
143
+ if (!media || typeof media !== 'object' || Array.isArray(media) || Object.keys(media).some((key) => key !== 'editorWorker')) {
144
+ throw new TypeError('Invalid media options');
145
+ }
146
+
147
+ if (media.editorWorker !== undefined && media.editorWorker !== false && typeof media.editorWorker !== 'function') {
148
+ throw new TypeError('media.editorWorker must be false or a plugin factory');
149
+ }
150
+
151
+ const wpRoot = process.env.EIGHTSHIFT_WP_ROOT ? resolve(process.env.EIGHTSHIFT_WP_ROOT) : resolve(root, '../../..');
152
+ const themePath = relative(wpRoot, resolve(root));
153
+ let publicPath = configuredPublicPrefix ?? process.env.EIGHTSHIFT_PUBLIC_PREFIX;
154
+ if (publicPath === undefined) {
155
+ if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
156
+ throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
157
+ }
158
+ publicPath = `/${themePath.split(sep).join('/')}/public/`;
159
+ }
160
+ if (typeof publicPath !== 'string' || !publicPath.startsWith('/') || publicPath.startsWith('//') || !publicPath.endsWith('/') || publicPath.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPath) || publicPath.split('/').some((part) => part === '.' || part === '..')) {
161
+ throw new Error('publicPrefix must be a root-relative URL path ending in /');
162
+ }
163
+ let outdir;
164
+ let editorWorker;
165
+ const makePreset = async ({ sourcemaps }) => {
166
+ const versionFile = resolve(wpRoot, 'wp-includes/version.php');
167
+ let versionSource;
168
+ try {
169
+ versionSource = await readFile(versionFile, 'utf8');
170
+ } catch (error) {
171
+ throw new Error(`Cannot read WordPress version at ${versionFile}. Set EIGHTSHIFT_WP_ROOT to a WordPress installation.`, { cause: error });
172
+ }
173
+ const version = versionSource.match(/^\s*\$wp_version\s*=\s*['"](\d+)\.(\d+)(?:\.(\d+))?(['"]);/m);
174
+ if (!version) {
175
+ throw new Error(`Cannot determine a stable WordPress version from ${versionFile}; WordPress 7.0 or newer is required.`);
176
+ }
177
+ if (Number(version[1]) < 7) {
178
+ throw new Error(`WordPress 7.0 or newer is required; found ${version[1]}.${version[2]}${version[3] === undefined ? '' : `.${version[3]}`}.`);
179
+ }
180
+
181
+ editorWorker = undefined;
182
+ const publicDir = resolve(root, 'public');
183
+ outdir = resolve(publicDir, '.build');
184
+ if (publish === undefined) {
185
+ await clearBuildDirectory(publicDir, root);
186
+ await mkdir(publicDir, { recursive: true });
187
+ } else {
188
+ await clearBuildDirectory(outdir, root);
189
+ }
190
+ const require = createRequire(resolve(root, 'package.json'));
191
+ const names = ['componentManifests', 'customManifests', 'customBlocks', 'customHooks', 'customTransforms', 'customDeprecations', 'customOverrides', 'variationManifests', 'customVariationManifests', 'variationOverrides', 'componentAdminAssets', 'customAdminAssets'];
192
+ const specs = [
193
+ ['componentManifests', 'components', /manifest\.json$/],
194
+ ['customManifests', 'custom', /manifest\.json$/],
195
+ ...['block', 'hooks', 'transforms', 'deprecations', 'overrides'].map((suffix, index) => [names[index + 2], 'custom', new RegExp(`-${suffix}.js$`)]),
196
+ ['componentAdminAssets', 'components', /assets-admin\/index\.js$/, 'lazy'],
197
+ ['customAdminAssets', 'custom', /assets-admin\/index\.js$/, 'lazy'],
198
+ ];
199
+ const entryNames = {
200
+ frontend: names.slice(0, 2),
201
+ admin: [names[0], names[1], names[10], names[11]],
202
+ };
203
+ const surfaces = Object.fromEntries(Object.entries(entryNames).map(([entry, selected]) => [entry, specs.filter(([name]) => selected.includes(name)).map(([name, directory, pattern, mode]) => ({ name, directory: `src/Blocks/${directory}`, pattern, mode }))]));
204
+ let frontendImporters;
205
+ const manifestReplacements = [
206
+ ["require.context('./../../components', true, /manifest\\.json$/)", 'componentManifests'],
207
+ ["require.context('./../../custom', true, /manifest\\.json$/)", 'customManifests'],
208
+ ];
209
+ let discoveryDir;
210
+ const discoveryPlugin = {
211
+ name: 'theme-discovery-setup',
212
+ setup(builder) {
213
+ themeDiscoveryPlugin({
214
+ root,
215
+ entries: [
216
+ {
217
+ path: 'src/Blocks/assets/scripts/application-blocks-frontend.js',
218
+ module: resolve(discoveryDir, 'frontend.mjs'),
219
+ imports: entryNames.frontend,
220
+ importStatement: "import { dynamicImport } from '@eightshift/frontend-libs-tailwind/scripts/helpers';",
221
+ prefix: frontendImporters,
222
+ replacements: [
223
+ ...manifestReplacements,
224
+ ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets/index.js`);', 'const importer = bunFrontendImporters[`${importBasePath}/${directory}`]; if (!importer) return Promise.reject(new Error("Missing frontend asset")); return importer();'],
225
+ ],
226
+ remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
227
+ },
228
+ {
229
+ path: 'src/Blocks/assets/scripts/application-admin.js',
230
+ module: resolve(discoveryDir, 'admin.mjs'),
231
+ imports: entryNames.admin,
232
+ importStatement: "import { dynamicImport } from '@eightshift/frontend-libs-tailwind/scripts/helpers';",
233
+ replacements: [
234
+ ...manifestReplacements,
235
+ ["require.context('./../../components', true, /assets-admin\\/index\\.js$/)", 'componentAdminAssets'],
236
+ ["require.context('./../../custom', true, /assets-admin\\/index\\.js$/)", 'customAdminAssets'],
237
+ ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets-admin/index.js`);', 'return assetContext(assetPath);'],
238
+ ],
239
+ remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
240
+ },
241
+ ],
242
+ }).setup(builder);
243
+ },
244
+ };
245
+ const pluginContext = {
246
+ root,
247
+ setEditorWorker: (worker) => {
248
+ editorWorker = worker;
249
+ },
250
+ getEditorWorker: () => editorWorker,
251
+ };
252
+ const callerPlugins = createPlugins(pluginContext);
253
+
254
+ if (!Array.isArray(callerPlugins)) {
255
+ throw new TypeError('createPlugins must return an array');
256
+ }
257
+
258
+ const workerFactory = media.editorWorker === undefined ? editorWorkerPlugin : media.editorWorker;
259
+ const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
260
+
261
+ if (discovery === undefined) {
262
+ plugins.push(allowPureJsxGrouping(discoveryPlugin));
263
+ } else if (discovery) {
264
+ const plugin = await discovery(pluginContext);
265
+
266
+ if (!plugin || typeof plugin.setup !== 'function') {
267
+ throw new TypeError('discovery must return a Bun plugin');
268
+ }
269
+
270
+ plugins.push(plugin);
271
+ }
272
+
273
+ return {
274
+ root,
275
+ outdir,
276
+ direct: true,
277
+ wpRoot,
278
+ entries: entries ?? { frontend: 'src/Blocks/assets/scripts/application-blocks-frontend.js', admin: 'src/Blocks/assets/scripts/application-admin.js', editor: 'src/Blocks/assets/scripts/application-blocks-editor.js' },
279
+ responsive,
280
+ editor: editor ?? {
281
+ entry: 'editor',
282
+ filename: 'applicationBlocksEditor.js',
283
+ discovery: {
284
+ filter: /application-blocks-editor\.js$/,
285
+ omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
286
+ },
287
+ },
288
+ css: async (context) => {
289
+ const { outdir: stage, responsive: generated } = context;
290
+
291
+ if (css === undefined) {
292
+ for (const surface of ['frontend', 'editor', 'admin']) {
293
+ const name = surface === 'admin' ? 'applicationAdmin' : `applicationBlocks${surface === 'frontend' ? 'Frontend' : 'Editor'}`;
294
+
295
+ await processEightshiftCss({ projectDir: root, surface, responsiveFile: generated[surface], outputFile: resolve(stage, 'css', `${name}.css`), production: true });
296
+ }
297
+ } else if (css) {
298
+ await css({ ...context, stage, require });
299
+ }
300
+
301
+ if (typeof extraCss === 'function') {
302
+ await extraCss({ root, stage, require });
303
+ }
304
+
305
+ const styles = [...frontendStyles];
306
+ const outputNames = new Set(cssNames);
307
+
308
+ for (const { output, files, keys, href } of cssDefinitions) {
309
+ const resolveFile = (file) => {
310
+ if (typeof file !== 'string' || !file) {
311
+ throw new TypeError('Invalid extraCss file');
312
+ }
313
+
314
+ return file.startsWith('package:') ? require.resolve(file.slice(8)) : isAbsolute(file) ? file : resolve(root, file);
315
+ };
316
+ const temporary = resolve(stage, 'css', `.extra-${randomUUID()}.css`);
317
+ const outputFile = output ? resolve(stage, 'css', output) : temporary;
318
+
319
+ await processCss({ projectDir: root, outputFile, files: files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) })), production: true });
320
+ let name = output;
321
+
322
+ if (!name) {
323
+ const hash = createHash('sha256')
324
+ .update(await readFile(temporary))
325
+ .digest('hex')
326
+ .slice(0, 20);
327
+
328
+ name = `extra-${hash}.css`;
329
+
330
+ if (outputNames.has(name)) {
331
+ throw new Error(`Duplicate CSS output: ${name}`);
332
+ }
333
+
334
+ outputNames.add(name);
335
+ await link(temporary, resolve(stage, 'css', name));
336
+ await unlink(temporary);
337
+ }
338
+
339
+ if (keys) {
340
+ styles.push({ keys, href: href ?? `../css/${name}` });
341
+ }
342
+ }
343
+
344
+ if (discovery === undefined) {
345
+ frontendImporters = await generateThemeImporters({
346
+ root,
347
+ glob: 'src/Blocks/{components,custom}/**/assets/index.js',
348
+ key: (file) => file.replace(/^src\/Blocks\//, '').replace(/\/assets\/index\.js$/, ''),
349
+ styles,
350
+ });
351
+ discoveryDir = resolve(stage, 'discovery');
352
+ await generateThemeDiscovery({ root, outputDir: discoveryDir, surfaces });
353
+ }
354
+ },
355
+ buildOptions: {
356
+ optimizeImports,
357
+ minify: true,
358
+ publicPath,
359
+ naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
360
+ sourcemap: sourcemaps ? 'external' : 'none',
361
+ loader: { '.js': 'jsx', '.svg': 'file' },
362
+ define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': '"library-release"' },
363
+ plugins,
364
+ },
365
+ };
366
+ };
367
+ const defaultPublish = async ({ result }) => {
368
+ const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
369
+
370
+ if (requireEditorWorker && !editorWorker) {
371
+ throw new Error('Missing editor worker');
372
+ }
373
+
374
+ const ssrDir = resolve(outdir, 'ssr/production');
375
+ const ssrNames = [];
376
+
377
+ if (ssr !== false) {
378
+ if (ssr || buildSsr) {
379
+ await (ssr ?? buildSsr)({ root, mode: 'production' });
380
+ }
381
+
382
+ for await (const file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root })) {
383
+ const name = file.split('/').at(-3);
384
+
385
+ if (ssrNames.includes(name)) {
386
+ throw new Error(`Duplicate SSR entry: ${name}`);
387
+ }
388
+
389
+ ssrNames.push(name);
390
+ }
391
+
392
+ if (ssrNames.length && !ssr && !buildSsr) {
393
+ await defaultSsr({ root, mode: 'production' });
394
+ }
395
+
396
+ if (!ssrNames.length && (ssr || buildSsr)) {
397
+ throw new Error('No SSR entries found');
398
+ }
399
+ }
400
+
401
+ const surfaces = { frontend: 'applicationBlocksFrontend', editor: 'applicationBlocksEditor', admin: 'applicationAdmin' };
402
+ const flatDir = resolve(outdir, 'flat');
403
+ const { rewrite } = await flattenAssets({
404
+ outdir,
405
+ flatDir,
406
+ extraSources: editorWorker ? { [`editor/editor-assets/${basename(editorWorker)}`]: editorWorker } : {},
407
+ editorEntry: result.entries.editor.entry,
408
+ editorScript,
409
+ });
410
+ // Webpack exposed standalone images by basename, even when not imported by JS.
411
+ const standaloneAssets = new Map();
412
+
413
+ for await (const file of new Bun.Glob('src/Blocks/assets/images/**/*').scan({ cwd: root, onlyFiles: true })) {
414
+ const name = basename(file);
415
+
416
+ if (standaloneAssets.has(name)) {
417
+ throw new Error(`Duplicate standalone asset: ${name}`);
418
+ }
419
+
420
+ standaloneAssets.set(name, resolve(root, file));
421
+ }
422
+
423
+ const entries = Object.entries(surfaces).map(([surface, name]) => {
424
+ const entry = result.entries[surface];
425
+ const script = surface === 'editor' ? rewrite(editorScript, entry.entry) : undefined;
426
+
427
+ console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
428
+
429
+ return {
430
+ name,
431
+ entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry),
432
+ style: `${name}.css`,
433
+ dependencies: entry.dependencies,
434
+ ...(script && { script }),
435
+ ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
436
+ };
437
+ });
438
+ const { release, version, manifest } = await packageFlatRelease({
439
+ root: resolve(root, 'public'),
440
+ outputDirectory: resolve(root, 'public'),
441
+ removeIntermediates: true,
442
+ flatDir,
443
+ entries,
444
+ ssrDir,
445
+ ssrNames,
446
+ standaloneAssets,
447
+ aliases,
448
+ });
449
+
450
+ await publishFlatRelease({ root, wpRoot, release, manifest, version, direct: true, publicPrefix: publicPath });
451
+ await clearBuildDirectory(outdir, root);
452
+ };
453
+ const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
454
+ const customSsr = ssr ?? buildSsr;
455
+ const definition = defineBuild({
456
+ root,
457
+ preset: makePreset,
458
+ ssr:
459
+ publish !== undefined && ssr !== false
460
+ ? async (state) => {
461
+ if (customSsr) {
462
+ return customSsr({ ...state, mode: 'production' });
463
+ }
464
+
465
+ for await (const _file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root, onlyFiles: true })) {
466
+ return defaultSsr({ root, mode: 'production' });
467
+ }
468
+ }
469
+ : undefined,
470
+ publish: publish === undefined ? defaultPublish : publish || undefined,
471
+ watch: { sources: ['src', 'build', 'eightshift.build.mjs', 'package.json', 'bun.lock', 'tailwind.css', 'tailwind-editor.css', 'tailwind-frontend.css', 'color-themes.css'], ignored: ['.git', '.bun-pilot', 'node_modules', 'vendor', 'vendor-prefixed', 'public'], ...(watch || {}) },
472
+ });
473
+
474
+ if (watch === false) {
475
+ definition.watch = () => {
476
+ throw new Error('Watching is disabled');
477
+ };
478
+ }
479
+
480
+ return definition;
481
+ }