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

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 CHANGED
@@ -8,6 +8,14 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
8
8
 
9
9
  ## [4.0.0]
10
10
 
11
+ ### 4.0.0-beta.4
12
+
13
+ - Default conventional theme editor builds to unified sharing; compatible PHP module-readiness integration is required.
14
+ - Add opt-in shared same-origin font publication, requiring UI Components 8.5.0-beta.1 and Eightshift Libs 14.0.0-alpha.3 shared-font support.
15
+ - Compile default SSR entries together as standalone CommonJS bundles; preserve sequential compilation for caller plugins and prevent implicit writes during compilation.
16
+ - Restart CLI watch workers on selected configuration, root package manifest and Bun lockfile changes, draining active work before replacement.
17
+ - Accept both verified generated Smart Image worker URL forms.
18
+
11
19
  ### Changed
12
20
 
13
21
  - Show build/watch progress and total duration by default, with `--quiet` and `--verbose` output modes.
@@ -21,7 +29,7 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
21
29
  - Improved browser bundle tree-shaking and WordPress dependency metadata.
22
30
  - Prevented unnecessary watch rebuilds on macOS.
23
31
  - Removed the experimental `editor.sharedPackages` option. Existing configurations must remove it or migrate to a supported sharing mode.
24
- - Added opt-in editor sharing modes: `native` shares lazy-loaded modules while preserving synchronous registration; `unified` also shares registration code and requires matching PHP module-readiness integration. Independent builds remain the default.
32
+ - **Breaking:** conventional theme builds now default to `unified` editor sharing, requiring matching PHP module-readiness integration (validated with eightshift-libs 14.0.0-alpha.2). The lower-level editor API still defaults to `independent`. Explicit editor presets retain their own sharing choice. `native` remains opt-in and shares lazy modules while keeping registration separate.
25
33
  - Added opt-in `editor.pureJsxGroups` to reduce chunk requests in unified production builds. Unsupported configurations, including source-map builds, fall back to ungrouped output.
26
34
 
27
35
  ## [3.5.0]
package/README.md CHANGED
@@ -54,6 +54,31 @@ The manifest maps the conventional `applicationBlocksFrontend`, `applicationBloc
54
54
 
55
55
  Successful default publication replaces the previous `public/` contents. Run only one build or publication per theme at a time; output directories are not locked against concurrent builds. The PHP manifest cache update is not coordinated with PHP cache rebuilds: if they overlap, stale asset URLs can remain until the next successful build or cache reset. Account for cached pages that may still request files removed by successful publication; retain old releases externally if needed. Verify block registration, editor controls and save/reload behavior, frontend styles and lazy assets, representative admin screens, script dependencies, browser console and asset URLs. Keep the previous Webpack build available for rollback until the new build is verified.
56
56
 
57
+ ### Editor default and PHP compatibility
58
+
59
+ `defineThemeBuild({ root })` uses unified editor sharing: registration and lazy editor modules share one ESM graph. It requires the PHP `eightshift-editor-v1` module-readiness integration, validated with `infinum/eightshift-libs` 14.0.0-alpha.2. Install compatible PHP integration before serving these assets, and enqueue editor JavaScript through `enqueue_block_editor_assets`. The build checks WordPress source compatibility but cannot certify which PHP integration is active at runtime. Without the readiness bootstrap, the generated module throws an explicit error; there is no automatic classic-script fallback.
60
+
61
+ Classic consumers that require registered blocks must await the readiness promise described below. This is a registration-semantics change, not a guaranteed startup speedup. Package import optimization and pure JSX grouping are separate settings; JSX grouping remains off by default.
62
+
63
+ For an explicit classic-registration fallback, provide the complete editor preset:
64
+
65
+ ```js
66
+ export default defineThemeBuild({
67
+ root: import.meta.dirname,
68
+ editor: {
69
+ entry: 'editor',
70
+ filename: 'applicationBlocksEditor.js',
71
+ sharing: 'independent',
72
+ discovery: {
73
+ filter: /application-blocks-editor\.js$/,
74
+ omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
75
+ },
76
+ },
77
+ });
78
+ ```
79
+
80
+ Independent entries do not preserve shared module state across separately compiled bundles: context providers and consumers spanning those bundles need an explicit compatibility solution. Rebuild and deploy matching scripts and metadata together when changing modes. Supplying `editor` replaces the whole preset; an explicit editor object without `sharing` retains the lower-level independent default.
81
+
57
82
  ### Lower-level build API
58
83
 
59
84
  For a nonstandard project, run the following as a project-root `build.mjs`, adapting the paths to your project:
@@ -101,7 +126,7 @@ Run `bun run build.mjs`, add `--production` for minification, or `--watch` for a
101
126
 
102
127
  `build` requires named entries and an output directory. By default, it builds each entry separately as browser ESM with splitting and hashed filenames, writes `manifest.json` and an `<entry>/<entry>.asset.json` with dependencies and a version hash, and returns `{ outdir, entries }`. Integrate these files with your WordPress enqueue code; this package does not enqueue them. Output is staged and published only after success. An existing output directory must have the build's ownership marker, and output paths and trees cannot contain symlinks. Do not use a directory containing the project root. `buildOptions` can override Bun defaults such as `target`, `format`, `splitting`, `naming`, loaders and plugins; callers must ensure the resulting format matches their WordPress loading strategy. Entry points, output directory and write mode are controlled by the build API.
103
128
 
104
- For projects that prefer a validated configuration, `createPreset` and `buildPreset` are exported from `@eightshift/frontend-libs-tailwind/bun/preset.mjs`. Pass `wordpress: false`, `discovery: false`, `responsive: false` or `css: false` to disable the corresponding feature; discovery, responsive generation and CSS are opt-in. Configure CSS surfaces or pass a custom CSS callback. `buildOptions` accepts the same overrides as `build`. When an editor entry is enabled, `buildOptions.sourcemap` supports only `none` and `external`. The default `editor.sharing: 'independent'` keeps synchronous registration and lazy entries in separate bundles. Its lazy editor URLs use a build-wide query version derived from the registration and lazy bundles; changing either invalidates all lazy URLs. The opt-in sharing modes below change graph layout, and unified mode also changes registration timing.
129
+ For projects that prefer a validated configuration, `createPreset` and `buildPreset` are exported from `@eightshift/frontend-libs-tailwind/bun/preset.mjs`. Pass `wordpress: false`, `discovery: false`, `responsive: false` or `css: false` to disable the corresponding feature; discovery, responsive generation and CSS are opt-in. Configure CSS surfaces or pass a custom CSS callback. `buildOptions` accepts the same overrides as `build`. When an editor entry is enabled, `buildOptions.sourcemap` supports only `none` and `external`. The lower-level default `editor.sharing: 'independent'` keeps synchronous registration and lazy entries in separate bundles; the conventional theme preset instead defaults to unified sharing. Its lazy editor URLs use a build-wide query version derived from the registration and lazy bundles; changing either invalidates all lazy URLs. The opt-in sharing modes below change graph layout, and unified mode also changes registration timing.
105
130
 
106
131
  ### Native editor sharing (experimental, opt-in)
107
132
 
@@ -130,11 +155,11 @@ Native sharing preserves nested lazy imports and emits source maps when requeste
130
155
 
131
156
  This mode requires readable Bun entry metadata and rejects dynamic imports that Bun inlines into the current chunk: those can lose native module namespaces, and dynamic self-imports were observed to generate an undefined helper in Bun 1.4.4-canary.1. These cases fail the build rather than silently falling back to different semantics. Native output must remain JavaScript and source maps, as with the existing editor pipeline.
132
157
 
133
- Native sharing can substantially reduce total output while increasing the number of files requested by the editor. It does **not** guarantee faster startup or Webpack parity. Validate cold and warm editor loads, first-block rendering, options, custom plugins, worker URLs and module state before enabling it. No theme is opted in automatically. Remove `sharing: 'native'` to restore independent chunks and rebuild; do not mix outputs from the two modes.
158
+ Native sharing can substantially reduce total output while increasing the number of files requested by the editor. It does **not** guarantee faster startup or Webpack parity. Validate cold and warm editor loads, first-block rendering, options, custom plugins, worker URLs and module state before enabling it. No theme is opted into native sharing automatically. Set `sharing: 'independent'` explicitly to restore independent chunks, or remove the entire editor override to use the theme preset's unified default; rebuild and do not mix outputs from different modes.
134
159
 
135
- ### Unified editor graph (experimental, compatibility-changing)
160
+ ### Unified editor graph (theme default, compatibility-changing)
136
161
 
137
- `editor.sharing: 'unified'` builds registration and all lazy editor code in one native ESM graph. Unlike `native`, it can share dependency instances between registration and lazy consumers. It does **not** preserve synchronous classic-script registration. Keep it disabled until the matching Eightshift PHP module-readiness integration is installed and every dependent consumer has been checked.
162
+ `editor.sharing: 'unified'` builds registration and all lazy editor code in one native ESM graph. Unlike `native`, it can share dependency instances between registration and lazy consumers. It does **not** preserve synchronous classic-script registration. The conventional theme preset now selects this mode by default; install matching Eightshift PHP module-readiness integration and check dependent consumers before switching. Lower-level callers must still opt in explicitly.
138
163
 
139
164
  Use the native-sharing configuration above with `sharing: 'unified'`. Do not provide `editor.lazy` rewriting options; unified mode lets Bun discover native imports. It keeps the same lazy-transform rejection rules as native mode. Its JavaScript wrapper statically imports the editor graph and signals completion through `globalThis.eightshiftEditorModules.complete(import.meta.url)`. Generated editor asset metadata declares `format: 'module'` and `readiness: 'eightshift-editor-v1'`; frontend/admin and existing editor modes retain their previous metadata. Older classic-only PHP integration is incompatible.
140
165
 
@@ -171,7 +196,7 @@ A second native build compiles the original graph with bounded groups. Static na
171
196
 
172
197
  In an isolated production-release comparison using Bun 1.4.4-canary.1, 4 KiB grouping reduced startup theme-JavaScript requests from 34 to 16 while increasing gzip bytes from 307108 to 309447. After rendering a CTA block, requests fell from 37 to 19 and gzip bytes increased from 388459 to 390798. Both variants registered 33 theme blocks and rendered three editable CTA fields without browser errors. These measurements used a synthetic editor page with the PHP readiness bootstrap and disabled browser cache; WordPress core assets are excluded. The same-source Webpack reference used 10 startup requests / 287529 gzip bytes and 12 requests / 366641 gzip bytes after the CTA. These results do **not** establish a repeatable latency improvement or Webpack parity. Measure your own editor and lazy interactions before opting in. Remove `pureJsxGroups` or set it to `false` and rebuild to roll back; independent and native-lazy modes remain unchanged.
173
198
 
174
- The earlier `editor.sharedPackages` vendor-bridge experiment was removed. Existing experimental configurations must remove that option; it now fails configuration validation rather than silently changing initialization behavior. Use independent mode by default, or explicitly evaluate native/unified sharing with their compatibility requirements.
199
+ The earlier `editor.sharedPackages` vendor-bridge experiment was removed. Existing experimental configurations must remove that option; it now fails configuration validation rather than silently changing initialization behavior. The lower-level API retains independent mode by default; the theme preset uses unified mode with the PHP compatibility requirements above. Native sharing remains opt-in.
175
200
 
176
201
  ### Theme build and watch integration
177
202
 
@@ -179,6 +204,16 @@ For `defineBuild` watch configurations with `ssr` or `publish` callbacks, explic
179
204
 
180
205
  `defineThemeBuild` from `bun/theme-build.mjs` supplies the conventional theme layout and flat publication. `entries` replaces the complete entry map; `editor` replaces the editor preset or may be `false`. `responsive` accepts the preset's options or `false`. `css` accepts an async callback receiving `{ root, outdir, stage, responsive, require }` or `false`; `extraCss` still runs afterwards. `discovery` accepts a plugin factory receiving `{ root, setEditorWorker, getEditorWorker }` (also async) or `false`; with either override, callers must provide discovery compatible with their entry sources. `frontendStyles` applies only to default discovery. The built-in editor worker plugin runs before plugins returned by `createPlugins`; replace it via `media.editorWorker` when custom handling is needed. The returned plugin array is not modified. `ssr` replaces `buildSsr` or can be `false`; do not specify both. `publish` replaces the flat publisher with an async callback receiving the build state, or `false` leaves the intermediate build unpublished in `public/.build`. With custom or disabled publication, the SSR callback runs after the browser build and receives the build state and `mode: 'production'`.
181
206
 
207
+ ### Shared same-origin UI Components fonts (opt-in)
208
+
209
+ Set `sharedFonts: true` in `defineThemeBuild` only after installing compatible PHP shared-font integration (`infinum/eightshift-libs` 14.0.0-alpha.3) and a UI Components release containing `dist/assets/fonts-manifest.json` (`@eightshift/ui-components` 8.5.0-beta.1). These are the first published versions containing the shared-font contract; earlier releases do not provide it. Fonts remain required: this option changes their provider, not typography. The default is `false`, preserving standalone builds.
210
+
211
+ The current shared-provider contract supports WOFF2 only and rejects other manifest formats. The build verifies UI Components font bytes against their SHA-256 manifest, extracts matching compiled `@font-face` rules from the published CSS, and stages `shared-fonts.json` plus `fonts/<sha256>.<extension>` alongside other assets. Unrelated or mixed-source faces remain untouched. Extraction occurs before final stylesheet hashes are calculated. The default staged publisher is required; custom publication is rejected for this option. Missing manifests, integrity mismatches or no matching faces fail the build rather than silently omitting fonts.
212
+
213
+ Compatible Eightshift PHP integration must read the generated manifest and enqueue the required font declarations with same-origin URLs shared across participating themes/plugins. Deploy PHP support and the matching assets together. Existing consumers that embed their own font faces still download their own URLs until rebuilt with this integration. Separate frames still need declarations; browser caching can reuse common URLs when enabled. No remote CDN, database cache or shared-directory write is required.
214
+
215
+ The exported `prepareSharedFonts({ root, flatDir })` helper in `bun/shared-fonts.mjs` is also available for a custom build pipeline. It mutates staged flat CSS and returns publication `extraFiles`/`aliases`; call it before hashing styles, and publish those additions atomically with the CSS. Do not run it directly on active public assets.
216
+
182
217
  ### Staged theme publication
183
218
 
184
219
  Default theme builds now prepare assets outside `public`, then swap the validated
@@ -264,6 +299,8 @@ The build regenerates discovery and CSS on each rebuild. Watch monitors the conf
264
299
 
265
300
  Default flat publication requires frontend, admin and editor entries, an editor build, and CSS at the conventional filenames. It scans the conventional SSR source glob and expects matching outputs in `.bun-pilot/theme-build/ssr/production`. With default publication, custom `ssr` (or legacy `buildSsr`) callbacks receive `{ root, mode: 'production', outdir }`, where `outdir` is the absolute path to that SSR output directory. Callbacks must finish writing `<name>.js` files there before resolving, where `<name>` is the directory containing each conventional `assets-ssr` directory; `packageFlatRelease` reads those files from the same directory. Use `ssr: false` to omit SSR or supply custom publication for a different layout. Disabling responsive generation requires custom or disabled CSS. Custom publication is required when disabling CSS or the editor, or changing the entry set. With custom or disabled publication, intermediate output remains in `public/.build`; the project owns its publication and cleanup.
266
301
 
302
+ The default SSR builder compiles all discovered entries together into standalone Node CJS bundles, without shared chunks or sourcemaps. Output filenames remain `<block-or-component-directory>.js`; duplicate names are rejected before compilation. Caller-supplied plugins retain one sequential compilation per entry to preserve their per-build lifecycle. Compilation omits Bun's `outdir` so it stays in memory (Bun 1.4.4 can write files when `outdir` is set even with `write: false`). All outputs are validated before explicit writes; compilation failures leave existing files untouched. Returned `outputs[].path` is the publication path, while `outputs[].output.path` is Bun's intermediate artifact path. `write: false` never creates the output directory. The low-level builder does not prune old files when entries are removed; the theme preset rebuilds its owned staging directory. Writes are sequential, not an atomic transaction for I/O failures. Multi-entry compilation can retain additional dependency definitions and change bundle bytes; it does not guarantee byte identity with separate compilations.
303
+
267
304
  WordPress externalization is enabled by default. Set `wpRoot` to the WordPress installation when using externalized `@wordpress/*` imports; export discovery reads its core scripts and requires compatible installed package metadata. The adapter also maps React and selected common dependencies to WordPress globals. Those globals and script handles must be available at runtime. Set `wordpress: false` to disable this adapter. For direct Bun integration, `wordpressPlugin({ projectRoot, wpRoot })` returns `{ plugin, dependencies, getEmittedDependencies }`; use a fresh adapter for each build and absolute paths. `dependencies` contains all resolved handles. Request a Bun metafile and pass it to `getEmittedDependencies(metafile)` to derive handles from every emitted output; invalid metadata falls back to all resolved handles. Some Bun versions can throw when reading `result.metafile` itself, so catch that access and fall back to `dependencies` too.
268
305
 
269
306
  `processCss` compiles the `files` array in order into one output file. Each item is a path or `{ file, scan, sources, scanFiles, removeSources }`: scanning is opt-in; `sources` adds Tailwind scanner source objects, `scanFiles` adds explicit candidate files, and `removeSources` removes exact source-rule strings (and fails if absent). Relative paths resolve from `projectDir`. Local URL assets are copied next to the CSS with content-hashed names. Production uses Lightning CSS and the `browsers` option (default `>= 0.25%`); the return value includes `outputFile` and discovered `dependencies`. Watch does not automatically use those dependencies. `responsive: {}` generates frontend and editor class lists from `src/**/manifest.json`, expanding responsive classes for `sm` and `md`; customize `breakpoints`, `manifestGlob`, and `output`. Pass the relevant generated list to CSS scanning, as above. The standalone `generateResponsiveClasses({ projectDir, ... })` is also exported from `bun/build.mjs`.
@@ -339,3 +376,29 @@ Eightshift Frontend Libs Tailwind is maintained and sponsored by
339
376
 
340
377
  ## License
341
378
  Eightshift Frontend Libs Tailwind [Eightshift](https://eightshift.com) and [Infinum](https://infinum.com). This is free software, and may be redistributed under the terms specified in the LICENSE file.
379
+
380
+ ### CLI watch process restarts
381
+
382
+ `eightshift-build watch` keeps ordinary source watching in the configured watcher.
383
+ It polls the selected config file and the working directory's `package.json`,
384
+ `bun.lock`, and `bun.lockb` for content changes (100 ms polling, 200 ms settling),
385
+ then drains the old worker before importing configuration in a fresh Bun process.
386
+ Missing files and atomic replacements are detected. Invalid configuration prints
387
+ its error and waits for another restart-input change instead of respawning in a loop.
388
+ A worker failure remains reflected in the supervisor's eventual exit status.
389
+
390
+ This is an explicit boundary, not dependency discovery. Nested dependency manifests,
391
+ installed library edits, imported config helpers, other lockfiles and environment
392
+ changes require manually stopping and starting the CLI. In particular, editing a
393
+ nested package's exports alone does not trigger a restart; changing a root restart
394
+ input afterward loads it fresh. Install transactions should finish before restarting.
395
+ Programmatic `defineBuild`/`watchBuild` behavior and custom watch options are unchanged.
396
+
397
+ SIGINT/SIGTERM request shutdown even during configuration loading. The CLI waits
398
+ for config loading and the watcher's `stop()` promise; it never force-kills a slow
399
+ build or launches a concurrent replacement. A hung import or callback can therefore
400
+ hold shutdown indefinitely. Custom watchers must stop scheduling and drain all
401
+ work in `stop()`. Custom SSR/publication callbacks remain responsible for their own
402
+ transactional guarantees: process serialization does not provide rollback across
403
+ browser assets, SSR and custom publication. Reported build errors retain the
404
+ configured watcher's existing reporting/recovery behavior.
@@ -0,0 +1,115 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { delimiter, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export async function supervise(invocation) {
6
+ const watching = invocation.command === 'watch';
7
+ const inputs = [invocation.config, ...['package.json', 'bun.lock', 'bun.lockb'].map((name) => resolve(name))];
8
+ const snapshot = () =>
9
+ JSON.stringify(
10
+ inputs.map((path) => {
11
+ try {
12
+ return readFileSync(path).toString('base64');
13
+ } catch (error) {
14
+ if (error.code === 'ENOENT') return null;
15
+ throw error;
16
+ }
17
+ }),
18
+ );
19
+ let observed = watching ? snapshot() : '';
20
+ let child,
21
+ ready,
22
+ resolveReady,
23
+ timer,
24
+ changedAt = 0,
25
+ pending = false,
26
+ closing = false,
27
+ busy = false,
28
+ failure = 0;
29
+ let draining;
30
+ const drain = () => {
31
+ if (!child) return Promise.resolve();
32
+ if (!draining) {
33
+ const current = child;
34
+ draining = (async () => {
35
+ await Promise.race([ready, current.exited]);
36
+ if (current.exitCode === null) current.send('stop');
37
+ await current.exited;
38
+ if (child === current) child = undefined;
39
+ })();
40
+ }
41
+ return draining;
42
+ };
43
+ const launch = () => {
44
+ draining = undefined;
45
+ ready = new Promise((done) => {
46
+ resolveReady = done;
47
+ });
48
+ child = Bun.spawn([process.execPath, fileURLToPath(new URL('./cli-worker.mjs', import.meta.url)), JSON.stringify(invocation)], {
49
+ cwd: process.cwd(),
50
+ env: { ...process.env, NODE_PATH: [resolve('node_modules'), process.env.NODE_PATH].filter(Boolean).join(delimiter) },
51
+ stdin: 'inherit',
52
+ stdout: 'inherit',
53
+ stderr: 'inherit',
54
+ ipc(message) {
55
+ if (message === 'ready') resolveReady();
56
+ },
57
+ });
58
+ const current = child;
59
+ void current.exited.then((code) => {
60
+ if (child === current && !busy && !closing) {
61
+ failure = code || failure;
62
+ if (watching) console.error(`[eightshift-build] Worker exited (${code}); waiting for a restart input change.`);
63
+ }
64
+ });
65
+ };
66
+ const stop = async () => {
67
+ if (closing) return;
68
+ closing = true;
69
+ clearInterval(timer);
70
+ while (busy) await Bun.sleep(20);
71
+ await drain();
72
+ process.exitCode = failure;
73
+ };
74
+ process.on('SIGINT', stop);
75
+ process.on('SIGTERM', stop);
76
+ try {
77
+ launch();
78
+ if (!watching) {
79
+ failure = await child.exited;
80
+ return;
81
+ }
82
+ timer = setInterval(async () => {
83
+ if (closing || busy) return;
84
+ try {
85
+ const next = snapshot();
86
+ if (next !== observed) {
87
+ observed = next;
88
+ changedAt = Date.now();
89
+ pending = true;
90
+ }
91
+ if (!pending || Date.now() - changedAt < 200) return;
92
+ busy = true;
93
+ await drain();
94
+ observed = snapshot();
95
+ pending = false;
96
+ if (!closing) launch();
97
+ } catch (error) {
98
+ console.error(error);
99
+ failure = 1;
100
+ pending = false;
101
+ } finally {
102
+ busy = false;
103
+ }
104
+ }, 100);
105
+ while (!closing) await Bun.sleep(100);
106
+ await stop();
107
+ } finally {
108
+ while (busy) await Bun.sleep(20);
109
+ await drain();
110
+ clearInterval(timer);
111
+ process.removeListener('SIGINT', stop);
112
+ process.removeListener('SIGTERM', stop);
113
+ process.exitCode = failure;
114
+ }
115
+ }
@@ -0,0 +1,40 @@
1
+ import { pathToFileURL } from 'node:url';
2
+
3
+ let stopping = false;
4
+ let watcher;
5
+ let drain;
6
+ const stop = () => {
7
+ stopping = true;
8
+ if (watcher && !drain) {
9
+ drain = Promise.resolve()
10
+ .then(() => watcher.stop())
11
+ .catch((error) => {
12
+ console.error(error);
13
+ process.exitCode = 1;
14
+ })
15
+ .finally(() => process.disconnect?.());
16
+ }
17
+ };
18
+ process.on('SIGINT', stop);
19
+ process.on('SIGTERM', stop);
20
+ process.on('message', (message) => {
21
+ if (message === 'stop') stop();
22
+ });
23
+ process.send('ready');
24
+ try {
25
+ const { command, config, options } = JSON.parse(process.argv[2]);
26
+ const { default: definition } = await import(pathToFileURL(config).href);
27
+ if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
28
+ throw new TypeError('Config default export must be a defineBuild result');
29
+ }
30
+ if (!stopping) {
31
+ if (command === 'build') await definition.build(options);
32
+ else watcher = definition.watch(options);
33
+ }
34
+ if (stopping) stop();
35
+ } catch (error) {
36
+ console.error(error);
37
+ process.exitCode = 1;
38
+ } finally {
39
+ if (!watcher) process.disconnect?.();
40
+ }
package/bun/cli.mjs CHANGED
@@ -1,27 +1,5 @@
1
1
  #!/usr/bin/env bun
2
- import { delimiter, resolve } from 'node:path';
3
- import { pathToFileURL } from 'node:url';
4
-
5
- const projectModules = resolve('node_modules');
6
-
7
- if (!(process.env.NODE_PATH ?? '').split(delimiter).includes(projectModules)) {
8
- const child = Bun.spawn([process.execPath, ...process.argv.slice(1)], {
9
- cwd: process.cwd(),
10
- env: { ...process.env, NODE_PATH: [projectModules, process.env.NODE_PATH].filter(Boolean).join(delimiter) },
11
- stdin: 'inherit',
12
- stdout: 'inherit',
13
- stderr: 'inherit',
14
- });
15
-
16
- const forwardInt = () => child.kill('SIGINT');
17
- const forwardTerm = () => child.kill('SIGTERM');
18
- process.on('SIGINT', forwardInt);
19
- process.on('SIGTERM', forwardTerm);
20
- const exitCode = await child.exited;
21
- process.removeListener('SIGINT', forwardInt);
22
- process.removeListener('SIGTERM', forwardTerm);
23
- process.exit(exitCode);
24
- }
2
+ import { resolve } from 'node:path';
25
3
 
26
4
  const args = process.argv.slice(2);
27
5
  const command = args.shift();
@@ -62,29 +40,5 @@ if (options.quiet && options.verbose) {
62
40
  throw new Error('--quiet and --verbose cannot be combined');
63
41
  }
64
42
 
65
- const { default: definition } = await import(pathToFileURL(resolve(config)).href);
66
-
67
- if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
68
- throw new TypeError('Config default export must be a defineBuild result');
69
- }
70
-
71
- if (command === 'build') {
72
- await definition.build(options);
73
- } else {
74
- const watcher = definition.watch(options);
75
- let stopping;
76
- const stop = () => {
77
- if (!stopping) {
78
- stopping = Promise.resolve()
79
- .then(() => watcher.stop())
80
- .finally(() => {
81
- process.removeListener('SIGINT', stop);
82
- process.removeListener('SIGTERM', stop);
83
- });
84
- }
85
- return stopping;
86
- };
87
-
88
- process.on('SIGINT', stop);
89
- process.on('SIGTERM', stop);
90
- }
43
+ const { supervise } = await import('./cli-supervisor.mjs');
44
+ await supervise({ command, config: resolve(config), options });
package/bun/media.mjs CHANGED
@@ -26,7 +26,7 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
26
26
  return;
27
27
  }
28
28
 
29
- const pattern = /new URL\("" \+ new URL\("(\.\.\/\.\.\/assets\/image-analysis-worker-[A-Za-z0-9_-]+\.js)", import\.meta\.url\)\.href \+ "", "" \+ import\.meta\.url\)/g;
29
+ const pattern = /new URL\((?:"" \+ )?new URL\("(\.\.\/\.\.\/assets\/image-analysis-worker-[A-Za-z0-9_-]+\.js)", import\.meta\.url\)\.href(?: \+ "")?, "" \+ import\.meta\.url\)/g;
30
30
  const matches = [...source.matchAll(pattern)];
31
31
 
32
32
  if (matches.length !== 1) {
@@ -0,0 +1,90 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createRequire } from 'node:module';
3
+ import { readFile, readdir, writeFile } from 'node:fs/promises';
4
+ import { basename, dirname, extname, isAbsolute, relative, resolve } from 'node:path';
5
+ import postcss from 'postcss';
6
+ import valueParser from 'postcss-value-parser';
7
+
8
+ /** Extract verified UI Components font faces before stylesheet hashes are calculated. */
9
+ export async function prepareSharedFonts({ root, flatDir }) {
10
+ const require = createRequire(resolve(root, 'package.json'));
11
+ const assets = dirname(require.resolve('@eightshift/ui-components/dist/assets/style.css'));
12
+ const manifest = JSON.parse(await readFile(resolve(assets, 'fonts-manifest.json'), 'utf8'));
13
+
14
+ if (manifest.version !== 1 || !Array.isArray(manifest.fonts) || !manifest.fonts.length || typeof manifest.css !== 'string') {
15
+ throw new Error('Invalid UI Components font manifest; rebuild UI Components with shared-font support.');
16
+ }
17
+
18
+ const hashes = new Set();
19
+ for (const font of manifest.fonts) {
20
+ if (!font || !/^[a-f0-9]{64}$/.test(font.hash) || typeof font.file !== 'string' || !/^fonts\/[\w.-]+\.woff2$/.test(font.file)) {
21
+ throw new Error('Invalid shared font asset descriptor.');
22
+ }
23
+ const bytes = await readFile(resolve(assets, font.file));
24
+ if (createHash('sha256').update(bytes).digest('hex') !== font.hash) {
25
+ throw new Error(`Shared font integrity mismatch: ${font.file}`);
26
+ }
27
+ hashes.add(font.hash);
28
+ }
29
+
30
+ const faces = new Set();
31
+ const fonts = new Map();
32
+ const updated = [];
33
+ for (const name of (await readdir(flatDir)).filter((name) => name.endsWith('.css')).sort()) {
34
+ const file = resolve(flatDir, name);
35
+ const tree = postcss.parse(await readFile(file, 'utf8'), { from: file });
36
+ const candidates = [];
37
+ tree.walkAtRules('font-face', (face) => candidates.push(face));
38
+ for (const face of candidates) {
39
+ const sources = [];
40
+ face.walkDecls('src', (decl) => {
41
+ const parsed = valueParser(decl.value);
42
+ parsed.walk((node) => {
43
+ if (node.type === 'function' && node.value.toLowerCase() === 'url') {
44
+ sources.push({
45
+ node,
46
+ parsed,
47
+ decl,
48
+ url: valueParser
49
+ .stringify(node.nodes)
50
+ .trim()
51
+ .replace(/^(['"])(.*)\1$/, '$2'),
52
+ });
53
+ }
54
+ });
55
+ });
56
+ if (!sources.length) continue;
57
+ const resolved = [];
58
+ for (const source of sources) {
59
+ if (/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(source.url) || /[?#]/.test(source.url)) break;
60
+ const path = resolve(flatDir, source.url);
61
+ const rel = relative(flatDir, path);
62
+ if (isAbsolute(rel) || rel.startsWith('..') || !/\.woff2$/.test(path)) break;
63
+ const hash = createHash('sha256')
64
+ .update(await readFile(path))
65
+ .digest('hex');
66
+ if (!hashes.has(hash)) break;
67
+ resolved.push({ ...source, path, hash, file: `fonts/${hash}${extname(path)}` });
68
+ }
69
+ // Leave mixed or unrelated font declarations entirely unchanged.
70
+ if (resolved.length !== sources.length) continue;
71
+ for (const source of resolved) {
72
+ source.node.nodes = [{ type: 'string', quote: '"', value: `./${source.file}` }];
73
+ fonts.set(source.file, { hash: source.hash, file: source.file, source: source.path });
74
+ }
75
+ for (const source of resolved) source.decl.value = source.parsed.toString();
76
+ faces.add(face.toString());
77
+ face.remove();
78
+ }
79
+ updated.push([file, tree.toString()]);
80
+ }
81
+
82
+ if (!faces.size) throw new Error('Shared fonts enabled but no verified UI Components font faces were found.');
83
+ const output = resolve(flatDir, '../shared-fonts.json');
84
+ await writeFile(output, JSON.stringify({ version: 1, fonts: [...fonts.values()].map(({ hash, file }) => ({ hash, file })), css: [...faces].join('\n') }, null, 2));
85
+ for (const [file, css] of updated) await writeFile(file, css);
86
+ return {
87
+ extraFiles: [{ source: output, destination: basename(output) }, ...[...fonts.values()].map(({ source, file }) => ({ source, destination: file }))],
88
+ aliases: { 'shared-fonts.json': 'shared-fonts.json' },
89
+ };
90
+ }
package/bun/ssr.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
- import { basename, dirname, resolve } from 'node:path';
2
+ import { basename, dirname, relative, resolve } from 'node:path';
3
3
 
4
4
  /** Discover SSR entries by their block/component directory name. */
5
5
  export async function discoverSsrEntries({ root, pattern = 'src/**/assets-ssr/ssr.{js,mjs}' }) {
@@ -37,9 +37,10 @@ export function ssrCssAsText() {
37
37
  }
38
38
 
39
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.
40
+ * Build discovered SSR entries as standalone Node CJS bundles in one compilation.
41
+ * Caller plugins retain sequential compilations and run before the CSS plugin.
42
+ * Paths are relative to root unless absolute; cssAsText: false disables the CSS
43
+ * plugin. write: false returns in-memory outputs without touching the output tree.
43
44
  */
44
45
  export async function buildSsr({ root, outdir, pattern, mode = 'development', plugins = [], cssAsText = true, write = true }) {
45
46
  if (typeof root !== 'string' || !root || typeof outdir !== 'string' || !outdir || !['development', 'production'].includes(mode) || !Array.isArray(plugins) || typeof cssAsText !== 'boolean' || typeof write !== 'boolean') {
@@ -50,12 +51,16 @@ export async function buildSsr({ root, outdir, pattern, mode = 'development', pl
50
51
  const entries = await discoverSsrEntries({ root, pattern });
51
52
  const outputs = [];
52
53
 
53
- for (const [name, entrypoint] of entries) {
54
+ // Caller plugins may keep per-build state, so retain their sequential lifecycle.
55
+ const groups = plugins.length ? [...entries].map((entry) => new Map([entry])) : [entries];
56
+
57
+ for (const group of groups) {
54
58
  const result = await Bun.build({
55
- entrypoints: [entrypoint],
56
- outdir: directory,
59
+ entrypoints: [...group.values()],
60
+ root: resolve(root),
61
+ // Omitting outdir is essential: Bun can write files despite write: false.
57
62
  write: false,
58
- naming: `${name}.js`,
63
+ naming: '[dir]/[name].[ext]',
59
64
  target: 'node',
60
65
  format: 'cjs',
61
66
  splitting: false,
@@ -67,14 +72,23 @@ export async function buildSsr({ root, outdir, pattern, mode = 'development', pl
67
72
  });
68
73
 
69
74
  if (!result.success) {
70
- throw new AggregateError(result.logs, `SSR build failed: ${name}`);
75
+ throw new AggregateError(result.logs, `SSR build failed: ${[...group.keys()].join(', ')}`);
71
76
  }
72
77
 
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}`);
78
+ if (result.outputs.length !== group.size || result.outputs.some((output) => output.kind !== 'entry-point')) {
79
+ throw new Error(`Unexpected SSR output count or kind: ${result.outputs.length}`);
75
80
  }
76
81
 
77
- outputs.push({ name, entrypoint, path: resolve(directory, `${name}.js`), output: result.outputs[0], logs: result.logs });
82
+ for (const [name, entrypoint] of group) {
83
+ const expected = relative(resolve(root), entrypoint).replace(/\.m?js$/, '.js');
84
+ const output = result.outputs.find((item) => resolve(root, item.path) === resolve(root, expected));
85
+
86
+ if (!output) {
87
+ throw new Error(`Missing SSR output: ${name}`);
88
+ }
89
+
90
+ outputs.push({ name, entrypoint, path: resolve(directory, `${name}.js`), output, logs: result.logs });
91
+ }
78
92
  }
79
93
 
80
94
  if (write) {
@@ -11,6 +11,7 @@ import { editorWorkerPlugin } from './media.mjs';
11
11
  import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
12
12
  import { processCss } from './css.mjs';
13
13
  import { buildSsr as buildDefaultSsr } from './ssr.mjs';
14
+ import { prepareSharedFonts } from './shared-fonts.mjs';
14
15
 
15
16
  /**
16
17
  * Define a conventional theme build. extraCss may be a hook or an array of
@@ -28,6 +29,7 @@ export function defineThemeBuild({
28
29
  createPlugins = () => [],
29
30
  frontendStyles = [],
30
31
  optimizeImports = ['@eightshift/ui-components'],
32
+ sharedFonts = false,
31
33
  extraCss = async () => {},
32
34
  aliases = {},
33
35
  publication = async () => ({}),
@@ -46,6 +48,10 @@ export function defineThemeBuild({
46
48
  throw new TypeError('root must be a non-empty string');
47
49
  }
48
50
 
51
+ if (typeof sharedFonts !== 'boolean' || (sharedFonts && publish !== undefined)) {
52
+ throw new TypeError('sharedFonts must be a boolean and requires default theme publication');
53
+ }
54
+
49
55
  if (typeof createPlugins !== 'function') {
50
56
  throw new TypeError('createPlugins must be a function');
51
57
  }
@@ -276,6 +282,7 @@ export function defineThemeBuild({
276
282
  editor: editor ?? {
277
283
  entry: 'editor',
278
284
  filename: 'applicationBlocksEditor.js',
285
+ sharing: 'unified',
279
286
  discovery: {
280
287
  filter: /application-blocks-editor\.js$/,
281
288
  omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
@@ -453,8 +460,12 @@ export function defineThemeBuild({
453
460
  throw new Error(`Duplicate publication alias: ${key}`);
454
461
  }
455
462
  }
463
+ const fontAssets = sharedFonts ? await prepareSharedFonts({ root, flatDir }) : { extraFiles: [], aliases: {} };
464
+ if (sharedFonts && (Object.hasOwn(aliases, 'shared-fonts.json') || Object.hasOwn(additions.aliases ?? {}, 'shared-fonts.json'))) {
465
+ throw new Error('shared-fonts.json is reserved when sharedFonts is enabled');
466
+ }
456
467
  const { release, version, manifest } = await packageFlatRelease({
457
- extraFiles: additions.extraFiles,
468
+ extraFiles: [...fontAssets.extraFiles, ...(additions.extraFiles ?? [])],
458
469
  retain: additions.retain,
459
470
  previousPublic: resolve(root, 'public'),
460
471
  root: outdir,
@@ -464,7 +475,7 @@ export function defineThemeBuild({
464
475
  ssrDir,
465
476
  ssrNames,
466
477
  standaloneAssets,
467
- aliases: { ...aliases, ...additions.aliases },
478
+ aliases: { ...aliases, ...additions.aliases, ...fontAssets.aliases },
468
479
  });
469
480
 
470
481
  await publishFlatRelease({ root, wpRoot, release, manifest, version, publicPrefix: publicPath });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eightshift/frontend-libs-tailwind",
3
- "version": "4.0.0-beta.3",
3
+ "version": "4.0.0-beta.4",
4
4
  "description": "A framework for creating modern Gutenberg themes with styling provided by Tailwind CSS.",
5
5
  "author": {
6
6
  "name": "Eightshift team",