@eightshift/frontend-libs-tailwind 4.0.0-beta.1 → 4.0.0-beta.3

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.
@@ -50,7 +50,7 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
50
50
  targetsByName.set(name, targets);
51
51
  }
52
52
  const unusualTargets = [...targetsByName].filter(([name]) => !/^[\w.@+-]+$/.test(name)).flatMap(([, targets]) => targets);
53
- const rewrite = (input, path) => {
53
+ const rewriteLegacy = (input, path) => {
54
54
  let source = input;
55
55
  const candidates = new Set(unusualTargets);
56
56
 
@@ -80,6 +80,8 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
80
80
  for (const value of variants) {
81
81
  for (const quote of ['"', "'"]) {
82
82
  source = source.replaceAll(`${quote}${value}${quote}`, `${quote}./${basename(target)}${quote}`);
83
+ source = source.replaceAll(`${quote}${value}?`, `${quote}./${basename(target)}?`);
84
+ source = source.replaceAll(`${quote}${value}#`, `${quote}./${basename(target)}#`);
83
85
  }
84
86
 
85
87
  source = source.replaceAll(`sourceMappingURL=${value}`, `sourceMappingURL=./${basename(target)}`);
@@ -89,6 +91,66 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
89
91
  return source;
90
92
  };
91
93
 
94
+ const referencePatterns = new Map();
95
+ const rewrite = (input, path) => {
96
+ // Keep the existing source-map comment handling for map-bearing files.
97
+ if (input.includes('sourceMappingURL=')) {
98
+ return rewriteLegacy(input, path);
99
+ }
100
+
101
+ const directory = posix.dirname(path);
102
+ const editorPath = path.startsWith('editor/');
103
+ const cacheKey = `${directory}:${editorPath}`;
104
+ let cached = referencePatterns.get(cacheKey);
105
+
106
+ if (!cached) {
107
+ const references = new Map();
108
+
109
+ for (const target of sources.keys()) {
110
+ const reference = posix.relative(directory, target);
111
+ if (!reference) {
112
+ continue;
113
+ }
114
+
115
+ const variants = [reference];
116
+ if (!reference.startsWith('.')) {
117
+ variants.push(`./${reference}`);
118
+ }
119
+ if (target.startsWith('editor/editor-assets/') || (target.startsWith('editor/') && editorPath)) {
120
+ variants.push(target.slice('editor/'.length));
121
+ }
122
+ for (const value of variants) {
123
+ references.set(value, `./${basename(target)}`);
124
+ }
125
+ }
126
+
127
+ const alternatives = [...references.keys()].map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
128
+ let pattern;
129
+ let fallback = alternatives.length > 200000;
130
+
131
+ if (alternatives && !fallback) {
132
+ try {
133
+ pattern = new RegExp(`(["'])(?:${alternatives})(?=\\1|[?#])`, 'g');
134
+ } catch (error) {
135
+ if (!(error instanceof SyntaxError)) {
136
+ throw error;
137
+ }
138
+ fallback = true;
139
+ }
140
+ }
141
+ cached = { references, pattern, fallback };
142
+ referencePatterns.set(cacheKey, cached);
143
+ }
144
+
145
+ if (cached.fallback) {
146
+ return rewriteLegacy(input, path);
147
+ }
148
+ if (!cached.pattern) {
149
+ return input;
150
+ }
151
+ return input.replace(cached.pattern, (match, quote) => `${quote}${cached.references.get(match.slice(1))}`);
152
+ };
153
+
92
154
  const contentFor = async (path) => {
93
155
  const content = await readFile(sources.get(path));
94
156
  return /\.(?:js|css|map)$/.test(basename(path)) ? Buffer.from(rewrite(content.toString(), path)) : content;
@@ -129,8 +191,25 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
129
191
  }
130
192
 
131
193
  /** Package flattened files, optional SSR files and standalone assets. */
132
- export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, outputDirectory }) {
133
- const files = [];
194
+ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, extraFiles = [], retain = [], previousPublic, outputDirectory, removeIntermediates = false }) {
195
+ if (!Array.isArray(extraFiles) || !Array.isArray(retain) || (retain.length && !previousPublic)) {
196
+ throw new TypeError('extraFiles and retain must be arrays; retention requires previousPublic');
197
+ }
198
+ const files = [...extraFiles];
199
+ for (const name of retain) {
200
+ pathName(name);
201
+ let source = resolve(previousPublic);
202
+ for (const part of name.split('/')) {
203
+ source = resolve(source, part);
204
+ if ((await lstat(source)).isSymbolicLink()) {
205
+ throw new Error(`Symlink in retained path: ${name}`);
206
+ }
207
+ }
208
+ if (!(await lstat(source)).isFile()) {
209
+ throw new Error(`Retained path must be an exact file: ${name}`);
210
+ }
211
+ files.push({ source, destination: name });
212
+ }
134
213
 
135
214
  for (const name of await readdir(flatDir)) {
136
215
  files.push({ source: resolve(flatDir, name), destination: name });
@@ -155,7 +234,13 @@ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNa
155
234
  extraAliases[name] = name;
156
235
  }
157
236
 
158
- return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory });
237
+ const omitted = removeIntermediates ? entries.flatMap((entry) => [entry.style, ...(entry.script !== undefined ? [entry.entry] : [])]) : [];
238
+ for (const entry of entries) {
239
+ if (entry.script === undefined && omitted.includes(entry.entry)) {
240
+ throw new Error(`Cannot omit a script bootstrap target: ${entry.entry}`);
241
+ }
242
+ }
243
+ return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory, omit: [...new Set(omitted)] });
159
244
  }
160
245
 
161
246
  /** Publish a flat release and synchronize an existing PHP asset cache.
@@ -225,7 +310,7 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
225
310
  throw new Error(`Unsupported release output: ${name}`);
226
311
  }
227
312
 
228
- if (name !== 'manifest.json' && name !== 'ssr' && !(direct && name === '.build') && !Object.hasOwn(result, name)) {
313
+ if (entry.isFile() && name !== 'manifest.json' && name !== 'ssr' && !(direct && name === '.build') && !Object.hasOwn(result, name)) {
229
314
  result[name] = name;
230
315
  }
231
316
  }
@@ -336,7 +421,11 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
336
421
  };
337
422
 
338
423
  if (hadPublic) {
339
- await removeTree(backup);
424
+ try {
425
+ await removeTree(backup);
426
+ } catch (error) {
427
+ console.warn(`Build published, but backup cleanup failed at ${backup}:`, error);
428
+ }
340
429
  }
341
430
 
342
431
  return { publicDir, manifest: publicManifest, version };
package/bun/index.mjs CHANGED
@@ -33,15 +33,34 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
33
33
  throw new TypeError('watch.ignore must be a function');
34
34
  }
35
35
 
36
+ const validateOptions = (options) => {
37
+ if (Object.hasOwn(options, 'timings')) {
38
+ throw new Error('The timings option is no longer supported');
39
+ }
40
+ if (options.quiet && options.verbose) {
41
+ throw new Error('quiet and verbose cannot be combined');
42
+ }
43
+ };
44
+
36
45
  root = resolve(root);
37
46
  let active;
38
47
  const outputs = new Set();
39
48
  const run = async (options = {}) => {
49
+ validateOptions(options);
40
50
  if (active) {
41
51
  throw new Error('A build is already running');
42
52
  }
43
53
 
54
+ const started = performance.now();
55
+ const report = (message, detail = false) => {
56
+ if (!options.quiet && (!detail || options.verbose)) {
57
+ console.log(`[eightshift-build] ${message}`);
58
+ }
59
+ };
60
+
44
61
  active = (async () => {
62
+ report('Starting build…');
63
+ report('Preparing build…', true);
45
64
  const context = { ...options, root };
46
65
  const configured = typeof preset === 'function' ? await preset(context) : preset;
47
66
  outputs.clear();
@@ -53,17 +72,21 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
53
72
  }
54
73
  outputs.add(output);
55
74
  }
75
+ report('Building browser assets…');
56
76
  const result = await buildPreset({ ...configured, root });
57
77
  const state = { ...context, result };
58
78
 
59
79
  if (ssr) {
80
+ report('Building SSR assets…');
60
81
  state.ssr = await ssr(state);
61
82
  }
62
83
 
63
84
  if (publish) {
85
+ report('Running publication…');
64
86
  state.publication = await publish(state);
65
87
  }
66
88
 
89
+ report(`Build completed in ${((performance.now() - started) / 1000).toFixed(2)}s.`);
67
90
  return state;
68
91
  })();
69
92
 
@@ -77,6 +100,7 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
77
100
  return {
78
101
  build: run,
79
102
  watch: (options = {}) => {
103
+ validateOptions(options);
80
104
  if ((ssr || publish) && watch.sources === undefined && !watch.ignored?.length) {
81
105
  throw new Error('Watch builds with ssr or publish callbacks require explicit watch.sources or watch.ignored');
82
106
  }
package/bun/media.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { basename, dirname, resolve } from 'node:path';
3
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
3
4
 
4
5
  /**
5
6
  * Adapt the published UI Components smart-image worker for flat theme releases.
@@ -11,7 +12,7 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
11
12
  throw new TypeError('Worker callbacks are required');
12
13
  }
13
14
 
14
- return {
15
+ return allowPureJsxGrouping({
15
16
  name: 'eightshift-editor-worker-url',
16
17
  setup(builder) {
17
18
  builder.onLoad({ filter: /[/\\]smart-image[/\\]smart-image\.js$/ }, async ({ path }) => {
@@ -45,5 +46,5 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
45
46
  return { contents: source.replace(pattern, `new URL(${JSON.stringify(`editor-assets/${basename(worker)}`)}, ${base})`), loader: 'js', resolveDir: dirname(path) };
46
47
  });
47
48
  },
48
- };
49
+ });
49
50
  }
@@ -0,0 +1,11 @@
1
+ const pureJsxCompatible = new WeakMap();
2
+
3
+ // Only audited built-ins may participate; plugin names are not a trust boundary.
4
+ export function allowPureJsxGrouping(plugin) {
5
+ pureJsxCompatible.set(plugin, plugin.setup);
6
+ return plugin;
7
+ }
8
+
9
+ export function supportsPureJsxGrouping(plugin) {
10
+ return pureJsxCompatible.has(plugin) && pureJsxCompatible.get(plugin) === plugin.setup;
11
+ }
package/bun/preset.mjs CHANGED
@@ -31,8 +31,10 @@ const feature = (value, keys, label) => {
31
31
  * Set wordpress: false to bundle dependencies instead of externalizing them.
32
32
  * Configure Bun target, format, naming and splitting via buildOptions.
33
33
  * Entry points, staging output and write mode are controlled by build.
34
- * editor: { entry, filename, chunkDir, scriptUrlIdentifier, discovery, lazy }
35
- * makes the named entry a synchronous classic script with lazy ESM chunks.
34
+ * editor: { entry, filename, chunkDir, scriptUrlIdentifier, discovery, lazy, sharing, pureJsxGroups }
35
+ * builds classic registration with lazy ESM chunks by default.
36
+ * sharing: 'native' bundles lazy targets together; the default is 'independent'.
37
+ * sharing: 'unified' also moves registration to ESM and requires readiness integration.
36
38
  * discovery configures eightshiftDiscovery; lazy configures editorLazyImports.
37
39
  * Both are opt-in, and all filenames and discovery behavior are overridable.
38
40
  */
@@ -66,7 +68,7 @@ export function createPreset(options = {}) {
66
68
  }
67
69
  }
68
70
 
69
- const editor = feature(options.editor, ['entry', 'chunkDir', 'filename', 'scriptUrlIdentifier', 'discovery', 'lazy'], 'editor');
71
+ const editor = feature(options.editor, ['entry', 'chunkDir', 'filename', 'scriptUrlIdentifier', 'discovery', 'lazy', 'sharing', 'pureJsxGroups'], 'editor');
70
72
  const discovery = feature(options.discovery, ['output', 'definitions'], 'discovery');
71
73
  const responsive = feature(options.responsive, ['breakpoints', 'manifestGlob', 'output'], 'responsive');
72
74
 
package/bun/release.mjs CHANGED
@@ -39,13 +39,15 @@ const releasePath = (value) => {
39
39
  *
40
40
  * files: [{ source, destination }] copies files or directory trees.
41
41
  * entries: [{ name, entry, style, dependencies, script? }] generates the root
42
- * scripts and WordPress asset metadata. script supplies synchronous editor code;
42
+ * scripts and WordPress asset metadata. script supplies the entry wrapper code;
43
43
  * otherwise a dynamic-import bootstrap loads entry relative to the root script.
44
+ * Unified editor scripts declare format: 'module', readiness: 'eightshift-editor-v1';
45
+ * their static-import wrapper must be loaded by matching module-aware PHP integration.
44
46
  * aliases maps additional flat manifest keys to packaged paths.
45
47
  * Returns { release, version, manifest }. A failed staging directory is retained.
46
48
  * outputDirectory writes directly to an existing directory instead of staging.
47
49
  */
48
- export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory }) {
50
+ export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory, omit = [] }) {
49
51
  if (typeof root !== 'string' || !root || !Array.isArray(files) || !Array.isArray(entries) || !entries.length || !aliases || typeof aliases !== 'object' || Array.isArray(aliases)) {
50
52
  throw new TypeError('Expected root, files, entries and optional aliases');
51
53
  }
@@ -117,13 +119,23 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
117
119
  throw new TypeError(`Invalid script for ${entry.name}`);
118
120
  }
119
121
 
122
+ if (entry.format !== undefined && entry.format !== 'module') {
123
+ throw new TypeError(`Unsupported script format for ${entry.name}`);
124
+ }
125
+ if (entry.format === 'module' && (entry.readiness !== 'eightshift-editor-v1' || entry.script === undefined)) {
126
+ throw new TypeError(`Module entry ${entry.name} requires an explicit script and readiness contract`);
127
+ }
128
+ if (entry.readiness !== undefined && entry.format !== 'module') {
129
+ throw new TypeError(`Readiness requires a module entry: ${entry.name}`);
130
+ }
131
+
120
132
  const script = entry.script ?? `(() => { const url = new URL(${JSON.stringify(target)}, document.currentScript.src); import(url.href).catch((error) => console.error(${JSON.stringify(`Failed to load ${entry.name}:`)}, error)); })();\n`;
121
133
 
122
134
  if (scripts.has(entry.name)) {
123
135
  throw new Error(`Duplicate entry: ${entry.name}`);
124
136
  }
125
137
 
126
- scripts.set(entry.name, { script, dependencies: entry.dependencies });
138
+ scripts.set(entry.name, { script, dependencies: entry.dependencies, ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}) });
127
139
  const scriptName = `${entry.name}-${digest(script)}.js`;
128
140
  const styleBytes = contents.get(style);
129
141
  const styleName = `${entry.name}-${digest(styleBytes)}.css`;
@@ -151,12 +163,25 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
151
163
  setManifest(key, value);
152
164
  }
153
165
 
166
+ if (!Array.isArray(omit)) {
167
+ throw new TypeError('omit must be an array');
168
+ }
169
+ for (const path of omit) {
170
+ releasePath(path);
171
+ if (Object.values(manifest).includes(path)) {
172
+ throw new Error(`Cannot omit manifest target: ${path}`);
173
+ }
174
+ if (!contents.delete(path)) {
175
+ throw new Error(`Cannot omit missing release file: ${path}`);
176
+ }
177
+ }
178
+
154
179
  const inventory = Object.fromEntries([...contents].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, bytes]) => [path, digest(bytes)]));
155
180
  const version = digest(JSON.stringify({ format: 1, inventory, scripts: [...scripts].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), manifest }));
156
181
 
157
- for (const [name, { script, dependencies }] of scripts) {
182
+ for (const [name, { script, dependencies, format, readiness }] of scripts) {
158
183
  add(manifest[`${name}.js`], Buffer.from(script));
159
- add(`${name}.asset.json`, Buffer.from(`${JSON.stringify({ dependencies, version }, null, 2)}\n`));
184
+ add(`${name}.asset.json`, Buffer.from(`${JSON.stringify({ dependencies, version, ...(format === 'module' ? { format, readiness } : {}) }, null, 2)}\n`));
160
185
  }
161
186
 
162
187
  add('manifest.json', Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`));
@@ -8,6 +8,7 @@ import { generateThemeDiscovery, generateThemeImporters, themeDiscoveryPlugin }
8
8
  import { processEightshiftCss } from './eightshift-css.mjs';
9
9
  import { flattenAssets, packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
10
10
  import { editorWorkerPlugin } from './media.mjs';
11
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
11
12
  import { processCss } from './css.mjs';
12
13
  import { buildSsr as buildDefaultSsr } from './ssr.mjs';
13
14
 
@@ -16,6 +17,8 @@ import { buildSsr as buildDefaultSsr } from './ssr.mjs';
16
17
  * { files, output?, keys?, href? }; package files use the `package:` prefix.
17
18
  * Omitted output names use a content hash. Keys attach CSS to frontend importers.
18
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.
19
22
  * watch: false disables watching; an object overrides the safe watch defaults.
20
23
  */
21
24
  export function defineThemeBuild({
@@ -24,8 +27,10 @@ export function defineThemeBuild({
24
27
  buildSsr,
25
28
  createPlugins = () => [],
26
29
  frontendStyles = [],
30
+ optimizeImports = ['@eightshift/ui-components'],
27
31
  extraCss = async () => {},
28
32
  aliases = {},
33
+ publication = async () => ({}),
29
34
  requireEditorWorker = false,
30
35
  media = {},
31
36
  watch = {},
@@ -45,6 +50,10 @@ export function defineThemeBuild({
45
50
  throw new TypeError('createPlugins must be a function');
46
51
  }
47
52
 
53
+ if (!Array.isArray(optimizeImports) || optimizeImports.some((name) => typeof name !== 'string' || !name.trim())) {
54
+ throw new TypeError('optimizeImports must be an array of package names');
55
+ }
56
+
48
57
  if (extraCss !== false && typeof extraCss !== 'function' && !Array.isArray(extraCss)) {
49
58
  throw new TypeError('extraCss must be false, a function, or an array');
50
59
  }
@@ -172,13 +181,8 @@ export function defineThemeBuild({
172
181
 
173
182
  editorWorker = undefined;
174
183
  const publicDir = resolve(root, 'public');
175
- outdir = resolve(publicDir, '.build');
176
- if (publish === undefined) {
177
- await clearBuildDirectory(publicDir, root);
178
- await mkdir(publicDir, { recursive: true });
179
- } else {
180
- await clearBuildDirectory(outdir, root);
181
- }
184
+ outdir = publish === undefined ? resolve(root, '.bun-pilot/theme-build') : resolve(publicDir, '.build');
185
+ await clearBuildDirectory(outdir, root);
182
186
  const require = createRequire(resolve(root, 'package.json'));
183
187
  const names = ['componentManifests', 'customManifests', 'customBlocks', 'customHooks', 'customTransforms', 'customDeprecations', 'customOverrides', 'variationManifests', 'customVariationManifests', 'variationOverrides', 'componentAdminAssets', 'customAdminAssets'];
184
188
  const specs = [
@@ -251,7 +255,7 @@ export function defineThemeBuild({
251
255
  const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
252
256
 
253
257
  if (discovery === undefined) {
254
- plugins.push(discoveryPlugin);
258
+ plugins.push(allowPureJsxGrouping(discoveryPlugin));
255
259
  } else if (discovery) {
256
260
  const plugin = await discovery(pluginContext);
257
261
 
@@ -345,6 +349,7 @@ export function defineThemeBuild({
345
349
  }
346
350
  },
347
351
  buildOptions: {
352
+ optimizeImports,
348
353
  minify: true,
349
354
  publicPath,
350
355
  naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
@@ -355,7 +360,7 @@ export function defineThemeBuild({
355
360
  },
356
361
  };
357
362
  };
358
- const defaultPublish = async ({ result }) => {
363
+ const defaultPublish = async ({ result, verbose, quiet }) => {
359
364
  const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
360
365
 
361
366
  if (requireEditorWorker && !editorWorker) {
@@ -367,7 +372,7 @@ export function defineThemeBuild({
367
372
 
368
373
  if (ssr !== false) {
369
374
  if (ssr || buildSsr) {
370
- await (ssr ?? buildSsr)({ root, mode: 'production' });
375
+ await (ssr ?? buildSsr)({ root, mode: 'production', outdir: ssrDir });
371
376
  }
372
377
 
373
378
  for await (const file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root })) {
@@ -415,22 +420,54 @@ export function defineThemeBuild({
415
420
  const entry = result.entries[surface];
416
421
  const script = surface === 'editor' ? rewrite(editorScript, entry.entry) : undefined;
417
422
 
418
- console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
423
+ if (verbose && !quiet) {
424
+ console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
425
+ }
419
426
 
420
- return { name, entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry), style: `${name}.css`, dependencies: entry.dependencies, ...(script && { script }) };
427
+ return {
428
+ name,
429
+ entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry),
430
+ style: `${name}.css`,
431
+ dependencies: entry.dependencies,
432
+ ...(script && { script }),
433
+ ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
434
+ };
421
435
  });
436
+ const publicationResult = await publication({ root, outdir, result });
437
+ const additions = publicationResult === undefined ? {} : publicationResult;
438
+
439
+ if (!additions || typeof additions !== 'object' || Array.isArray(additions)) {
440
+ throw new TypeError('publication must return an object or undefined');
441
+ }
442
+
443
+ if (additions.aliases !== undefined && (!additions.aliases || typeof additions.aliases !== 'object' || Array.isArray(additions.aliases))) {
444
+ throw new TypeError('publication aliases must be a non-array object');
445
+ }
446
+
447
+ if (additions.extraFiles !== undefined && !Array.isArray(additions.extraFiles)) {
448
+ throw new TypeError('publication extraFiles must be an array');
449
+ }
450
+
451
+ for (const key of Object.keys(additions.aliases ?? {})) {
452
+ if (Object.hasOwn(aliases, key)) {
453
+ throw new Error(`Duplicate publication alias: ${key}`);
454
+ }
455
+ }
422
456
  const { release, version, manifest } = await packageFlatRelease({
423
- root: resolve(root, 'public'),
424
- outputDirectory: resolve(root, 'public'),
457
+ extraFiles: additions.extraFiles,
458
+ retain: additions.retain,
459
+ previousPublic: resolve(root, 'public'),
460
+ root: outdir,
461
+ removeIntermediates: true,
425
462
  flatDir,
426
463
  entries,
427
464
  ssrDir,
428
465
  ssrNames,
429
466
  standaloneAssets,
430
- aliases,
467
+ aliases: { ...aliases, ...additions.aliases },
431
468
  });
432
469
 
433
- await publishFlatRelease({ root, wpRoot, release, manifest, version, direct: true, publicPrefix: publicPath });
470
+ await publishFlatRelease({ root, wpRoot, release, manifest, version, publicPrefix: publicPath });
434
471
  await clearBuildDirectory(outdir, root);
435
472
  };
436
473
  const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
package/bun/watch.mjs CHANGED
@@ -41,6 +41,21 @@ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => f
41
41
  let pending = false;
42
42
  let stopped = false;
43
43
  const watchers = new Map();
44
+ const directoryStamps = new Map();
45
+ const filterDirectoryEvents = process.platform === 'darwin' && typeof Bun !== 'undefined';
46
+ const directoryStamp = (path) => {
47
+ try {
48
+ const info = statSync(path);
49
+
50
+ return info.isDirectory() ? `${info.dev}:${info.ino}:${info.mode}:${info.mtimeMs}:${info.ctimeMs}` : undefined;
51
+ } catch (error) {
52
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
53
+ return undefined;
54
+ }
55
+
56
+ throw error;
57
+ }
58
+ };
44
59
 
45
60
  const report = (error) => {
46
61
  try {
@@ -146,6 +161,9 @@ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => f
146
161
  }
147
162
  }
148
163
  if (current === input && info.isDirectory()) {
164
+ if (filterDirectoryEvents && !directoryStamps.has(input)) {
165
+ directoryStamps.set(input, directoryStamp(input));
166
+ }
149
167
  add(input, true);
150
168
  if (input !== root) {
151
169
  add(dirname(input), false, basename(input));
@@ -171,8 +189,43 @@ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => f
171
189
  return;
172
190
  }
173
191
  const path = resolve(config.directory, name);
174
- onEvent(path);
175
192
  try {
193
+ // Bun on macOS can report unchanged watched directories as changes.
194
+ if (filterDirectoryEvents && _event === 'change') {
195
+ let directory;
196
+
197
+ if (!config.recursive && inputs.includes(path)) {
198
+ directory = path;
199
+ } else if (config.recursive && name === basename(config.directory)) {
200
+ try {
201
+ statSync(path);
202
+ } catch (error) {
203
+ if (error.code !== 'ENOENT') {
204
+ throw error;
205
+ }
206
+ directory = config.directory;
207
+ }
208
+ }
209
+
210
+ if (directory) {
211
+ const stamp = directoryStamp(directory);
212
+
213
+ if (stamp && directoryStamps.get(directory) === stamp) {
214
+ return;
215
+ }
216
+ if (stamp) {
217
+ directoryStamps.set(directory, stamp);
218
+ }
219
+ }
220
+ }
221
+ if (filterDirectoryEvents && config.recursive) {
222
+ const stamp = directoryStamp(config.directory);
223
+
224
+ if (stamp) {
225
+ directoryStamps.set(config.directory, stamp);
226
+ }
227
+ }
228
+ onEvent(path);
176
229
  refresh();
177
230
  } catch (error) {
178
231
  report(error);
package/bun/wordpress.mjs CHANGED
@@ -3,6 +3,7 @@ import { dirname, isAbsolute, resolve } from 'node:path';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { promisify } from 'node:util';
5
5
  import { execFile } from 'node:child_process';
6
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
6
7
 
7
8
  const execFileAsync = promisify(execFile);
8
9
  const externals = {
@@ -80,13 +81,58 @@ export function wordpressPlugin({ projectRoot = process.cwd(), wpRoot } = {}) {
80
81
  const projectRequire = createRequire(resolve(projectRoot, 'package.json'));
81
82
  const dependencies = new Set();
82
83
  const modules = new Map();
84
+ const handles = new Map();
83
85
 
84
86
  return {
85
87
  dependencies,
86
- plugin: {
88
+ getEmittedDependencies(metafile) {
89
+ try {
90
+ const data = typeof metafile === 'string' ? JSON.parse(metafile) : metafile;
91
+ const outputs = Object.values(data?.outputs ?? {});
92
+
93
+ if (!outputs.length) {
94
+ return [...dependencies].sort();
95
+ }
96
+
97
+ const emitted = new Set();
98
+
99
+ for (const output of outputs) {
100
+ if (!output?.inputs || typeof output.inputs !== 'object') {
101
+ return [...dependencies].sort();
102
+ }
103
+
104
+ for (const [input, info] of Object.entries(output.inputs)) {
105
+ if (!input.startsWith('wordpress-global:')) {
106
+ continue;
107
+ }
108
+
109
+ if (typeof info?.bytesInOutput !== 'number') {
110
+ return [...dependencies].sort();
111
+ }
112
+
113
+ if (!info.bytesInOutput) {
114
+ continue;
115
+ }
116
+
117
+ const key = input.slice('wordpress-global:'.length);
118
+
119
+ if (!handles.has(key)) {
120
+ return [...dependencies].sort();
121
+ }
122
+
123
+ emitted.add(handles.get(key));
124
+ }
125
+ }
126
+
127
+ return [...emitted].sort();
128
+ } catch {
129
+ return [...dependencies].sort();
130
+ }
131
+ },
132
+ plugin: allowPureJsxGrouping({
87
133
  name: 'wordpress-globals',
88
134
  setup(build) {
89
- build.onResolve({ filter: /.*/ }, async (args) => {
135
+ build.onResolve({ filter: /^(?:moment|jquery|lodash|lodash-es|@babel\/runtime\/regenerator|react|react-dom)(?:$|\/)|^@wordpress\/|react-refresh\/runtime/ }, async (args) => {
90
136
  const request = args.path;
91
137
  const external = externalFor(request);
92
138
 
@@ -163,11 +209,12 @@ export function wordpressPlugin({ projectRoot = process.cwd(), wpRoot } = {}) {
163
209
  }
164
210
 
165
211
  dependencies.add(handle);
212
+ handles.set(key, handle);
166
213
 
167
214
  return { path: key, namespace: 'wordpress-global' };
168
215
  });
169
216
  build.onLoad({ filter: /.*/, namespace: 'wordpress-global' }, (args) => ({ contents: modules.get(args.path), loader: 'js' }));
170
217
  },
171
- },
218
+ }),
172
219
  };
173
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eightshift/frontend-libs-tailwind",
3
- "version": "4.0.0-beta.1",
3
+ "version": "4.0.0-beta.3",
4
4
  "description": "A framework for creating modern Gutenberg themes with styling provided by Tailwind CSS.",
5
5
  "author": {
6
6
  "name": "Eightshift team",