@eightshift/frontend-libs-tailwind 4.0.0-beta.4 → 4.0.0-beta.5
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 +21 -0
- package/README.md +85 -11
- package/bin/tw-sweep.mjs +35 -14
- package/bun/browser-css.mjs +487 -0
- package/bun/build.mjs +20 -1
- package/bun/cli-supervisor.mjs +70 -14
- package/bun/cli-worker.mjs +22 -5
- package/bun/css.mjs +126 -25
- package/bun/discovery.mjs +12 -1
- package/bun/editor-native.mjs +38 -0
- package/bun/editor-pure-jsx.mjs +88 -0
- package/bun/editor.mjs +33 -0
- package/bun/eightshift-discovery.mjs +102 -26
- package/bun/flat-publication.mjs +19 -184
- package/bun/index.mjs +14 -0
- package/bun/media.mjs +16 -4
- package/bun/plugin-capabilities.mjs +1 -0
- package/bun/preset.mjs +6 -4
- package/bun/publish.mjs +7 -4
- package/bun/release.mjs +56 -4
- package/bun/shared-fonts.mjs +62 -12
- package/bun/structured-publication.mjs +66 -0
- package/bun/theme-build.mjs +119 -43
- package/bun/theme-discovery.mjs +113 -9
- package/bun/watch.mjs +32 -0
- package/bun/wordpress.mjs +49 -23
- package/eslint.config.mjs +22 -1
- package/linters/base.config.mjs +1 -0
- package/linters/tw-sweep-extract.mjs +5 -0
- package/package.json +5 -5
- package/scripts/components/link-section-editor.js +1 -0
- package/scripts/editor/editor.js +1 -0
- package/scripts/editor/registration.js +3 -0
- package/scripts/editor/store.js +7 -0
- package/test/bun-discovery.test.mjs +69 -0
- package/test/bun-publication.test.mjs +144 -0
- package/test/bun-theme-build.test.mjs +12 -0
- package/test/bun-wordpress.test.mjs +82 -0
- package/test/fixtures/theme-build-regressions.mjs +585 -0
package/bun/theme-build.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { link, mkdir, readFile, unlink } from 'node:fs/promises';
|
|
2
|
+
import { link, mkdir, readFile, realpath, unlink } from 'node:fs/promises';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { defineBuild } from './index.mjs';
|
|
6
6
|
import { clearBuildDirectory } from './build.mjs';
|
|
7
7
|
import { generateThemeDiscovery, generateThemeImporters, themeDiscoveryPlugin } from './theme-discovery.mjs';
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { eightshiftCssEntries } from './eightshift-css.mjs';
|
|
9
|
+
import { preserveAssets } from './structured-publication.mjs';
|
|
10
|
+
import { packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
|
|
11
|
+
import { browserCssPlugin, browserCssRuntime, collectConventionalCss } from './browser-css.mjs';
|
|
10
12
|
import { editorWorkerPlugin } from './media.mjs';
|
|
11
13
|
import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
|
|
12
14
|
import { processCss } from './css.mjs';
|
|
@@ -17,33 +19,42 @@ import { prepareSharedFonts } from './shared-fonts.mjs';
|
|
|
17
19
|
* Define a conventional theme build. extraCss may be a hook or an array of
|
|
18
20
|
* { files, output?, keys?, href? }; package files use the `package:` prefix.
|
|
19
21
|
* Omitted output names use a content hash. Keys attach CSS to frontend importers.
|
|
22
|
+
* Frontend/admin JS imports compile styles separately and load them before the
|
|
23
|
+
* importing module; styles imported by lazy modules remain lazy.
|
|
24
|
+
* Direct imports already in conventional CSS are not loaded twice.
|
|
20
25
|
* SSR is built when conventional entries exist; ssr: false disables it.
|
|
21
26
|
* optimizeImports controls Bun's package barrel optimization for browser builds.
|
|
22
27
|
* UI Components is optimized by default; pass [] to disable the explicit default.
|
|
23
28
|
* watch: false disables watching; an object overrides the safe watch defaults.
|
|
24
29
|
*/
|
|
25
|
-
export function defineThemeBuild({
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
30
|
+
export function defineThemeBuild(options = {}) {
|
|
31
|
+
if (Object.hasOwn(options, 'publicationLayout')) {
|
|
32
|
+
throw new TypeError('publicationLayout has been removed; theme builds use structured publication. Remove the option and migrate publication hooks to publicationRoot.');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const {
|
|
36
|
+
root,
|
|
37
|
+
publicPrefix: configuredPublicPrefix,
|
|
38
|
+
buildSsr,
|
|
39
|
+
createPlugins = () => [],
|
|
40
|
+
frontendStyles = [],
|
|
41
|
+
optimizeImports = ['@eightshift/ui-components'],
|
|
42
|
+
sharedFonts = false,
|
|
43
|
+
extraCss = async () => {},
|
|
44
|
+
aliases = {},
|
|
45
|
+
publication = async () => ({}),
|
|
46
|
+
requireEditorWorker = false,
|
|
47
|
+
media = {},
|
|
48
|
+
watch = {},
|
|
49
|
+
entries,
|
|
50
|
+
editor,
|
|
51
|
+
responsive = {},
|
|
52
|
+
css,
|
|
53
|
+
discovery,
|
|
54
|
+
ssr,
|
|
55
|
+
publish,
|
|
56
|
+
} = options;
|
|
57
|
+
|
|
47
58
|
if (typeof root !== 'string' || !root) {
|
|
48
59
|
throw new TypeError('root must be a non-empty string');
|
|
49
60
|
}
|
|
@@ -158,34 +169,47 @@ export function defineThemeBuild({
|
|
|
158
169
|
const wpRoot = process.env.EIGHTSHIFT_WP_ROOT ? resolve(process.env.EIGHTSHIFT_WP_ROOT) : resolve(root, '../../..');
|
|
159
170
|
const themePath = relative(wpRoot, resolve(root));
|
|
160
171
|
let publicPath = configuredPublicPrefix ?? process.env.EIGHTSHIFT_PUBLIC_PREFIX;
|
|
172
|
+
|
|
161
173
|
if (publicPath === undefined) {
|
|
162
174
|
if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
|
|
163
175
|
throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
|
|
164
176
|
}
|
|
177
|
+
|
|
165
178
|
publicPath = `/${themePath.split(sep).join('/')}/public/`;
|
|
166
179
|
}
|
|
180
|
+
|
|
167
181
|
if (typeof publicPath !== 'string' || !publicPath.startsWith('/') || publicPath.startsWith('//') || !publicPath.endsWith('/') || publicPath.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPath) || publicPath.split('/').some((part) => part === '.' || part === '..')) {
|
|
168
182
|
throw new Error('publicPrefix must be a root-relative URL path ending in /');
|
|
169
183
|
}
|
|
184
|
+
|
|
170
185
|
let outdir;
|
|
171
186
|
let editorWorker;
|
|
187
|
+
let retainedStyles;
|
|
172
188
|
const makePreset = async ({ sourcemaps }) => {
|
|
173
189
|
const versionFile = resolve(wpRoot, 'wp-includes/version.php');
|
|
174
190
|
let versionSource;
|
|
191
|
+
|
|
175
192
|
try {
|
|
176
193
|
versionSource = await readFile(versionFile, 'utf8');
|
|
177
194
|
} catch (error) {
|
|
178
195
|
throw new Error(`Cannot read WordPress version at ${versionFile}. Set EIGHTSHIFT_WP_ROOT to a WordPress installation.`, { cause: error });
|
|
179
196
|
}
|
|
197
|
+
|
|
180
198
|
const version = versionSource.match(/^\s*\$wp_version\s*=\s*['"](\d+)\.(\d+)(?:\.(\d+))?(['"]);/m);
|
|
199
|
+
|
|
181
200
|
if (!version) {
|
|
182
201
|
throw new Error(`Cannot determine a stable WordPress version from ${versionFile}; WordPress 7.0 or newer is required.`);
|
|
183
202
|
}
|
|
203
|
+
|
|
184
204
|
if (Number(version[1]) < 7) {
|
|
185
205
|
throw new Error(`WordPress 7.0 or newer is required; found ${version[1]}.${version[2]}${version[3] === undefined ? '' : `.${version[3]}`}.`);
|
|
186
206
|
}
|
|
187
207
|
|
|
188
208
|
editorWorker = undefined;
|
|
209
|
+
retainedStyles = new Set();
|
|
210
|
+
const extraCssByFile = new Map();
|
|
211
|
+
const conventionalCss = new Map();
|
|
212
|
+
const responsiveFiles = {};
|
|
189
213
|
const publicDir = resolve(root, 'public');
|
|
190
214
|
outdir = publish === undefined ? resolve(root, '.bun-pilot/theme-build') : resolve(publicDir, '.build');
|
|
191
215
|
await clearBuildDirectory(outdir, root);
|
|
@@ -225,7 +249,7 @@ export function defineThemeBuild({
|
|
|
225
249
|
...manifestReplacements,
|
|
226
250
|
['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets/index.js`);', 'const importer = bunFrontendImporters[`${importBasePath}/${directory}`]; if (!importer) return Promise.reject(new Error("Missing frontend asset")); return importer();'],
|
|
227
251
|
],
|
|
228
|
-
|
|
252
|
+
omitContexts: ({ directory, pattern }) => css === undefined && ['components', 'custom', 'wrapper'].some((group) => directory === resolve(root, 'src/Blocks', group)) && ['styles-frontend.css$', 'styles-frontend\\.css$'].includes(pattern.source) && !pattern.flags,
|
|
229
253
|
},
|
|
230
254
|
{
|
|
231
255
|
path: 'src/Blocks/assets/scripts/application-admin.js',
|
|
@@ -238,7 +262,7 @@ export function defineThemeBuild({
|
|
|
238
262
|
["require.context('./../../custom', true, /assets-admin\\/index\\.js$/)", 'customAdminAssets'],
|
|
239
263
|
['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets-admin/index.js`);', 'return assetContext(assetPath);'],
|
|
240
264
|
],
|
|
241
|
-
|
|
265
|
+
omitContexts: ({ directory, pattern }) => css === undefined && ['components', 'custom'].some((group) => directory === resolve(root, 'src/Blocks', group)) && ['styles-admin.css$', 'styles-admin\\.css$'].includes(pattern.source) && !pattern.flags,
|
|
242
266
|
},
|
|
243
267
|
],
|
|
244
268
|
}).setup(builder);
|
|
@@ -246,6 +270,8 @@ export function defineThemeBuild({
|
|
|
246
270
|
};
|
|
247
271
|
const pluginContext = {
|
|
248
272
|
root,
|
|
273
|
+
publicPrefix: publicPath,
|
|
274
|
+
scriptUrlIdentifier: editor?.scriptUrlIdentifier ?? '__eightshiftEditorScriptUrl',
|
|
249
275
|
setEditorWorker: (worker) => {
|
|
250
276
|
editorWorker = worker;
|
|
251
277
|
},
|
|
@@ -260,6 +286,10 @@ export function defineThemeBuild({
|
|
|
260
286
|
const workerFactory = media.editorWorker === undefined ? editorWorkerPlugin : media.editorWorker;
|
|
261
287
|
const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
|
|
262
288
|
|
|
289
|
+
if (publish === undefined) {
|
|
290
|
+
plugins.push(browserCssPlugin({ root, outdir, conventionalCss, extraCssByFile, responsiveFiles, retainedStyles }));
|
|
291
|
+
}
|
|
292
|
+
|
|
263
293
|
if (discovery === undefined) {
|
|
264
294
|
plugins.push(allowPureJsxGrouping(discoveryPlugin));
|
|
265
295
|
} else if (discovery) {
|
|
@@ -285,17 +315,23 @@ export function defineThemeBuild({
|
|
|
285
315
|
sharing: 'unified',
|
|
286
316
|
discovery: {
|
|
287
317
|
filter: /application-blocks-editor\.js$/,
|
|
288
|
-
omitContexts: ({ pattern }) =>
|
|
318
|
+
omitContexts: ({ pattern }) => ['styles-editor.css$', 'styles-editor\\.css$'].includes(pattern.source),
|
|
289
319
|
},
|
|
290
320
|
},
|
|
291
321
|
css: async (context) => {
|
|
292
322
|
const { outdir: stage, responsive: generated } = context;
|
|
323
|
+
Object.assign(responsiveFiles, generated);
|
|
293
324
|
|
|
294
325
|
if (css === undefined) {
|
|
295
326
|
for (const surface of ['frontend', 'editor', 'admin']) {
|
|
296
327
|
const name = surface === 'admin' ? 'applicationAdmin' : `applicationBlocks${surface === 'frontend' ? 'Frontend' : 'Editor'}`;
|
|
297
328
|
|
|
298
|
-
await
|
|
329
|
+
const files = await eightshiftCssEntries({ projectDir: root, surface, responsiveFile: generated[surface] });
|
|
330
|
+
await processCss({ projectDir: root, files, outputFile: resolve(stage, 'css', `${name}.css`), production: true });
|
|
331
|
+
|
|
332
|
+
if (surface !== 'editor' && publish === undefined) {
|
|
333
|
+
conventionalCss.set(surface, await collectConventionalCss({ root, files }));
|
|
334
|
+
}
|
|
299
335
|
}
|
|
300
336
|
} else if (css) {
|
|
301
337
|
await css({ ...context, stage, require });
|
|
@@ -316,10 +352,12 @@ export function defineThemeBuild({
|
|
|
316
352
|
|
|
317
353
|
return file.startsWith('package:') ? require.resolve(file.slice(8)) : isAbsolute(file) ? file : resolve(root, file);
|
|
318
354
|
};
|
|
355
|
+
|
|
319
356
|
const temporary = resolve(stage, 'css', `.extra-${randomUUID()}.css`);
|
|
320
357
|
const outputFile = output ? resolve(stage, 'css', output) : temporary;
|
|
358
|
+
const resolvedFiles = files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) }));
|
|
321
359
|
|
|
322
|
-
await processCss({ projectDir: root, outputFile, files:
|
|
360
|
+
await processCss({ projectDir: root, outputFile, files: resolvedFiles, production: true });
|
|
323
361
|
let name = output;
|
|
324
362
|
|
|
325
363
|
if (!name) {
|
|
@@ -339,8 +377,20 @@ export function defineThemeBuild({
|
|
|
339
377
|
await unlink(temporary);
|
|
340
378
|
}
|
|
341
379
|
|
|
380
|
+
retainedStyles.add(name);
|
|
381
|
+
|
|
342
382
|
if (keys) {
|
|
343
|
-
|
|
383
|
+
const group = { href: href ?? `../css/${name}`, files: resolvedFiles };
|
|
384
|
+
styles.push({ keys, href: group.href });
|
|
385
|
+
|
|
386
|
+
if (publish === undefined) {
|
|
387
|
+
for (const entry of resolvedFiles) {
|
|
388
|
+
const file = await realpath(typeof entry === 'string' ? entry : entry.file);
|
|
389
|
+
const groups = extraCssByFile.get(file) ?? [];
|
|
390
|
+
groups.push(group);
|
|
391
|
+
extraCssByFile.set(file, groups);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
344
394
|
}
|
|
345
395
|
}
|
|
346
396
|
|
|
@@ -350,11 +400,13 @@ export function defineThemeBuild({
|
|
|
350
400
|
glob: 'src/Blocks/{components,custom}/**/assets/index.js',
|
|
351
401
|
key: (file) => file.replace(/^src\/Blocks\//, '').replace(/\/assets\/index\.js$/, ''),
|
|
352
402
|
styles,
|
|
403
|
+
...(publish === undefined ? { styleRuntime: browserCssRuntime } : {}),
|
|
353
404
|
});
|
|
354
405
|
discoveryDir = resolve(stage, 'discovery');
|
|
355
406
|
await generateThemeDiscovery({ root, outputDir: discoveryDir, surfaces });
|
|
356
407
|
}
|
|
357
408
|
},
|
|
409
|
+
entryPublicPaths: Object.fromEntries(['frontend', 'admin'].filter((name) => entries === undefined || Object.hasOwn(entries, name)).map((name) => [name, `${publicPath}${name}/`])),
|
|
358
410
|
buildOptions: {
|
|
359
411
|
optimizeImports,
|
|
360
412
|
minify: true,
|
|
@@ -362,11 +414,12 @@ export function defineThemeBuild({
|
|
|
362
414
|
naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
|
|
363
415
|
sourcemap: sourcemaps ? 'external' : 'none',
|
|
364
416
|
loader: { '.js': 'jsx', '.svg': 'file' },
|
|
365
|
-
define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': '
|
|
417
|
+
define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': JSON.stringify(createHash('sha256').update(publicPath).digest('hex').slice(0, 20)) },
|
|
366
418
|
plugins,
|
|
367
419
|
},
|
|
368
420
|
};
|
|
369
421
|
};
|
|
422
|
+
|
|
370
423
|
const defaultPublish = async ({ result, verbose, quiet }) => {
|
|
371
424
|
const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
|
|
372
425
|
|
|
@@ -401,14 +454,18 @@ export function defineThemeBuild({
|
|
|
401
454
|
}
|
|
402
455
|
}
|
|
403
456
|
|
|
457
|
+
for (const surface of ['frontend', 'admin']) {
|
|
458
|
+
if (result.entries[surface].styles.length) {
|
|
459
|
+
throw new Error(`Unexpected Bun CSS output for ${surface}; a custom plugin bypassed the theme CSS loader. Configure a compatible plugin or custom publication.`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
404
463
|
const surfaces = { frontend: 'applicationBlocksFrontend', editor: 'applicationBlocksEditor', admin: 'applicationAdmin' };
|
|
405
|
-
const flatDir = resolve(outdir, '
|
|
406
|
-
|
|
464
|
+
const flatDir = resolve(outdir, 'structured');
|
|
465
|
+
await preserveAssets({
|
|
407
466
|
outdir,
|
|
408
467
|
flatDir,
|
|
409
468
|
extraSources: editorWorker ? { [`editor/editor-assets/${basename(editorWorker)}`]: editorWorker } : {},
|
|
410
|
-
editorEntry: result.entries.editor.entry,
|
|
411
|
-
editorScript,
|
|
412
469
|
});
|
|
413
470
|
// Webpack exposed standalone images by basename, even when not imported by JS.
|
|
414
471
|
const standaloneAssets = new Map();
|
|
@@ -425,7 +482,22 @@ export function defineThemeBuild({
|
|
|
425
482
|
|
|
426
483
|
const entries = Object.entries(surfaces).map(([surface, name]) => {
|
|
427
484
|
const entry = result.entries[surface];
|
|
428
|
-
|
|
485
|
+
let script;
|
|
486
|
+
|
|
487
|
+
if (surface === 'editor') {
|
|
488
|
+
if (entry.format === 'module') {
|
|
489
|
+
script = editorScript.replace(/^(import ["'])\.\//gm, `$1./${entry.entry.slice(0, entry.entry.lastIndexOf('/') + 1)}`);
|
|
490
|
+
} else {
|
|
491
|
+
const wrapper = '})(document.currentScript.src);\n';
|
|
492
|
+
|
|
493
|
+
if (editorScript.split(wrapper).length !== 2) {
|
|
494
|
+
throw new Error('Cannot relocate the classic editor script wrapper');
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
script = editorScript.replace(wrapper, () => `})(new URL(${JSON.stringify(entry.entry)}, document.currentScript.src).href);\n`);
|
|
498
|
+
script = script.replace(/^(\/\/# sourceMappingURL=)([^\r\n]+)$/m, (_match, prefix, map) => `${prefix}${entry.entry.slice(0, entry.entry.lastIndexOf('/') + 1)}${map}`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
429
501
|
|
|
430
502
|
if (verbose && !quiet) {
|
|
431
503
|
console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
|
|
@@ -433,14 +505,14 @@ export function defineThemeBuild({
|
|
|
433
505
|
|
|
434
506
|
return {
|
|
435
507
|
name,
|
|
436
|
-
entry:
|
|
437
|
-
style:
|
|
508
|
+
entry: entry.entry,
|
|
509
|
+
style: `css/${name}.css`,
|
|
438
510
|
dependencies: entry.dependencies,
|
|
439
511
|
...(script && { script }),
|
|
440
512
|
...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
|
|
441
513
|
};
|
|
442
514
|
});
|
|
443
|
-
const publicationResult = await publication({ root, outdir, result });
|
|
515
|
+
const publicationResult = await publication({ root, outdir, result, publicationRoot: flatDir });
|
|
444
516
|
const additions = publicationResult === undefined ? {} : publicationResult;
|
|
445
517
|
|
|
446
518
|
if (!additions || typeof additions !== 'object' || Array.isArray(additions)) {
|
|
@@ -460,16 +532,19 @@ export function defineThemeBuild({
|
|
|
460
532
|
throw new Error(`Duplicate publication alias: ${key}`);
|
|
461
533
|
}
|
|
462
534
|
}
|
|
463
|
-
|
|
535
|
+
|
|
536
|
+
const fontAssets = sharedFonts ? await prepareSharedFonts({ root, flatDir, retainedStyles }) : { extraFiles: [], aliases: {} };
|
|
537
|
+
|
|
464
538
|
if (sharedFonts && (Object.hasOwn(aliases, 'shared-fonts.json') || Object.hasOwn(additions.aliases ?? {}, 'shared-fonts.json'))) {
|
|
465
539
|
throw new Error('shared-fonts.json is reserved when sharedFonts is enabled');
|
|
466
540
|
}
|
|
541
|
+
|
|
467
542
|
const { release, version, manifest } = await packageFlatRelease({
|
|
468
543
|
extraFiles: [...fontAssets.extraFiles, ...(additions.extraFiles ?? [])],
|
|
469
544
|
retain: additions.retain,
|
|
470
545
|
previousPublic: resolve(root, 'public'),
|
|
471
546
|
root: outdir,
|
|
472
|
-
|
|
547
|
+
removeUnreferencedStyles: css === undefined,
|
|
473
548
|
flatDir,
|
|
474
549
|
entries,
|
|
475
550
|
ssrDir,
|
|
@@ -481,6 +556,7 @@ export function defineThemeBuild({
|
|
|
481
556
|
await publishFlatRelease({ root, wpRoot, release, manifest, version, publicPrefix: publicPath });
|
|
482
557
|
await clearBuildDirectory(outdir, root);
|
|
483
558
|
};
|
|
559
|
+
|
|
484
560
|
const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
|
|
485
561
|
const customSsr = ssr ?? buildSsr;
|
|
486
562
|
const definition = defineBuild({
|
|
@@ -490,7 +566,7 @@ export function defineThemeBuild({
|
|
|
490
566
|
publish !== undefined && ssr !== false
|
|
491
567
|
? async (state) => {
|
|
492
568
|
if (customSsr) {
|
|
493
|
-
return customSsr({ ...state, mode: 'production' });
|
|
569
|
+
return customSsr({ ...state, mode: 'production', outdir: resolve(outdir, 'ssr', 'production') });
|
|
494
570
|
}
|
|
495
571
|
|
|
496
572
|
for await (const _file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root, onlyFiles: true })) {
|
package/bun/theme-discovery.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { dirname, resolve } from 'node:path';
|
|
2
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
3
|
+
import { Linter } from 'eslint';
|
|
3
4
|
import { generateDiscovery } from './discovery.mjs';
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -34,8 +35,8 @@ export async function generateThemeDiscovery({ root, outputDir, surfaces }) {
|
|
|
34
35
|
* loads remove their link and can be retried. URLs resolve relative to the
|
|
35
36
|
* generated JavaScript module, matching Bun's import.meta.url behavior.
|
|
36
37
|
*/
|
|
37
|
-
export async function generateThemeImporters({ root, glob, key, styles = [] }) {
|
|
38
|
-
if (!root || typeof glob !== 'string' || typeof key !== 'function' || !Array.isArray(styles)) {
|
|
38
|
+
export async function generateThemeImporters({ root, glob, key, styles = [], styleRuntime }) {
|
|
39
|
+
if (!root || typeof glob !== 'string' || typeof key !== 'function' || !Array.isArray(styles) || (styleRuntime !== undefined && (typeof styleRuntime !== 'string' || !styleRuntime))) {
|
|
39
40
|
throw new TypeError('Expected root, glob, key and styles');
|
|
40
41
|
}
|
|
41
42
|
|
|
@@ -71,9 +72,10 @@ export async function generateThemeImporters({ root, glob, key, styles = [] }) {
|
|
|
71
72
|
}
|
|
72
73
|
|
|
73
74
|
const loaders = styles
|
|
74
|
-
.map(
|
|
75
|
-
|
|
76
|
-
`
|
|
75
|
+
.map(({ href }, index) =>
|
|
76
|
+
styleRuntime
|
|
77
|
+
? `const loadStyle${index} = () => __eightshiftLoadStylesheet(new URL(${JSON.stringify(href)}, import.meta.url).href);`
|
|
78
|
+
: `let stylePromise${index};
|
|
77
79
|
const loadStyle${index} = () => stylePromise${index} ??= new Promise((resolve, reject) => {
|
|
78
80
|
const link = document.createElement('link');
|
|
79
81
|
link.rel = 'stylesheet';
|
|
@@ -95,15 +97,115 @@ const loadStyle${index} = () => stylePromise${index} ??= new Promise((resolve, r
|
|
|
95
97
|
return `${JSON.stringify(name)}: ${style === undefined ? importer : `() => loadStyle${style}().then(${importer})`}`;
|
|
96
98
|
});
|
|
97
99
|
|
|
98
|
-
return `${loaders}\nconst bunFrontendImporters = {${importers.join(',')}};`;
|
|
100
|
+
return `${styleRuntime && styles.length ? `import { loadStylesheet as __eightshiftLoadStylesheet } from ${JSON.stringify(styleRuntime)};\n` : ''}${loaders}\nconst bunFrontendImporters = {${importers.join(',')}};`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function transformEagerContexts(source, path, root, output, omitContexts) {
|
|
104
|
+
const calls = [];
|
|
105
|
+
const identifiers = new Set();
|
|
106
|
+
const messages = new Linter().verify(
|
|
107
|
+
source,
|
|
108
|
+
[
|
|
109
|
+
{
|
|
110
|
+
languageOptions: { ecmaVersion: 'latest', sourceType: 'module', parserOptions: { ecmaFeatures: { jsx: true } } },
|
|
111
|
+
linterOptions: { noInlineConfig: true },
|
|
112
|
+
plugins: {
|
|
113
|
+
capture: {
|
|
114
|
+
rules: {
|
|
115
|
+
contexts: {
|
|
116
|
+
create: () => ({
|
|
117
|
+
Identifier: (node) => identifiers.add(node.name),
|
|
118
|
+
CallExpression: (node) => {
|
|
119
|
+
const context = node.arguments[0];
|
|
120
|
+
|
|
121
|
+
if (
|
|
122
|
+
node.callee.type === 'Identifier' &&
|
|
123
|
+
node.callee.name === 'dynamicImport' &&
|
|
124
|
+
!node.optional &&
|
|
125
|
+
node.arguments.length === 1 &&
|
|
126
|
+
context?.type === 'CallExpression' &&
|
|
127
|
+
context.callee.type === 'MemberExpression' &&
|
|
128
|
+
!context.callee.computed &&
|
|
129
|
+
context.callee.object.name === 'require' &&
|
|
130
|
+
context.callee.property.name === 'context'
|
|
131
|
+
) {
|
|
132
|
+
calls.push({ node, context });
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
}),
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
rules: { 'capture/contexts': 'error' },
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
{ filename: 'module.js' },
|
|
144
|
+
);
|
|
145
|
+
const fatal = messages.find((message) => message.fatal);
|
|
146
|
+
|
|
147
|
+
if (fatal) {
|
|
148
|
+
throw new Error(`Cannot parse ${path}: ${fatal.message}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const definitions = [];
|
|
152
|
+
const replacements = [];
|
|
153
|
+
|
|
154
|
+
for (const { node, context } of calls) {
|
|
155
|
+
const [directory, recursive, pattern, mode] = context.arguments;
|
|
156
|
+
|
|
157
|
+
if (
|
|
158
|
+
context.optional ||
|
|
159
|
+
context.arguments.length < 3 ||
|
|
160
|
+
context.arguments.length > 4 ||
|
|
161
|
+
directory?.type !== 'Literal' ||
|
|
162
|
+
typeof directory.value !== 'string' ||
|
|
163
|
+
recursive?.type !== 'Literal' ||
|
|
164
|
+
recursive.value !== true ||
|
|
165
|
+
!pattern?.regex ||
|
|
166
|
+
(mode && (mode.type !== 'Literal' || mode.value !== 'sync'))
|
|
167
|
+
) {
|
|
168
|
+
throw new Error(`Unsupported eager require.context in ${path}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const definition = { directory: resolve(dirname(path), directory.value), pattern: new RegExp(pattern.regex.pattern, pattern.regex.flags) };
|
|
172
|
+
let replacement = 'void 0';
|
|
173
|
+
|
|
174
|
+
if (!omitContexts?.({ ...definition, path })) {
|
|
175
|
+
let index = definitions.length;
|
|
176
|
+
let name = `eagerContext${index}`;
|
|
177
|
+
|
|
178
|
+
while (identifiers.has(name)) {
|
|
179
|
+
name = `eagerContext${++index}`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
identifiers.add(name);
|
|
183
|
+
definitions.push({ ...definition, name });
|
|
184
|
+
replacement = `${name}.keys().forEach(${name})`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
replacements.push({ start: node.start, end: node.end, replacement });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
for (const { start, end, replacement } of replacements.sort((a, b) => b.start - a.start)) {
|
|
191
|
+
source = source.slice(0, start) + replacement + source.slice(end);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (definitions.length) {
|
|
195
|
+
await generateDiscovery({ root, output, definitions });
|
|
196
|
+
source = `import { ${definitions.map(({ name }) => name).join(', ')} } from ${JSON.stringify(output)};\n${source}`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return source;
|
|
99
200
|
}
|
|
100
201
|
|
|
101
202
|
/**
|
|
102
203
|
* Transform only explicitly selected entry paths. Each entry specifies
|
|
103
204
|
* { path, module, imports, importStatement, replacements, prefix, remove }.
|
|
104
205
|
* Replacements are [literal, replacement] pairs and must occur exactly once.
|
|
105
|
-
* `remove` is an optional array of RegExps
|
|
106
|
-
*
|
|
206
|
+
* `remove` is an optional array of RegExps. Remaining eager dynamicImport
|
|
207
|
+
* contexts are generated; `omitContexts` selects separately handled styles.
|
|
208
|
+
* Other webpack discovery is rejected. `prefix` can contain the importer map.
|
|
107
209
|
*/
|
|
108
210
|
export function themeDiscoveryPlugin({ root, entries }) {
|
|
109
211
|
if (!root || !Array.isArray(entries)) {
|
|
@@ -160,6 +262,8 @@ export function themeDiscoveryPlugin({ root, entries }) {
|
|
|
160
262
|
source = source.replace(pattern, '');
|
|
161
263
|
}
|
|
162
264
|
|
|
265
|
+
source = await transformEagerContexts(source, path, root, resolve(dirname(resolve(root, entry.module)), `${basename(path)}.contexts.mjs`), entry.omitContexts);
|
|
266
|
+
|
|
163
267
|
if (source.includes('require.context') || source.includes('dynamicImport(')) {
|
|
164
268
|
throw new Error(`Unsupported discovery remains in ${path}`);
|
|
165
269
|
}
|