@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.
Files changed (40) hide show
  1. package/.github/CODEOWNERS +1 -1
  2. package/CHANGELOG.md +19 -1
  3. package/README.md +187 -0
  4. package/bin/tw-sweep.mjs +281 -0
  5. package/bun/build.mjs +341 -0
  6. package/bun/cli.mjs +77 -0
  7. package/bun/css.mjs +145 -0
  8. package/bun/discovery.mjs +121 -0
  9. package/bun/editor.mjs +105 -0
  10. package/bun/eightshift-css.mjs +66 -0
  11. package/bun/eightshift-discovery.mjs +135 -0
  12. package/bun/flat-publication.mjs +343 -0
  13. package/bun/index.mjs +118 -0
  14. package/bun/media.mjs +49 -0
  15. package/bun/preset.mjs +118 -0
  16. package/bun/publish.mjs +236 -0
  17. package/bun/release.mjs +182 -0
  18. package/{webpack/responsive-compiler.mjs → bun/responsive.mjs} +18 -39
  19. package/bun/ssr.mjs +89 -0
  20. package/bun/theme-build.mjs +464 -0
  21. package/bun/theme-discovery.mjs +171 -0
  22. package/bun/watch.mjs +211 -0
  23. package/bun/wordpress.mjs +173 -0
  24. package/linters/oxlint.config.mjs +65 -0
  25. package/linters/tw-ignore.mjs +45 -0
  26. package/linters/tw-sweep-extract.mjs +545 -0
  27. package/package.json +16 -16
  28. package/test/fixtures/theme/src/Blocks/custom/card/card.php +23 -0
  29. package/test/fixtures/theme/src/Blocks/custom/card/manifest.json +13 -0
  30. package/test/fixtures/theme/src/Plugins/Forms.php +15 -0
  31. package/test/fixtures/theme/src/card.js +2 -0
  32. package/test/fixtures/theme/tailwind.css +6 -0
  33. package/test/fixtures/theme/tw-ignore.json +1 -0
  34. package/test/tw-sweep.test.mjs +119 -0
  35. package/bun.lock +0 -1433
  36. package/webpack/base.mjs +0 -126
  37. package/webpack/helpers.mjs +0 -55
  38. package/webpack/index.mjs +0 -46
  39. package/webpack/production.mjs +0 -60
  40. package/webpack/project.mjs +0 -50
@@ -0,0 +1,182 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+
5
+ const digest = (value) => createHash('sha256').update(value).digest('hex');
6
+
7
+ async function ensureDirectory(directory, root) {
8
+ const location = root && relative(root, directory);
9
+ const withinRoot = root && (!location || (!isAbsolute(location) && location !== '..' && !location.startsWith(`..${sep}`)));
10
+ const parent = dirname(directory);
11
+ if (parent !== directory && (!withinRoot || directory !== root)) {
12
+ await ensureDirectory(parent, root);
13
+ }
14
+
15
+ try {
16
+ await mkdir(directory, { recursive: directory === root });
17
+ } catch (error) {
18
+ if (error.code !== 'EEXIST') {
19
+ throw error;
20
+ }
21
+ }
22
+
23
+ const info = await lstat(directory);
24
+ if (!info.isDirectory() || info.isSymbolicLink()) {
25
+ throw new Error(`Release path must be a real directory: ${directory}`);
26
+ }
27
+ }
28
+
29
+ const releasePath = (value) => {
30
+ if (typeof value !== 'string' || !value || value.includes('\\') || value.includes('\0') || isAbsolute(value) || value.split('/').some((part) => !part || part === '.' || part === '..')) {
31
+ throw new Error(`Invalid release path: ${String(value)}`);
32
+ }
33
+
34
+ return value;
35
+ };
36
+
37
+ /**
38
+ * Package a WordPress release without modifying or deleting existing releases.
39
+ *
40
+ * files: [{ source, destination }] copies files or directory trees.
41
+ * entries: [{ name, entry, style, dependencies, script? }] generates the root
42
+ * scripts and WordPress asset metadata. script supplies synchronous editor code;
43
+ * otherwise a dynamic-import bootstrap loads entry relative to the root script.
44
+ * aliases maps additional flat manifest keys to packaged paths.
45
+ * Returns { release, version, manifest }. A failed staging directory is retained.
46
+ * outputDirectory writes directly to an existing directory instead of staging.
47
+ */
48
+ export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory }) {
49
+ if (typeof root !== 'string' || !root || !Array.isArray(files) || !Array.isArray(entries) || !entries.length || !aliases || typeof aliases !== 'object' || Array.isArray(aliases)) {
50
+ throw new TypeError('Expected root, files, entries and optional aliases');
51
+ }
52
+
53
+ const contents = new Map();
54
+ const add = (path, bytes) => {
55
+ releasePath(path);
56
+
57
+ if (contents.has(path)) {
58
+ throw new Error(`Duplicate release path: ${path}`);
59
+ }
60
+
61
+ contents.set(path, bytes);
62
+ };
63
+ const collect = async (source, destination) => {
64
+ const info = await lstat(source);
65
+
66
+ if (info.isSymbolicLink()) {
67
+ throw new Error(`Symlinks are not supported: ${source}`);
68
+ }
69
+
70
+ if (info.isDirectory()) {
71
+ for (const name of (await readdir(source)).sort()) {
72
+ await collect(join(source, name), `${destination}/${name}`);
73
+ }
74
+ } else if (info.isFile()) {
75
+ const bytes = await readFile(source);
76
+
77
+ add(destination, bytes);
78
+ } else {
79
+ throw new Error(`Unsupported release file: ${source}`);
80
+ }
81
+ };
82
+
83
+ for (const file of files) {
84
+ if (!file || typeof file.source !== 'string' || !file.source) {
85
+ throw new TypeError('Each file requires a source and destination');
86
+ }
87
+
88
+ await collect(resolve(file.source), releasePath(file.destination));
89
+ }
90
+
91
+ const manifest = Object.create(null);
92
+ const setManifest = (key, value) => {
93
+ releasePath(key);
94
+ releasePath(value);
95
+
96
+ if (Object.hasOwn(manifest, key)) {
97
+ throw new Error(`Duplicate manifest key: ${key}`);
98
+ }
99
+
100
+ manifest[key] = value;
101
+ };
102
+ const scripts = new Map();
103
+
104
+ for (const entry of entries) {
105
+ if (!entry || typeof entry.name !== 'string' || !/^[A-Za-z0-9_-]+$/.test(entry.name) || !Array.isArray(entry.dependencies) || entry.dependencies.some((dependency) => typeof dependency !== 'string' || !dependency)) {
106
+ throw new TypeError('Invalid release entry');
107
+ }
108
+
109
+ const target = releasePath(entry.entry);
110
+ const style = releasePath(entry.style);
111
+
112
+ if (!contents.has(target) || !contents.has(style) || !contents.get(target).length || !contents.get(style).length) {
113
+ throw new Error(`Missing or empty entry or style for ${entry.name}`);
114
+ }
115
+
116
+ if (entry.script !== undefined && (typeof entry.script !== 'string' || !entry.script.trim())) {
117
+ throw new TypeError(`Invalid script for ${entry.name}`);
118
+ }
119
+
120
+ const script = entry.script ?? `(() => { const url = new URL(${JSON.stringify(target)}, document.currentScript.src); import(url.href).catch((error) => console.error(${JSON.stringify(`Failed to load ${entry.name}:`)}, error)); })();\n`;
121
+
122
+ if (scripts.has(entry.name)) {
123
+ throw new Error(`Duplicate entry: ${entry.name}`);
124
+ }
125
+
126
+ scripts.set(entry.name, { script, dependencies: entry.dependencies });
127
+ const scriptName = `${entry.name}-${digest(script)}.js`;
128
+ const styleBytes = contents.get(style);
129
+ const styleName = `${entry.name}-${digest(styleBytes)}.css`;
130
+
131
+ if (contents.has(scriptName)) {
132
+ throw new Error(`Duplicate release path: ${scriptName}`);
133
+ }
134
+
135
+ if (contents.has(styleName)) {
136
+ throw new Error(`Duplicate release path: ${styleName}`);
137
+ }
138
+
139
+ add(styleName, styleBytes);
140
+ setManifest(`${entry.name}.js`, scriptName);
141
+ setManifest(`${entry.name}.css`, styleName);
142
+ setManifest(`${entry.name}.asset.json`, `${entry.name}.asset.json`);
143
+ setManifest(`${entry.name}.json`, `${entry.name}.asset.json`);
144
+ }
145
+
146
+ for (const [key, value] of Object.entries(aliases)) {
147
+ if (!contents.has(value)) {
148
+ throw new Error(`Missing manifest target: ${value}`);
149
+ }
150
+
151
+ setManifest(key, value);
152
+ }
153
+
154
+ const inventory = Object.fromEntries([...contents].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, bytes]) => [path, digest(bytes)]));
155
+ const version = digest(JSON.stringify({ format: 1, inventory, scripts: [...scripts].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), manifest }));
156
+
157
+ for (const [name, { script, dependencies }] of scripts) {
158
+ add(manifest[`${name}.js`], Buffer.from(script));
159
+ add(`${name}.asset.json`, Buffer.from(`${JSON.stringify({ dependencies, version }, null, 2)}\n`));
160
+ }
161
+
162
+ add('manifest.json', Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`));
163
+ const parent = resolve(root);
164
+
165
+ await ensureDirectory(parent, parent);
166
+ const release = outputDirectory ? resolve(outputDirectory) : join(parent, `release-${randomUUID()}`, version);
167
+
168
+ await ensureDirectory(release, parent);
169
+
170
+ for (const [path, bytes] of contents) {
171
+ const target = resolve(release, ...path.split('/'));
172
+
173
+ if (relative(release, target).startsWith(`..${sep}`)) {
174
+ throw new Error(`Invalid release path: ${path}`);
175
+ }
176
+
177
+ await ensureDirectory(dirname(target), parent);
178
+ await writeFile(target, bytes, { flag: 'wx' });
179
+ }
180
+
181
+ return { release, version, manifest: { ...manifest } };
182
+ }
@@ -27,6 +27,7 @@ const addClasses = (value, breakpoints, output, isResponsive = false) => {
27
27
 
28
28
  if (Array.isArray(value)) {
29
29
  value.forEach((item) => addClasses(item, breakpoints, output, isResponsive));
30
+
30
31
  return;
31
32
  }
32
33
 
@@ -52,6 +53,7 @@ const addClasses = (value, breakpoints, output, isResponsive = false) => {
52
53
  .forEach((token) => {
53
54
  if (isResponsiveToken(token, breakpoints)) {
54
55
  output.add(token);
56
+
55
57
  return;
56
58
  }
57
59
 
@@ -71,12 +73,14 @@ const collectTailwindClasses = (value, allowedKeys, breakpoints, output) => {
71
73
 
72
74
  if (Array.isArray(value)) {
73
75
  value.forEach((item) => collectTailwindClasses(item, allowedKeys, breakpoints, output));
76
+
74
77
  return;
75
78
  }
76
79
 
77
80
  Object.entries(value).forEach(([key, item]) => {
78
81
  if (allowedKeys.has(key)) {
79
82
  addClasses(item, breakpoints, output, value.responsive === true);
83
+
80
84
  return;
81
85
  }
82
86
 
@@ -104,62 +108,37 @@ const runPreprocess = ({ projectDir, breakpoints, manifestGlob, outputFrontend,
104
108
 
105
109
  matches.forEach((filePath) => {
106
110
  const result = processManifest(filePath, breakpoints);
111
+
107
112
  result.frontend.forEach((cls) => frontend.add(cls));
108
113
  result.editor.forEach((cls) => editor.add(cls));
109
114
  });
110
115
 
116
+ fs.mkdirSync(path.dirname(outputFrontend), { recursive: true });
117
+ fs.mkdirSync(path.dirname(outputEditor), { recursive: true });
111
118
  fs.writeFileSync(outputFrontend, [...frontend].join(' '));
112
119
  fs.writeFileSync(outputEditor, [...editor].join(' '));
113
120
  };
114
121
 
115
122
  /**
116
- * Factory returning a webpack plugin that regenerates Tailwind class source
117
- * files before each build and on every manifest change in watch mode.
123
+ * Generate responsive Tailwind class source files without a bundler.
118
124
  *
119
- * @param {object} options
120
- * @param {string} options.projectDir Absolute path to the project root.
121
- * @param {string[]} [options.breakpoints] Tailwind breakpoint prefixes to expand. Defaults to `['sm', 'md']`.
122
- * @param {string} [options.manifestGlob] Glob (relative to `projectDir`) used to find manifests. Defaults to `src/**\/manifest.json`.
123
- * @param {{ frontend?: string, editor?: string }} [options.output] Override absolute output paths.
125
+ * @param {object} options Compiler options.
126
+ * @param {string} options.projectDir Absolute project directory.
127
+ * @param {string[]} [options.breakpoints] Responsive breakpoint prefixes.
128
+ * @param {string} [options.manifestGlob] Manifest glob relative to the project.
129
+ * @param {{ frontend?: string, editor?: string }} [options.output] Output paths.
130
+ * @returns {void}
124
131
  */
125
- export const esTwResponsiveCompiler = ({ projectDir, breakpoints = DEFAULT_BREAKPOINTS, manifestGlob = DEFAULT_MANIFEST_GLOB, output = {} } = {}) => {
132
+ export const generateResponsiveClasses = ({ projectDir, breakpoints = DEFAULT_BREAKPOINTS, manifestGlob = DEFAULT_MANIFEST_GLOB, output = {} } = {}) => {
126
133
  if (!projectDir) {
127
- throw new Error('esTwResponsiveCompiler: `projectDir` is required.');
134
+ throw new Error('generateResponsiveClasses: `projectDir` is required.');
128
135
  }
129
136
 
130
- const config = {
137
+ runPreprocess({
131
138
  projectDir,
132
139
  breakpoints,
133
140
  manifestGlob,
134
141
  outputFrontend: output.frontend ?? path.resolve(projectDir, 'es-tw-frontend-classes.txt'),
135
142
  outputEditor: output.editor ?? path.resolve(projectDir, 'es-tw-editor-classes.txt'),
136
- };
137
-
138
- const run = (label) => {
139
- console.log(`🔄 ${label}`);
140
- try {
141
- runPreprocess(config);
142
- console.log('✅ Done!');
143
- } catch (error) {
144
- console.error('❌ Failed. ', error);
145
- }
146
- };
147
-
148
- return {
149
- apply(compiler) {
150
- compiler.hooks.beforeRun.tap('EsTwResponsiveCompiler', () => {
151
- run('Generating Tailwind manifest class sources');
152
- });
153
-
154
- compiler.hooks.watchRun.tapAsync('EsTwResponsiveCompiler', ({ modifiedFiles }, callback) => {
155
- const manifestChanged = modifiedFiles && [...modifiedFiles].some((file) => file.includes('manifest.json'));
156
-
157
- if (manifestChanged) {
158
- run('A manifest was modified, re-running Tailwind manifest class generation');
159
- }
160
-
161
- callback();
162
- });
163
- },
164
- };
143
+ });
165
144
  };
package/bun/ssr.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+
4
+ /** Discover SSR entries by their block/component directory name. */
5
+ export async function discoverSsrEntries({ root, pattern = 'src/**/assets-ssr/ssr.{js,mjs}' }) {
6
+ if (typeof root !== 'string' || !root || typeof pattern !== 'string' || !pattern) {
7
+ throw new TypeError('Expected root and a valid SSR glob pattern');
8
+ }
9
+
10
+ const entries = new Map();
11
+
12
+ for await (const file of new Bun.Glob(pattern).scan({ cwd: resolve(root), onlyFiles: true })) {
13
+ const name = basename(dirname(dirname(file)));
14
+
15
+ if (entries.has(name)) {
16
+ throw new Error(`Duplicate SSR entry name: ${name}`);
17
+ }
18
+
19
+ entries.set(name, resolve(root, file));
20
+ }
21
+
22
+ if (!entries.size) {
23
+ throw new Error('No SSR entries found.');
24
+ }
25
+
26
+ return new Map([...entries].sort(([a], [b]) => a.localeCompare(b)));
27
+ }
28
+
29
+ /** Treat CSS imports as source text, matching the theme SSR build. */
30
+ export function ssrCssAsText() {
31
+ return {
32
+ name: 'css-as-source',
33
+ setup(build) {
34
+ build.onLoad({ filter: /\.css$/ }, async ({ path }) => ({ contents: await readFile(path, 'utf8'), loader: 'text' }));
35
+ },
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Build discovered SSR entries as individual Node CJS bundles. Paths are
41
+ * relative to root unless absolute. Caller plugins run before the CSS plugin;
42
+ * pass cssAsText: false to disable it. write: false returns in-memory outputs.
43
+ */
44
+ export async function buildSsr({ root, outdir, pattern, mode = 'development', plugins = [], cssAsText = true, write = true }) {
45
+ if (typeof root !== 'string' || !root || typeof outdir !== 'string' || !outdir || !['development', 'production'].includes(mode) || !Array.isArray(plugins) || typeof cssAsText !== 'boolean' || typeof write !== 'boolean') {
46
+ throw new TypeError('Invalid SSR build options');
47
+ }
48
+
49
+ const directory = resolve(root, outdir);
50
+ const entries = await discoverSsrEntries({ root, pattern });
51
+ const outputs = [];
52
+
53
+ for (const [name, entrypoint] of entries) {
54
+ const result = await Bun.build({
55
+ entrypoints: [entrypoint],
56
+ outdir: directory,
57
+ write: false,
58
+ naming: `${name}.js`,
59
+ target: 'node',
60
+ format: 'cjs',
61
+ splitting: false,
62
+ minify: mode === 'production',
63
+ sourcemap: 'none',
64
+ loader: { '.js': 'jsx' },
65
+ define: { 'process.env.NODE_ENV': JSON.stringify(mode) },
66
+ plugins: [...plugins, ...(cssAsText ? [ssrCssAsText()] : [])],
67
+ });
68
+
69
+ if (!result.success) {
70
+ throw new AggregateError(result.logs, `SSR build failed: ${name}`);
71
+ }
72
+
73
+ if (result.outputs.length !== 1 || result.outputs[0].kind !== 'entry-point') {
74
+ throw new Error(`Unexpected SSR output count or kind for ${name}: ${result.outputs.length}`);
75
+ }
76
+
77
+ outputs.push({ name, entrypoint, path: resolve(directory, `${name}.js`), output: result.outputs[0], logs: result.logs });
78
+ }
79
+
80
+ if (write) {
81
+ await mkdir(directory, { recursive: true });
82
+
83
+ for (const { path, output } of outputs) {
84
+ await writeFile(path, await output.arrayBuffer());
85
+ }
86
+ }
87
+
88
+ return { entries, outputs };
89
+ }