@eightshift/frontend-libs-tailwind 4.0.0-beta.2 → 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 +19 -11
- package/README.md +113 -9
- package/bun/build.mjs +7 -1
- package/bun/cli-supervisor.mjs +115 -0
- package/bun/cli-worker.mjs +40 -0
- package/bun/cli.mjs +14 -47
- package/bun/flat-publication.mjs +25 -4
- package/bun/index.mjs +24 -0
- package/bun/media.mjs +1 -1
- package/bun/shared-fonts.mjs +90 -0
- package/bun/ssr.mjs +26 -12
- package/bun/theme-build.mjs +45 -14
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,21 +8,29 @@ 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
|
|
|
21
|
+
- Show build/watch progress and total duration by default, with `--quiet` and `--verbose` output modes.
|
|
22
|
+
- Stage theme releases before replacing public assets, preserving the previous release on build or cache failures.
|
|
23
|
+
- Support extra publication files, manifest aliases and explicit file retention through the shared publisher.
|
|
24
|
+
|
|
13
25
|
- **Breaking:** the conventional theme build requires a stable WordPress 7.0 or newer installation.
|
|
14
26
|
- **Breaking:** removed the Webpack configuration, `webpack/*` API and its build dependencies. Migrate project build scripts to Bun or another independently configured build pipeline.
|
|
15
|
-
- Bun build helpers
|
|
16
|
-
-
|
|
17
|
-
- Improved
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
- Added
|
|
22
|
-
|
|
23
|
-
- Added experimental `editor.sharing: 'unified'` for one registration/lazy ESM graph with module metadata and an explicit readiness completion signal. Requires matching PHP integration; classic defaults and native-lazy sharing remain unchanged.
|
|
24
|
-
- Added opt-in `editor.pureJsxGroups: { maxBytes: 4096 }` for unified production builds: bounded, AST-proven dependency definitions share native chunks without co-loading application initialization. Custom transforms and source-map builds conservatively retain ungrouped output with a warning; default builds remain unchanged.
|
|
25
|
-
- Isolated native editor compilation in private staging so Bun versions ignoring `write: false` cannot publish discarded first-pass chunks; selected artifacts and source maps are materialized before cleanup.
|
|
27
|
+
- Added Bun build helpers with a conventional theme preset, CSS processing and watch support. These are not a drop-in replacement for Webpack; project configuration and WordPress asset integration must be migrated.
|
|
28
|
+
- Enabled import optimization for `@eightshift/ui-components` by default in conventional theme builds.
|
|
29
|
+
- Improved browser bundle tree-shaking and WordPress dependency metadata.
|
|
30
|
+
- Prevented unnecessary watch rebuilds on macOS.
|
|
31
|
+
- Removed the experimental `editor.sharedPackages` option. Existing configurations must remove it or migrate to a supported sharing mode.
|
|
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.
|
|
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]
|
|
28
36
|
|
package/README.md
CHANGED
|
@@ -45,14 +45,39 @@ The conventional theme build requires a stable WordPress 7.0 or newer installati
|
|
|
45
45
|
}
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
-
4. Run `bun run build` and compare the generated assets and site behavior with the previous build. Use `bun run start` for an initial build and subsequent rebuilds, or `bun run build:sourcemaps` for external source maps. The CLI accepts `--config path` to select another configuration. It is `eightshift-build`, not `bun build`: the library orchestrates CSS, discovery, WordPress dependencies and publication around Bun's bundler.
|
|
48
|
+
4. Run `bun run build` and compare the generated assets and site behavior with the previous build. Use `bun run start` for an initial build and subsequent rebuilds, or `bun run build:sourcemaps` for external source maps. The CLI accepts `--config path` to select another configuration. By default, builds log a short start message and total elapsed seconds on success. Use `--quiet` to suppress informational output while retaining warnings and errors, or `--verbose` for build stages and theme entry/dependency details. These flags are mutually exclusive. The obsolete `--timings` flag is rejected. Both modes work with `build` and `watch`; each rebuild gets its own timer. Completion is reported only after configured SSR and publication callbacks succeed, including staged theme publication. The theme publisher may also build SSR during its publication stage. Use `eightshift-build --help` for CLI options. Programmatic `defineBuild` and theme definitions accept `{ quiet: true }` or `{ verbose: true }` in `.build()` and `.watch()`; combining them or providing the removed `timings` option throws. Custom callbacks should use the invocation context’s `quiet` and `verbose` fields to control their own informational logging. It is `eightshift-build`, not `bun build`: the library orchestrates CSS, discovery, WordPress dependencies and publication around Bun's bundler.
|
|
49
49
|
5. Update CI and deployment to use Bun and the new scripts. Only remove Webpack dependencies and configuration after verifying the new build. Ensure the deployment environment has access to WordPress and its compatible script metadata for dependency extraction.
|
|
50
50
|
|
|
51
|
-
The default preset discovers conventional block and component assets, builds frontend, editor and admin scripts and styles, and builds conventional SSR entries when present. SVG imports in frontend and admin scripts emit files referenced by root-relative public URLs; editor SVG imports produce SVG text instead. The default build
|
|
51
|
+
The default preset discovers conventional block and component assets, builds frontend, editor and admin scripts and styles, and builds conventional SSR entries when present. SVG imports in frontend and admin scripts emit files referenced by root-relative public URLs; editor SVG imports produce SVG text instead. The default build stages intermediate assets in `.bun-pilot/theme-build`, including SSR output in `.bun-pilot/theme-build/ssr/production`, and replaces `public/` with the packaged assets and manifest only after packaging succeeds. Build or packaging failures preserve the existing public assets. Successful builds remove the staging directory. Only custom or disabled publication uses `public/.build`; the project owns its publication and cleanup. Do not keep manually maintained files in `public/`. Frontend and admin use classic-script bootstraps that dynamically import their bundled modules; the editor is packaged separately. Preserve the generated chunks alongside the entry scripts. The default preset always produces production-optimized assets, including in watch mode; watch does not provide hot reload. With `--sourcemaps`, external maps are generated for the editor entry and its lazy chunks as well as the browser bundles. SSR execution may still require Node in the project's PHP integration.
|
|
52
52
|
|
|
53
53
|
The manifest maps the conventional `applicationBlocksFrontend`, `applicationBlocksEditor` and `applicationAdmin` script and style keys to their generated files. Each entry also has `.asset.json` metadata containing WordPress dependency handles and a release version; the manifest maps its legacy `.json` key to that metadata as well. Browser entry metadata includes handles used by any emitted chunk, including lazy chunks. If Bun's build metadata is unavailable or cannot be read, the build conservatively includes all resolved handles instead; the editor also retains all resolved handles across its independently compiled chunks. **The build does not enqueue assets:** confirm that your installed PHP integration reads the generated metadata and merges its dependencies with the registered handles. Existing PHP/library versions may not support this; update or adapt them before switching, and check that the frontend, editor and admin load without missing globals. Do not assume Bun's `external` option supplies WordPress global mappings.
|
|
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
|
+
|
|
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.
|
|
56
81
|
|
|
57
82
|
### Lower-level build API
|
|
58
83
|
|
|
@@ -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
|
|
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 (
|
|
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.
|
|
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.
|
|
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,57 @@ 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
|
+
|
|
217
|
+
### Staged theme publication
|
|
218
|
+
|
|
219
|
+
Default theme builds now prepare assets outside `public`, then swap the validated
|
|
220
|
+
release into place. Build/package failures preserve the previous release; cache
|
|
221
|
+
update failures roll publication back. Custom `publish` hooks remain responsible
|
|
222
|
+
for their own publication and rollback.
|
|
223
|
+
|
|
224
|
+
Use `publication` to supply additional already-built files (for example Infobip
|
|
225
|
+
UTM scripts/fonts or Forms custom entry bundles) without replacing the publisher:
|
|
226
|
+
|
|
227
|
+
```js
|
|
228
|
+
import { resolve } from 'node:path';
|
|
229
|
+
import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
|
|
230
|
+
|
|
231
|
+
export default defineThemeBuild({
|
|
232
|
+
root: import.meta.dirname,
|
|
233
|
+
publication: async ({ root }) => ({
|
|
234
|
+
extraFiles: [
|
|
235
|
+
{ source: resolve(root, 'build/utm.js'), destination: 'utm.js' },
|
|
236
|
+
{ source: resolve(root, 'build/fonts'), destination: 'fonts' },
|
|
237
|
+
{ source: resolve(root, 'build/forms.js'), destination: 'forms.js' },
|
|
238
|
+
],
|
|
239
|
+
aliases: { 'utm.js': 'utm.js', 'forms.js': 'forms.js', 'font.woff2': 'fonts/font.woff2' },
|
|
240
|
+
retain: [],
|
|
241
|
+
}),
|
|
242
|
+
});
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Sources must exist before packaging; the hook can build them into `outdir`.
|
|
246
|
+
The hook may return `undefined` for no additions, or a non-array object. When
|
|
247
|
+
provided, `aliases` must be a non-null, non-array object and `extraFiles` must be
|
|
248
|
+
an array; invalid results throw a `TypeError` before packaging.
|
|
249
|
+
Paths are release-relative destinations; duplicate destinations fail rather than
|
|
250
|
+
silently overwrite. `packageFlatRelease` also accepts `extraFiles`, `retain` and
|
|
251
|
+
`previousPublic`. Retention is opt-in and names exact existing files, not globs or
|
|
252
|
+
filename heuristics. Retained files cannot collide with new outputs. Fixed names
|
|
253
|
+
are replaced on successful publication: they cannot preserve old browser sessions
|
|
254
|
+
like content-hashed filenames. Additional manifest generation and automatic
|
|
255
|
+
multi-release retention are not provided. Aliases join the primary manifest and
|
|
256
|
+
PHP asset cache; consumers needing separate manifests must use custom publication.
|
|
257
|
+
|
|
182
258
|
### Optimizing package imports
|
|
183
259
|
|
|
184
260
|
`optimizeImports` is an array of package names passed to Bun's [barrel import optimization](https://bun.com/docs/bundler#optimizeimports) for frontend, editor (including lazy chunks), and admin JavaScript. It also applies in watch and source-map builds, but not to SSR or CSS processing. The conventional theme build defaults to `['@eightshift/ui-components']`. Supply an array to replace the default, or `[]` to disable the preset's explicit optimization:
|
|
@@ -221,7 +297,9 @@ The default flat publisher includes generated stylesheets in `public/` and its m
|
|
|
221
297
|
|
|
222
298
|
The build regenerates discovery and CSS on each rebuild. Watch monitors the configured project paths, not `node_modules` or arbitrary external files by default; customize `watch.sources` for additional inputs. Default theme builds use production CSS processing, including Lightning CSS minification and its browser targets, even in watch mode. `extraCss` may also be an async hook receiving `{ root, stage, require }`, or `false` to disable it. Hooks are responsible for their own filenames and loading behavior. `frontendStyles` separately attaches existing URLs to keys; both automatic mechanisms require default discovery.
|
|
223
299
|
|
|
224
|
-
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
|
|
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.
|
|
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.
|
|
225
303
|
|
|
226
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.
|
|
227
305
|
|
|
@@ -298,3 +376,29 @@ Eightshift Frontend Libs Tailwind is maintained and sponsored by
|
|
|
298
376
|
|
|
299
377
|
## License
|
|
300
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.
|
package/bun/build.mjs
CHANGED
|
@@ -349,7 +349,13 @@ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wor
|
|
|
349
349
|
return { outdir, entries: manifest };
|
|
350
350
|
} finally {
|
|
351
351
|
if (!published) {
|
|
352
|
-
|
|
352
|
+
try {
|
|
353
|
+
await removeTree(stage);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (error.code !== 'ENOENT') {
|
|
356
|
+
console.warn(`Build staging cleanup failed at ${stage}:`, error);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
353
359
|
}
|
|
354
360
|
}
|
|
355
361
|
}
|
|
@@ -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,33 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import {
|
|
3
|
-
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
4
3
|
|
|
5
|
-
const
|
|
4
|
+
const args = process.argv.slice(2);
|
|
5
|
+
const command = args.shift();
|
|
6
6
|
|
|
7
|
-
|
|
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
|
-
});
|
|
7
|
+
const usage = 'Usage: eightshift-build <build|watch> [--config path] [--sourcemaps] [--quiet | --verbose]';
|
|
15
8
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
process.
|
|
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);
|
|
9
|
+
if (command === '--help' || command === '-h' || args.includes('--help') || args.includes('-h')) {
|
|
10
|
+
console.log(`${usage}\n --quiet Suppress informational output (warnings/errors remain).\n --verbose Show build stages and entry/dependency details.`);
|
|
11
|
+
process.exit(0);
|
|
24
12
|
}
|
|
25
13
|
|
|
26
|
-
const args = process.argv.slice(2);
|
|
27
|
-
const command = args.shift();
|
|
28
|
-
|
|
29
14
|
if (!['build', 'watch'].includes(command)) {
|
|
30
|
-
throw new Error(
|
|
15
|
+
throw new Error(usage);
|
|
31
16
|
}
|
|
32
17
|
|
|
33
18
|
let config = 'eightshift.build.mjs';
|
|
@@ -42,6 +27,8 @@ while (args.length) {
|
|
|
42
27
|
if (!config || config.startsWith('--')) {
|
|
43
28
|
throw new Error('--config requires a path');
|
|
44
29
|
}
|
|
30
|
+
} else if (arg === '--verbose' || arg === '--quiet') {
|
|
31
|
+
options[arg.slice(2)] = true;
|
|
45
32
|
} else if (arg === '--sourcemaps') {
|
|
46
33
|
options.sourcemaps = true;
|
|
47
34
|
} else {
|
|
@@ -49,29 +36,9 @@ while (args.length) {
|
|
|
49
36
|
}
|
|
50
37
|
}
|
|
51
38
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
|
|
55
|
-
throw new TypeError('Config default export must be a defineBuild result');
|
|
39
|
+
if (options.quiet && options.verbose) {
|
|
40
|
+
throw new Error('--quiet and --verbose cannot be combined');
|
|
56
41
|
}
|
|
57
42
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
} else {
|
|
61
|
-
const watcher = definition.watch(options);
|
|
62
|
-
let stopping;
|
|
63
|
-
const stop = () => {
|
|
64
|
-
if (!stopping) {
|
|
65
|
-
stopping = Promise.resolve()
|
|
66
|
-
.then(() => watcher.stop())
|
|
67
|
-
.finally(() => {
|
|
68
|
-
process.removeListener('SIGINT', stop);
|
|
69
|
-
process.removeListener('SIGTERM', stop);
|
|
70
|
-
});
|
|
71
|
-
}
|
|
72
|
-
return stopping;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
process.on('SIGINT', stop);
|
|
76
|
-
process.on('SIGTERM', stop);
|
|
77
|
-
}
|
|
43
|
+
const { supervise } = await import('./cli-supervisor.mjs');
|
|
44
|
+
await supervise({ command, config: resolve(config), options });
|
package/bun/flat-publication.mjs
CHANGED
|
@@ -191,8 +191,25 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
|
|
|
191
191
|
}
|
|
192
192
|
|
|
193
193
|
/** Package flattened files, optional SSR files and standalone assets. */
|
|
194
|
-
export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, outputDirectory, removeIntermediates = false }) {
|
|
195
|
-
|
|
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
|
+
}
|
|
196
213
|
|
|
197
214
|
for (const name of await readdir(flatDir)) {
|
|
198
215
|
files.push({ source: resolve(flatDir, name), destination: name });
|
|
@@ -293,7 +310,7 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
|
|
|
293
310
|
throw new Error(`Unsupported release output: ${name}`);
|
|
294
311
|
}
|
|
295
312
|
|
|
296
|
-
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)) {
|
|
297
314
|
result[name] = name;
|
|
298
315
|
}
|
|
299
316
|
}
|
|
@@ -404,7 +421,11 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
|
|
|
404
421
|
};
|
|
405
422
|
|
|
406
423
|
if (hadPublic) {
|
|
407
|
-
|
|
424
|
+
try {
|
|
425
|
+
await removeTree(backup);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
console.warn(`Build published, but backup cleanup failed at ${backup}:`, error);
|
|
428
|
+
}
|
|
408
429
|
}
|
|
409
430
|
|
|
410
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
|
@@ -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 \+ ""
|
|
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
|
|
41
|
-
*
|
|
42
|
-
*
|
|
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
|
-
|
|
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: [
|
|
56
|
-
|
|
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:
|
|
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: ${
|
|
75
|
+
throw new AggregateError(result.logs, `SSR build failed: ${[...group.keys()].join(', ')}`);
|
|
71
76
|
}
|
|
72
77
|
|
|
73
|
-
if (result.outputs.length !==
|
|
74
|
-
throw new Error(`Unexpected SSR output count or kind
|
|
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
|
-
|
|
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) {
|
package/bun/theme-build.mjs
CHANGED
|
@@ -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,8 +29,10 @@ 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 = {},
|
|
35
|
+
publication = async () => ({}),
|
|
33
36
|
requireEditorWorker = false,
|
|
34
37
|
media = {},
|
|
35
38
|
watch = {},
|
|
@@ -45,6 +48,10 @@ export function defineThemeBuild({
|
|
|
45
48
|
throw new TypeError('root must be a non-empty string');
|
|
46
49
|
}
|
|
47
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
|
+
|
|
48
55
|
if (typeof createPlugins !== 'function') {
|
|
49
56
|
throw new TypeError('createPlugins must be a function');
|
|
50
57
|
}
|
|
@@ -180,13 +187,8 @@ export function defineThemeBuild({
|
|
|
180
187
|
|
|
181
188
|
editorWorker = undefined;
|
|
182
189
|
const publicDir = resolve(root, 'public');
|
|
183
|
-
outdir = resolve(publicDir, '.build');
|
|
184
|
-
|
|
185
|
-
await clearBuildDirectory(publicDir, root);
|
|
186
|
-
await mkdir(publicDir, { recursive: true });
|
|
187
|
-
} else {
|
|
188
|
-
await clearBuildDirectory(outdir, root);
|
|
189
|
-
}
|
|
190
|
+
outdir = publish === undefined ? resolve(root, '.bun-pilot/theme-build') : resolve(publicDir, '.build');
|
|
191
|
+
await clearBuildDirectory(outdir, root);
|
|
190
192
|
const require = createRequire(resolve(root, 'package.json'));
|
|
191
193
|
const names = ['componentManifests', 'customManifests', 'customBlocks', 'customHooks', 'customTransforms', 'customDeprecations', 'customOverrides', 'variationManifests', 'customVariationManifests', 'variationOverrides', 'componentAdminAssets', 'customAdminAssets'];
|
|
192
194
|
const specs = [
|
|
@@ -280,6 +282,7 @@ export function defineThemeBuild({
|
|
|
280
282
|
editor: editor ?? {
|
|
281
283
|
entry: 'editor',
|
|
282
284
|
filename: 'applicationBlocksEditor.js',
|
|
285
|
+
sharing: 'unified',
|
|
283
286
|
discovery: {
|
|
284
287
|
filter: /application-blocks-editor\.js$/,
|
|
285
288
|
omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
|
|
@@ -364,7 +367,7 @@ export function defineThemeBuild({
|
|
|
364
367
|
},
|
|
365
368
|
};
|
|
366
369
|
};
|
|
367
|
-
const defaultPublish = async ({ result }) => {
|
|
370
|
+
const defaultPublish = async ({ result, verbose, quiet }) => {
|
|
368
371
|
const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
|
|
369
372
|
|
|
370
373
|
if (requireEditorWorker && !editorWorker) {
|
|
@@ -376,7 +379,7 @@ export function defineThemeBuild({
|
|
|
376
379
|
|
|
377
380
|
if (ssr !== false) {
|
|
378
381
|
if (ssr || buildSsr) {
|
|
379
|
-
await (ssr ?? buildSsr)({ root, mode: 'production' });
|
|
382
|
+
await (ssr ?? buildSsr)({ root, mode: 'production', outdir: ssrDir });
|
|
380
383
|
}
|
|
381
384
|
|
|
382
385
|
for await (const file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root })) {
|
|
@@ -424,7 +427,9 @@ export function defineThemeBuild({
|
|
|
424
427
|
const entry = result.entries[surface];
|
|
425
428
|
const script = surface === 'editor' ? rewrite(editorScript, entry.entry) : undefined;
|
|
426
429
|
|
|
427
|
-
|
|
430
|
+
if (verbose && !quiet) {
|
|
431
|
+
console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
|
|
432
|
+
}
|
|
428
433
|
|
|
429
434
|
return {
|
|
430
435
|
name,
|
|
@@ -435,19 +440,45 @@ export function defineThemeBuild({
|
|
|
435
440
|
...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
|
|
436
441
|
};
|
|
437
442
|
});
|
|
443
|
+
const publicationResult = await publication({ root, outdir, result });
|
|
444
|
+
const additions = publicationResult === undefined ? {} : publicationResult;
|
|
445
|
+
|
|
446
|
+
if (!additions || typeof additions !== 'object' || Array.isArray(additions)) {
|
|
447
|
+
throw new TypeError('publication must return an object or undefined');
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (additions.aliases !== undefined && (!additions.aliases || typeof additions.aliases !== 'object' || Array.isArray(additions.aliases))) {
|
|
451
|
+
throw new TypeError('publication aliases must be a non-array object');
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (additions.extraFiles !== undefined && !Array.isArray(additions.extraFiles)) {
|
|
455
|
+
throw new TypeError('publication extraFiles must be an array');
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
for (const key of Object.keys(additions.aliases ?? {})) {
|
|
459
|
+
if (Object.hasOwn(aliases, key)) {
|
|
460
|
+
throw new Error(`Duplicate publication alias: ${key}`);
|
|
461
|
+
}
|
|
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
|
+
}
|
|
438
467
|
const { release, version, manifest } = await packageFlatRelease({
|
|
439
|
-
|
|
440
|
-
|
|
468
|
+
extraFiles: [...fontAssets.extraFiles, ...(additions.extraFiles ?? [])],
|
|
469
|
+
retain: additions.retain,
|
|
470
|
+
previousPublic: resolve(root, 'public'),
|
|
471
|
+
root: outdir,
|
|
441
472
|
removeIntermediates: true,
|
|
442
473
|
flatDir,
|
|
443
474
|
entries,
|
|
444
475
|
ssrDir,
|
|
445
476
|
ssrNames,
|
|
446
477
|
standaloneAssets,
|
|
447
|
-
aliases,
|
|
478
|
+
aliases: { ...aliases, ...additions.aliases, ...fontAssets.aliases },
|
|
448
479
|
});
|
|
449
480
|
|
|
450
|
-
await publishFlatRelease({ root, wpRoot, release, manifest, version,
|
|
481
|
+
await publishFlatRelease({ root, wpRoot, release, manifest, version, publicPrefix: publicPath });
|
|
451
482
|
await clearBuildDirectory(outdir, root);
|
|
452
483
|
};
|
|
453
484
|
const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
|
package/package.json
CHANGED