@eightshift/frontend-libs-tailwind 3.4.0 → 4.0.0-beta.1
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/.github/CODEOWNERS +1 -1
- package/CHANGELOG.md +19 -1
- package/README.md +187 -0
- package/bin/tw-sweep.mjs +281 -0
- package/bun/build.mjs +341 -0
- package/bun/cli.mjs +77 -0
- package/bun/css.mjs +145 -0
- package/bun/discovery.mjs +121 -0
- package/bun/editor.mjs +105 -0
- package/bun/eightshift-css.mjs +66 -0
- package/bun/eightshift-discovery.mjs +135 -0
- package/bun/flat-publication.mjs +343 -0
- package/bun/index.mjs +118 -0
- package/bun/media.mjs +49 -0
- package/bun/preset.mjs +118 -0
- package/bun/publish.mjs +236 -0
- package/bun/release.mjs +182 -0
- package/{webpack/responsive-compiler.mjs → bun/responsive.mjs} +18 -39
- package/bun/ssr.mjs +89 -0
- package/bun/theme-build.mjs +464 -0
- package/bun/theme-discovery.mjs +171 -0
- package/bun/watch.mjs +211 -0
- package/bun/wordpress.mjs +173 -0
- package/linters/oxlint.config.mjs +65 -0
- package/linters/tw-ignore.mjs +45 -0
- package/linters/tw-sweep-extract.mjs +545 -0
- package/package.json +16 -16
- package/test/fixtures/theme/src/Blocks/custom/card/card.php +23 -0
- package/test/fixtures/theme/src/Blocks/custom/card/manifest.json +13 -0
- package/test/fixtures/theme/src/Plugins/Forms.php +15 -0
- package/test/fixtures/theme/src/card.js +2 -0
- package/test/fixtures/theme/tailwind.css +6 -0
- package/test/fixtures/theme/tw-ignore.json +1 -0
- package/test/tw-sweep.test.mjs +119 -0
- package/bun.lock +0 -1433
- package/webpack/base.mjs +0 -126
- package/webpack/helpers.mjs +0 -55
- package/webpack/index.mjs +0 -46
- package/webpack/production.mjs +0 -60
- package/webpack/project.mjs +0 -50
package/bun/editor.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { eightshiftDiscovery, editorLazyImports } from './eightshift-discovery.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build a synchronous classic entry and lazy ESM chunks. Discovery, when
|
|
7
|
+
* supplied, is composed with lazy rewriting so both can process one file.
|
|
8
|
+
* Other onLoad plugins that consume the same file must compose the rewrite.
|
|
9
|
+
* Editor output must not require extracted CSS or other emitted assets.
|
|
10
|
+
*/
|
|
11
|
+
export async function buildEditor({ root, directory, entry, buildOptions = {}, plugins = [], chunkDir = 'editor-chunks', filename = 'editor.js', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', discovery, lazy = {} }) {
|
|
12
|
+
const inside = (path) => {
|
|
13
|
+
if (typeof path !== 'string' || !path || isAbsolute(path)) {
|
|
14
|
+
throw new TypeError('Editor output paths must be relative');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const output = resolve(directory, path);
|
|
18
|
+
const location = relative(directory, output);
|
|
19
|
+
|
|
20
|
+
if (!location || location === '..' || location.startsWith(`..${sep}`) || isAbsolute(location)) {
|
|
21
|
+
throw new Error(`Editor output escapes entry directory: ${path}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return output;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
if (filename.includes('/') || filename.includes('\\')) {
|
|
28
|
+
throw new TypeError('Editor filename must be a basename');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const entryOutput = inside(filename);
|
|
32
|
+
const chunkOutput = inside(chunkDir);
|
|
33
|
+
|
|
34
|
+
if (relative(chunkOutput, entryOutput) === '' || (!relative(chunkOutput, entryOutput).startsWith(`..${sep}`) && relative(chunkOutput, entryOutput) !== '..')) {
|
|
35
|
+
throw new Error('Editor entry cannot be inside its chunk directory');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (buildOptions.sourcemap !== undefined && !['none', 'external'].includes(buildOptions.sourcemap)) {
|
|
39
|
+
throw new TypeError('Editor sourcemap must be "none" or "external"');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const chunks = new Map();
|
|
43
|
+
const lazyImports = editorLazyImports({ ...lazy, root, chunks, chunkDir, scriptUrlIdentifier });
|
|
44
|
+
const discoveryPlugin = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery'), transformSource: (source, path) => lazyImports.transformSource(discovery.transformSource ? discovery.transformSource(source, path) : source, path) }) : undefined;
|
|
45
|
+
const sourcemap = buildOptions.sourcemap === 'external';
|
|
46
|
+
const options = {
|
|
47
|
+
target: 'browser',
|
|
48
|
+
...buildOptions,
|
|
49
|
+
loader: { ...buildOptions.loader, '.svg': 'text' },
|
|
50
|
+
sourcemap: sourcemap ? 'external' : 'none',
|
|
51
|
+
entrypoints: [resolve(root, entry)],
|
|
52
|
+
format: 'iife',
|
|
53
|
+
splitting: false,
|
|
54
|
+
write: false,
|
|
55
|
+
plugins: [...(discoveryPlugin ? [discoveryPlugin] : []), ...plugins, lazyImports.plugin],
|
|
56
|
+
};
|
|
57
|
+
const paths = [];
|
|
58
|
+
const compile = async (target, format) => {
|
|
59
|
+
const result = await Bun.build({ ...options, entrypoints: [target], format });
|
|
60
|
+
|
|
61
|
+
if (!result.success) {
|
|
62
|
+
throw new AggregateError(result.logs, `Editor build failed: ${target}`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const entries = result.outputs.filter((output) => output.kind === 'entry-point');
|
|
66
|
+
const maps = result.outputs.filter((output) => output.kind === 'sourcemap');
|
|
67
|
+
if (entries.length !== 1 || maps.length !== (sourcemap ? 1 : 0) || result.outputs.length !== entries.length + maps.length) {
|
|
68
|
+
throw new Error(`Unexpected editor assets: ${target}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const map = sourcemap ? JSON.parse(await maps[0].text()) : undefined;
|
|
72
|
+
if (map) {
|
|
73
|
+
map.mappings = `;${map.mappings}`;
|
|
74
|
+
}
|
|
75
|
+
return { source: await entries[0].text(), map };
|
|
76
|
+
};
|
|
77
|
+
const write = async (path, source) => {
|
|
78
|
+
await mkdir(dirname(path), { recursive: true });
|
|
79
|
+
await writeFile(path, source);
|
|
80
|
+
paths.push(path);
|
|
81
|
+
};
|
|
82
|
+
const entryBuild = await compile(resolve(root, entry), 'iife');
|
|
83
|
+
const entryMap = `${basename(entryOutput)}.map`;
|
|
84
|
+
await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${entryBuild.source}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
|
|
85
|
+
if (entryBuild.map) {
|
|
86
|
+
await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
for (const [target, name] of chunks) {
|
|
90
|
+
const output = inside(`${chunkDir}/${name}`);
|
|
91
|
+
let entryPath = relative(dirname(output), entryOutput).split(sep).join('/');
|
|
92
|
+
|
|
93
|
+
if (!entryPath.startsWith('.')) {
|
|
94
|
+
entryPath = `./${entryPath}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const chunk = await compile(target, 'esm');
|
|
98
|
+
await write(output, `const ${scriptUrlIdentifier} = new URL(${JSON.stringify(entryPath)}, import.meta.url).href;\n${chunk.source}${chunk.map ? `\n//# sourceMappingURL=${basename(output)}.map\n` : ''}`);
|
|
99
|
+
if (chunk.map) {
|
|
100
|
+
await write(`${output}.map`, JSON.stringify(chunk.map));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return { entry: entryOutput, paths };
|
|
105
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { glob } from 'glob';
|
|
3
|
+
import { processCss } from './css.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build the ordered CSS inputs used by migrated Eightshift v3 themes.
|
|
7
|
+
* All paths and glob patterns are relative to projectDir unless absolute.
|
|
8
|
+
* Override paths, groups, manifestGlob or scan exclusions for another layout.
|
|
9
|
+
* responsiveFile replaces the generated @source in the Tailwind entry.
|
|
10
|
+
*/
|
|
11
|
+
export async function eightshiftCssEntries({
|
|
12
|
+
projectDir,
|
|
13
|
+
surface,
|
|
14
|
+
responsiveFile,
|
|
15
|
+
blocksDir = 'src/Blocks',
|
|
16
|
+
manifestGlob = 'src/**/manifest.json',
|
|
17
|
+
tailwindFile = `tailwind-${surface}.css`,
|
|
18
|
+
colorThemesFile = 'color-themes.css',
|
|
19
|
+
applicationFile = surface === 'admin' ? `${blocksDir}/assets/styles/application-admin.css` : `${blocksDir}/assets/styles/application-blocks-${surface}.css`,
|
|
20
|
+
groups = surface === 'admin' ? ['components', 'custom'] : ['components', 'custom', 'wrapper'],
|
|
21
|
+
scanExclusions = ['.bun-pilot/**', 'es-tw-*-classes.txt'],
|
|
22
|
+
responsiveSource = `@source './es-tw-${surface}-classes.txt';`,
|
|
23
|
+
} = {}) {
|
|
24
|
+
if (!projectDir || !['frontend', 'editor', 'admin'].includes(surface)) {
|
|
25
|
+
throw new TypeError('projectDir and a valid CSS surface are required');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const root = resolve(projectDir);
|
|
29
|
+
const styles = [];
|
|
30
|
+
|
|
31
|
+
for (const group of groups) {
|
|
32
|
+
const matches = await glob(`**/*styles-${surface}.css`, { cwd: resolve(root, blocksDir, group), absolute: true, nodir: true, follow: false });
|
|
33
|
+
|
|
34
|
+
styles.push(...matches.sort());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (surface === 'admin') {
|
|
38
|
+
return [applicationFile, ...styles];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!responsiveFile) {
|
|
42
|
+
throw new TypeError('responsiveFile is required for frontend and editor CSS');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const manifests = (await glob(manifestGlob, { cwd: root, absolute: true, nodir: true, follow: false })).sort();
|
|
46
|
+
|
|
47
|
+
return [
|
|
48
|
+
{
|
|
49
|
+
file: tailwindFile,
|
|
50
|
+
scan: true,
|
|
51
|
+
removeSources: responsiveSource ? [responsiveSource] : [],
|
|
52
|
+
sources: scanExclusions.map((pattern) => ({ pattern, negated: true })),
|
|
53
|
+
scanFiles: [responsiveFile, ...manifests],
|
|
54
|
+
},
|
|
55
|
+
colorThemesFile,
|
|
56
|
+
applicationFile,
|
|
57
|
+
...styles,
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Compile one surface. Options accepted by eightshiftCssEntries are forwarded. */
|
|
62
|
+
export async function processEightshiftCss({ outputFile, production = false, browsers, ...options } = {}) {
|
|
63
|
+
const files = await eightshiftCssEntries(options);
|
|
64
|
+
|
|
65
|
+
return processCss({ projectDir: options.projectDir, outputFile, files, production, browsers });
|
|
66
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { dirname, resolve, relative, sep } from 'node:path';
|
|
6
|
+
import { generateDiscovery } from './discovery.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Migrate literal webpack require.context calls in selected source files.
|
|
10
|
+
* Generated modules live in outputDir and must be regenerated on rebuild.
|
|
11
|
+
* Set lazyContexts to match contexts whose callers expect promises, and
|
|
12
|
+
* omitContexts to match contexts handled separately (for example CSS).
|
|
13
|
+
* Template-literal imports and nonliteral require.context calls are not rewritten.
|
|
14
|
+
*/
|
|
15
|
+
export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/, lazyContexts = () => false, omitContexts = () => false, transformSource = (source) => source } = {}) {
|
|
16
|
+
if (!root || !outputDir) {
|
|
17
|
+
throw new TypeError('root and outputDir are required');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
outputDir = resolve(root, outputDir);
|
|
21
|
+
root = realpathSync(root);
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
name: 'eightshift-discovery',
|
|
25
|
+
setup(builder) {
|
|
26
|
+
builder.onLoad({ filter }, async ({ path }) => {
|
|
27
|
+
if (!path.startsWith(`${root}${sep}`)) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const source = await readFile(path, 'utf8');
|
|
32
|
+
|
|
33
|
+
if (!source.includes('require.context')) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const pattern = /require\.context\(\s*(['"])([^'"\n]+)\1\s*,\s*(true|false)\s*,\s*\/(?!\*)(?!\/)((?:\\.|[^/\n])+)\/([dgimsuvy]*)\s*(?:,\s*(['"])(sync|lazy)\6\s*)?\)/g;
|
|
38
|
+
const matches = [...source.matchAll(pattern)];
|
|
39
|
+
|
|
40
|
+
if (!matches.length) {
|
|
41
|
+
throw new Error(`Unsupported require.context in ${path}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const definitions = [];
|
|
45
|
+
let contents = '';
|
|
46
|
+
let offset = 0;
|
|
47
|
+
|
|
48
|
+
for (const match of matches) {
|
|
49
|
+
const [, , directory, recursive, expression, flags, , webpackMode] = match;
|
|
50
|
+
|
|
51
|
+
if (recursive !== 'true') {
|
|
52
|
+
throw new Error(`Nonrecursive require.context is unsupported in ${path}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const context = { path, directory, pattern: new RegExp(expression, flags), mode: webpackMode || 'sync' };
|
|
56
|
+
const name = `context${definitions.length}`;
|
|
57
|
+
|
|
58
|
+
contents += source.slice(offset, match.index);
|
|
59
|
+
|
|
60
|
+
if (omitContexts(context)) {
|
|
61
|
+
contents += 'Object.assign(() => ({}), { keys: () => [] })';
|
|
62
|
+
} else {
|
|
63
|
+
definitions.push({ name, directory: resolve(dirname(path), directory), pattern: context.pattern, mode: lazyContexts(context) ? 'lazy' : context.mode });
|
|
64
|
+
contents += name;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
offset = match.index + match[0].length;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
contents += source.slice(offset);
|
|
71
|
+
|
|
72
|
+
if (contents.includes('require.context')) {
|
|
73
|
+
throw new Error(`Unsupported require.context remains in ${path}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (definitions.length) {
|
|
77
|
+
const id = createHash('sha256').update(relative(root, path)).digest('hex').slice(0, 20);
|
|
78
|
+
const output = resolve(outputDir, `${id}.mjs`);
|
|
79
|
+
|
|
80
|
+
await generateDiscovery({ root, output, definitions });
|
|
81
|
+
contents = `import { ${definitions.map(({ name }) => name).join(', ')} } from ${JSON.stringify(output)};\n${contents}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
contents = transformSource(contents, path);
|
|
85
|
+
|
|
86
|
+
return { contents, loader: 'jsx', resolveDir: dirname(path) };
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Rewrite literal relative dynamic imports for a synchronous IIFE editor build.
|
|
93
|
+
* Build each collected target as an ESM entry with the same plugin, then wrap
|
|
94
|
+
* the IIFE in a function receiving scriptUrlIdentifier from currentScript.src.
|
|
95
|
+
* Chunk URLs are relative to that script. The caller owns chunk output/builds.
|
|
96
|
+
* Pass transformSource to eightshiftDiscovery to compose both onLoad hooks.
|
|
97
|
+
*/
|
|
98
|
+
export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', filter = /\.[cm]?jsx?$/, include = (path) => !path.split(sep).includes('node_modules') } = {}) {
|
|
99
|
+
if (!root || !(chunks instanceof Map) || !/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
|
|
100
|
+
throw new TypeError('Expected root, chunks Map and valid script URL identifier');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
root = realpathSync(resolve(root));
|
|
104
|
+
const require = createRequire(import.meta.url);
|
|
105
|
+
const transformSource = (source, path) =>
|
|
106
|
+
!include(path)
|
|
107
|
+
? source
|
|
108
|
+
: source.replace(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])(\.[^'"\n]+)\1\s*\)/g, (_match, _quote, specifier) => {
|
|
109
|
+
const target = require.resolve(resolve(dirname(path), specifier));
|
|
110
|
+
const name = `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
|
|
111
|
+
|
|
112
|
+
chunks.set(target, name);
|
|
113
|
+
|
|
114
|
+
return `import(new URL(${JSON.stringify(`${chunkDir}/${name}`)}, ${scriptUrlIdentifier}).href)`;
|
|
115
|
+
});
|
|
116
|
+
const plugin = {
|
|
117
|
+
name: 'eightshift-editor-lazy-imports',
|
|
118
|
+
setup(builder) {
|
|
119
|
+
builder.onLoad({ filter }, async ({ path }) => {
|
|
120
|
+
if (!path.startsWith(`${root}${sep}`)) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const source = await readFile(path, 'utf8');
|
|
125
|
+
const contents = transformSource(source, path);
|
|
126
|
+
|
|
127
|
+
if (contents !== source) {
|
|
128
|
+
return { contents, loader: 'jsx', resolveDir: dirname(path) };
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
return { plugin, transformSource };
|
|
135
|
+
}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, lstat, mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, isAbsolute, posix, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { packageRelease } from './release.mjs';
|
|
5
|
+
|
|
6
|
+
const pathName = (value) => {
|
|
7
|
+
if (typeof value !== 'string' || !value || isAbsolute(value) || value.includes('\\') || value.includes('\0') || value.split('/').some((part) => !part || part === '.' || part === '..')) {
|
|
8
|
+
throw new Error(`Invalid path: ${String(value)}`);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return value;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** Collect build outputs and flatten them, rewriting relative JS, CSS and map references.
|
|
15
|
+
* sources maps output-relative paths to source files. Returns the rewrite function.
|
|
16
|
+
*/
|
|
17
|
+
export async function flattenAssets({ outdir, flatDir, directories = ['frontend', 'editor', 'admin', 'css'], extraSources = {}, editorEntry, editorScript }) {
|
|
18
|
+
const sources = new Map();
|
|
19
|
+
const collect = async (directory, prefix) => {
|
|
20
|
+
for (const item of await readdir(directory, { withFileTypes: true })) {
|
|
21
|
+
const path = `${prefix}/${item.name}`;
|
|
22
|
+
|
|
23
|
+
if (path === 'editor/discovery' || (item.isFile() && !prefix.includes('/') && item.name === `${prefix}.asset.json`)) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (item.isDirectory()) {
|
|
28
|
+
await collect(resolve(directory, item.name), path);
|
|
29
|
+
} else if (item.isFile()) {
|
|
30
|
+
sources.set(path, resolve(directory, item.name));
|
|
31
|
+
} else {
|
|
32
|
+
throw new Error(`Unsupported build output: ${path}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
for (const directory of directories) {
|
|
38
|
+
await collect(resolve(outdir, pathName(directory)), directory);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
for (const [path, source] of Object.entries(extraSources)) {
|
|
42
|
+
sources.set(pathName(path), source);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const targetsByName = new Map();
|
|
46
|
+
for (const target of sources.keys()) {
|
|
47
|
+
const name = basename(target);
|
|
48
|
+
const targets = targetsByName.get(name) ?? [];
|
|
49
|
+
targets.push(target);
|
|
50
|
+
targetsByName.set(name, targets);
|
|
51
|
+
}
|
|
52
|
+
const unusualTargets = [...targetsByName].filter(([name]) => !/^[\w.@+-]+$/.test(name)).flatMap(([, targets]) => targets);
|
|
53
|
+
const rewrite = (input, path) => {
|
|
54
|
+
let source = input;
|
|
55
|
+
const candidates = new Set(unusualTargets);
|
|
56
|
+
|
|
57
|
+
for (const match of input.matchAll(/[/'"=]([\w.@+-]+)/g)) {
|
|
58
|
+
for (const target of targetsByName.get(match[1]) ?? []) {
|
|
59
|
+
candidates.add(target);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
for (const target of candidates) {
|
|
64
|
+
const reference = posix.relative(posix.dirname(path), target);
|
|
65
|
+
|
|
66
|
+
if (!reference) {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const variants = [reference];
|
|
71
|
+
|
|
72
|
+
if (!reference.startsWith('.')) {
|
|
73
|
+
variants.push(`./${reference}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (target.startsWith('editor/editor-assets/') || (target.startsWith('editor/') && path.startsWith('editor/'))) {
|
|
77
|
+
variants.push(target.slice('editor/'.length));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
for (const value of variants) {
|
|
81
|
+
for (const quote of ['"', "'"]) {
|
|
82
|
+
source = source.replaceAll(`${quote}${value}${quote}`, `${quote}./${basename(target)}${quote}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
source = source.replaceAll(`sourceMappingURL=${value}`, `sourceMappingURL=./${basename(target)}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return source;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const contentFor = async (path) => {
|
|
93
|
+
const content = await readFile(sources.get(path));
|
|
94
|
+
return /\.(?:js|css|map)$/.test(basename(path)) ? Buffer.from(rewrite(content.toString(), path)) : content;
|
|
95
|
+
};
|
|
96
|
+
const outputNames = new Map();
|
|
97
|
+
for (const path of sources.keys()) {
|
|
98
|
+
if (path === editorEntry) {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const name = basename(path);
|
|
102
|
+
const previous = outputNames.get(name);
|
|
103
|
+
if (previous !== undefined) {
|
|
104
|
+
if (!(await contentFor(path)).equals(await contentFor(previous))) {
|
|
105
|
+
throw new Error(`Flat output collision: ${path} and ${previous}`);
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
outputNames.set(name, path);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
await mkdir(flatDir);
|
|
113
|
+
|
|
114
|
+
for (const [path] of sources) {
|
|
115
|
+
const name = basename(path);
|
|
116
|
+
|
|
117
|
+
if (path === editorEntry || outputNames.get(name) !== path) {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
await writeFile(resolve(flatDir, name), await contentFor(path), { flag: 'wx' });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (editorEntry !== undefined) {
|
|
125
|
+
await writeFile(resolve(flatDir, 'editor-entry.js'), rewrite(editorScript, editorEntry), { flag: 'wx' });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { sources, rewrite };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Package flattened files, optional SSR files and standalone assets. */
|
|
132
|
+
export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, outputDirectory }) {
|
|
133
|
+
const files = [];
|
|
134
|
+
|
|
135
|
+
for (const name of await readdir(flatDir)) {
|
|
136
|
+
files.push({ source: resolve(flatDir, name), destination: name });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const extraAliases = {};
|
|
140
|
+
|
|
141
|
+
for (const name of [...ssrNames].sort()) {
|
|
142
|
+
pathName(name);
|
|
143
|
+
|
|
144
|
+
if (name.includes('/')) {
|
|
145
|
+
throw new Error(`Invalid SSR name: ${name}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
files.push({ source: resolve(ssrDir, `${name}.js`), destination: `ssr/${name}.js` });
|
|
149
|
+
extraAliases[`ssr/${name}.js`] = `ssr/${name}.js`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
for (const [name, source] of standaloneAssets) {
|
|
153
|
+
pathName(name);
|
|
154
|
+
files.push({ source, destination: name });
|
|
155
|
+
extraAliases[name] = name;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Publish a flat release and synchronize an existing PHP asset cache.
|
|
162
|
+
* Staged publication restores the previous public directory on cache failure.
|
|
163
|
+
* Direct publication writes in public and does not roll back. Missing caches are ignored.
|
|
164
|
+
*/
|
|
165
|
+
export async function publishFlatRelease({ root, wpRoot, release, manifest, version, direct = false, publicPrefix }) {
|
|
166
|
+
root = resolve(root);
|
|
167
|
+
wpRoot = resolve(wpRoot);
|
|
168
|
+
release = resolve(release);
|
|
169
|
+
const publicDir = resolve(root, 'public');
|
|
170
|
+
const within = (parent, child) => {
|
|
171
|
+
const path = relative(parent, child);
|
|
172
|
+
|
|
173
|
+
return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
if ((!direct && (within(publicDir, release) || within(release, publicDir) || within(release, root))) || (direct && release !== publicDir)) {
|
|
177
|
+
throw new Error('Release, root and public directory must be distinct');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (publicPrefix === undefined) {
|
|
181
|
+
const themePath = relative(wpRoot, root);
|
|
182
|
+
|
|
183
|
+
if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
|
|
184
|
+
throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
publicPrefix = `/${themePath.split(sep).join('/')}/public/`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (typeof publicPrefix !== 'string' || !publicPrefix.startsWith('/') || publicPrefix.startsWith('//') || !publicPrefix.endsWith('/') || publicPrefix.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPrefix) || publicPrefix.split('/').some((part) => part === '.' || part === '..')) {
|
|
191
|
+
throw new Error('publicPrefix must be a root-relative URL path ending in /');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const info = await lstat(release);
|
|
195
|
+
|
|
196
|
+
if (!info.isDirectory() || info.isSymbolicLink()) {
|
|
197
|
+
throw new Error('Release must be a directory');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const result = { ...manifest };
|
|
201
|
+
|
|
202
|
+
for (const [key, value] of Object.entries(result)) {
|
|
203
|
+
pathName(key);
|
|
204
|
+
pathName(value);
|
|
205
|
+
let current = release;
|
|
206
|
+
|
|
207
|
+
for (const part of value.split('/')) {
|
|
208
|
+
current = resolve(current, part);
|
|
209
|
+
const entry = await lstat(current);
|
|
210
|
+
|
|
211
|
+
if (entry.isSymbolicLink()) {
|
|
212
|
+
throw new Error(`Symlink in release path: ${value}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (!(await lstat(current)).isFile()) {
|
|
217
|
+
throw new Error(`Manifest target is not a file: ${value}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
for (const name of await readdir(release)) {
|
|
222
|
+
const entry = await lstat(resolve(release, name));
|
|
223
|
+
|
|
224
|
+
if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) {
|
|
225
|
+
throw new Error(`Unsupported release output: ${name}`);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (name !== 'manifest.json' && name !== 'ssr' && !(direct && name === '.build') && !Object.hasOwn(result, name)) {
|
|
229
|
+
result[name] = name;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const publicManifest = Object.fromEntries(Object.entries(result).map(([key, value]) => [key, `${publicPrefix}${value}`]));
|
|
234
|
+
|
|
235
|
+
await writeFile(resolve(release, 'manifest.json'), `${JSON.stringify(publicManifest, null, 2)}\n`);
|
|
236
|
+
const backup = resolve(root, `.public-previous-${randomUUID()}`);
|
|
237
|
+
let hadPublic = false;
|
|
238
|
+
|
|
239
|
+
if (!direct) {
|
|
240
|
+
try {
|
|
241
|
+
const publicInfo = await lstat(publicDir);
|
|
242
|
+
|
|
243
|
+
if (!publicInfo.isDirectory() || publicInfo.isSymbolicLink()) {
|
|
244
|
+
throw new Error('Refusing to replace non-directory public path');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
await rename(publicDir, backup);
|
|
248
|
+
hadPublic = true;
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (error.code !== 'ENOENT') {
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
try {
|
|
257
|
+
if (!direct) {
|
|
258
|
+
await rename(release, publicDir);
|
|
259
|
+
}
|
|
260
|
+
const cachePath = resolve(root, 'eightshift/manifests.json');
|
|
261
|
+
let cacheExists = false;
|
|
262
|
+
|
|
263
|
+
try {
|
|
264
|
+
const cacheInfo = await lstat(cachePath);
|
|
265
|
+
if (!cacheInfo.isFile() || cacheInfo.isSymbolicLink()) {
|
|
266
|
+
throw new Error(`Manifest cache must be a regular file: ${cachePath}`);
|
|
267
|
+
}
|
|
268
|
+
cacheExists = true;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.code !== 'ENOENT') {
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (cacheExists) {
|
|
276
|
+
let temporary;
|
|
277
|
+
|
|
278
|
+
try {
|
|
279
|
+
const cacheInfo = await lstat(cachePath);
|
|
280
|
+
if (!cacheInfo.isFile() || cacheInfo.isSymbolicLink()) {
|
|
281
|
+
throw new Error(`Manifest cache must be a regular file: ${cachePath}`);
|
|
282
|
+
}
|
|
283
|
+
const data = JSON.parse(await readFile(cachePath, 'utf8'));
|
|
284
|
+
|
|
285
|
+
if (!data?.assets || Array.isArray(data.assets) || typeof data.assets !== 'object' || !data.assets.assets || Array.isArray(data.assets.assets) || typeof data.assets.assets !== 'object') {
|
|
286
|
+
throw new Error('Invalid manifest cache structure');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
data.assets.assets = publicManifest;
|
|
290
|
+
temporary = `${cachePath}.${randomUUID()}`;
|
|
291
|
+
await writeFile(temporary, JSON.stringify(data), { flag: 'wx', mode: cacheInfo.mode & 0o7777 });
|
|
292
|
+
await chmod(temporary, cacheInfo.mode & 0o7777);
|
|
293
|
+
await rename(temporary, cachePath);
|
|
294
|
+
temporary = undefined;
|
|
295
|
+
} finally {
|
|
296
|
+
if (temporary) {
|
|
297
|
+
await unlink(temporary).catch((error) => {
|
|
298
|
+
if (error.code !== 'ENOENT') {
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (direct) {
|
|
307
|
+
throw error;
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
await rename(publicDir, release);
|
|
311
|
+
} catch (rollbackError) {
|
|
312
|
+
if (rollbackError.code !== 'ENOENT') {
|
|
313
|
+
throw rollbackError;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (hadPublic) {
|
|
318
|
+
await rename(backup, publicDir);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
throw error;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const removeTree = async (path) => {
|
|
325
|
+
const entry = await lstat(path);
|
|
326
|
+
|
|
327
|
+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
328
|
+
for (const name of await readdir(path)) {
|
|
329
|
+
await removeTree(resolve(path, name));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
await rmdir(path);
|
|
333
|
+
} else {
|
|
334
|
+
await unlink(path);
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
if (hadPublic) {
|
|
339
|
+
await removeTree(backup);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
return { publicDir, manifest: publicManifest, version };
|
|
343
|
+
}
|