@eightshift/frontend-libs-tailwind 3.5.0 → 4.0.0-beta.2
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 -0
- package/README.md +231 -0
- package/bun/build.mjs +357 -0
- package/bun/cli.mjs +77 -0
- package/bun/css.mjs +145 -0
- package/bun/discovery.mjs +121 -0
- package/bun/editor-native.mjs +191 -0
- package/bun/editor-pure-jsx.mjs +381 -0
- package/bun/editor.mjs +215 -0
- package/bun/eightshift-css.mjs +66 -0
- package/bun/eightshift-discovery.mjs +140 -0
- package/bun/flat-publication.mjs +411 -0
- package/bun/index.mjs +118 -0
- package/bun/media.mjs +50 -0
- package/bun/plugin-capabilities.mjs +11 -0
- package/bun/preset.mjs +120 -0
- package/bun/publish.mjs +236 -0
- package/bun/release.mjs +207 -0
- package/{webpack/responsive-compiler.mjs → bun/responsive.mjs} +18 -39
- package/bun/ssr.mjs +89 -0
- package/bun/theme-build.mjs +481 -0
- package/bun/theme-discovery.mjs +171 -0
- package/bun/watch.mjs +264 -0
- package/bun/wordpress.mjs +220 -0
- package/package.json +9 -17
- package/bun.lock +0 -1504
- 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
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, isAbsolute, resolve, sep } from 'node:path';
|
|
4
|
+
import { Linter } from 'eslint';
|
|
5
|
+
|
|
6
|
+
const linter = new Linter();
|
|
7
|
+
const inDependencies = (path) => path.split(sep).includes('node_modules');
|
|
8
|
+
const comparePaths = (a, b) => (a.path < b.path ? -1 : Number(a.path > b.path));
|
|
9
|
+
|
|
10
|
+
function parse(source) {
|
|
11
|
+
let ast;
|
|
12
|
+
const messages = linter.verify(
|
|
13
|
+
source,
|
|
14
|
+
[
|
|
15
|
+
{
|
|
16
|
+
languageOptions: { ecmaVersion: 'latest', sourceType: 'module', parserOptions: { ecmaFeatures: { jsx: true } } },
|
|
17
|
+
plugins: {
|
|
18
|
+
capture: {
|
|
19
|
+
rules: {
|
|
20
|
+
ast: {
|
|
21
|
+
create: () => ({
|
|
22
|
+
Program: (node) => {
|
|
23
|
+
ast = node;
|
|
24
|
+
},
|
|
25
|
+
}),
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
rules: { 'capture/ast': 'error' },
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
{ filename: 'module.js' },
|
|
34
|
+
);
|
|
35
|
+
return messages.length ? undefined : ast;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function inspect(source) {
|
|
39
|
+
const ast = parse(source);
|
|
40
|
+
if (!ast) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const factories = new Set();
|
|
44
|
+
const locals = new Set();
|
|
45
|
+
const names = [];
|
|
46
|
+
const pure = (node) => {
|
|
47
|
+
if (!node) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
if (node.type === 'Literal') {
|
|
51
|
+
return !node.regex && (node.value === null || ['string', 'number', 'boolean'].includes(typeof node.value));
|
|
52
|
+
}
|
|
53
|
+
if (node.type === 'UnaryExpression') {
|
|
54
|
+
return ['+', '-', '!'].includes(node.operator) && node.argument.type === 'Literal' && pure(node.argument);
|
|
55
|
+
}
|
|
56
|
+
if (node.type === 'ArrayExpression') {
|
|
57
|
+
return node.elements.every((element) => element === null || pure(element));
|
|
58
|
+
}
|
|
59
|
+
if (node.type === 'ObjectExpression') {
|
|
60
|
+
return node.properties.every((property) => property.type === 'Property' && property.kind === 'init' && !property.method && !property.computed && !property.shorthand && pure(property.value));
|
|
61
|
+
}
|
|
62
|
+
return (
|
|
63
|
+
node.type === 'CallExpression' &&
|
|
64
|
+
!node.optional &&
|
|
65
|
+
node.callee.type === 'Identifier' &&
|
|
66
|
+
factories.has(node.callee.name) &&
|
|
67
|
+
node.arguments.length >= 2 &&
|
|
68
|
+
node.arguments.length <= 3 &&
|
|
69
|
+
node.arguments[0].type === 'Literal' &&
|
|
70
|
+
typeof node.arguments[0].value === 'string' &&
|
|
71
|
+
node.arguments[1].type === 'ObjectExpression' &&
|
|
72
|
+
(node.arguments.length === 2 || node.arguments[2].type === 'Literal') &&
|
|
73
|
+
node.arguments.slice(1).every(pure)
|
|
74
|
+
);
|
|
75
|
+
};
|
|
76
|
+
for (const node of ast.body) {
|
|
77
|
+
if (node.type === 'ImportDeclaration') {
|
|
78
|
+
if (node.source.value !== 'react/jsx-runtime' || !node.specifiers.length || node.attributes?.length) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
for (const specifier of node.specifiers) {
|
|
82
|
+
if (specifier.type !== 'ImportSpecifier' || !['jsx', 'jsxs'].includes(specifier.imported.name) || factories.has(specifier.local.name) || locals.has(specifier.local.name)) {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
factories.add(specifier.local.name);
|
|
86
|
+
}
|
|
87
|
+
} else if (node.type === 'VariableDeclaration') {
|
|
88
|
+
for (const declaration of node.declarations) {
|
|
89
|
+
if (declaration.id.type !== 'Identifier' || locals.has(declaration.id.name) || factories.has(declaration.id.name) || !pure(declaration.init)) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
locals.add(declaration.id.name);
|
|
93
|
+
}
|
|
94
|
+
} else if (node.type === 'ExportNamedDeclaration' && !node.source && !node.declaration) {
|
|
95
|
+
for (const specifier of node.specifiers) {
|
|
96
|
+
if (specifier.type !== 'ExportSpecifier' || !locals.has(specifier.local.name) || specifier.exported.type !== 'Identifier') {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
names.push(specifier.exported.name);
|
|
100
|
+
}
|
|
101
|
+
} else {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (!factories.size || !names.length || new Set(names).size !== names.length) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
return { ast, names };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function combine({ source, ast }, index) {
|
|
112
|
+
const prefix = `__eightshiftPure${index}_`;
|
|
113
|
+
const edits = [];
|
|
114
|
+
const names = [];
|
|
115
|
+
const replace = (node, text) => edits.push({ start: node.range[0], end: node.range[1], text });
|
|
116
|
+
const visit = (node) => {
|
|
117
|
+
if (!node || typeof node !== 'object') {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (node.type === 'ExportNamedDeclaration') {
|
|
121
|
+
for (const specifier of node.specifiers) {
|
|
122
|
+
names.push(`${prefix}${specifier.local.name} as ${specifier.exported.name}`);
|
|
123
|
+
}
|
|
124
|
+
replace(node, '');
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (node.type === 'ImportSpecifier') {
|
|
128
|
+
replace(node, `${node.imported.name} as ${prefix}${node.local.name}`);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (node.type === 'VariableDeclarator') {
|
|
132
|
+
replace(node.id, `${prefix}${node.id.name}`);
|
|
133
|
+
visit(node.init);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (node.type === 'CallExpression') {
|
|
137
|
+
replace(node.callee, `${prefix}${node.callee.name}`);
|
|
138
|
+
node.arguments.forEach(visit);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
for (const [key, value] of Object.entries(node)) {
|
|
142
|
+
if (['parent', 'tokens', 'comments', 'loc', 'range'].includes(key)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (Array.isArray(value)) {
|
|
146
|
+
value.forEach(visit);
|
|
147
|
+
} else {
|
|
148
|
+
visit(value);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
visit(ast);
|
|
153
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
154
|
+
source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);
|
|
155
|
+
}
|
|
156
|
+
return `${source}\nexport { ${names.join(', ')} };\n`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function analyzeGraph({ result, metadata, directory, entries }) {
|
|
160
|
+
const outputs = new Map(Object.entries(metadata.outputs).map(([path, info]) => [resolve(directory, path), info]));
|
|
161
|
+
const artifacts = new Map(result.outputs.map((output) => [output.path, output]));
|
|
162
|
+
const roots = [...outputs].filter(([, info]) => info.entryPoint && entries.has(resolve(info.entryPoint))).map(([path]) => path);
|
|
163
|
+
if (roots.length !== entries.size) {
|
|
164
|
+
throw new Error('Ambiguous initial editor roots');
|
|
165
|
+
}
|
|
166
|
+
const graph = new Map();
|
|
167
|
+
const scanner = new Bun.Transpiler();
|
|
168
|
+
for (const [path] of outputs) {
|
|
169
|
+
if (!path.endsWith('.js')) {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const artifact = artifacts.get(path);
|
|
173
|
+
if (!artifact) {
|
|
174
|
+
throw new Error('Missing native editor artifact');
|
|
175
|
+
}
|
|
176
|
+
const edges = [];
|
|
177
|
+
for (const imported of scanner.scan(await artifact.text()).imports) {
|
|
178
|
+
if (!imported.path.startsWith('.')) {
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const target = resolve(dirname(path), imported.path);
|
|
182
|
+
if (!outputs.has(target) || !['import-statement', 'dynamic-import'].includes(imported.kind)) {
|
|
183
|
+
throw new Error('Unknown native editor graph edge');
|
|
184
|
+
}
|
|
185
|
+
edges.push({ path: target, lazy: Number(imported.kind === 'dynamic-import') });
|
|
186
|
+
}
|
|
187
|
+
graph.set(path, edges);
|
|
188
|
+
}
|
|
189
|
+
const depths = new Map();
|
|
190
|
+
const pending = roots.map((path) => ({ path, depth: 0 }));
|
|
191
|
+
for (let index = 0; index < pending.length; index++) {
|
|
192
|
+
const { path, depth } = pending[index];
|
|
193
|
+
if ((depths.get(path) ?? Infinity) <= depth) {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
depths.set(path, depth);
|
|
197
|
+
for (const edge of graph.get(path) ?? []) {
|
|
198
|
+
pending.push({ path: edge.path, depth: depth + edge.lazy });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const sourceDepths = new Map();
|
|
202
|
+
for (const [path, info] of outputs) {
|
|
203
|
+
for (const [source, input] of Object.entries(info.inputs ?? {})) {
|
|
204
|
+
if (input.bytesInOutput > 0 && depths.has(path)) {
|
|
205
|
+
const key = source.includes(':') ? source : resolve(source);
|
|
206
|
+
sourceDepths.set(key, Math.min(sourceDepths.get(key) ?? Infinity, depths.get(path)));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { outputs, depths, sourceDepths };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Analyze native output, but rebuild original sources rather than editing emitted chunks. */
|
|
214
|
+
export async function createPureJsxGroups({ result, metadata, directory, entries, maxBytes }) {
|
|
215
|
+
const { outputs, depths, sourceDepths } = await analyzeGraph({ result, metadata, directory, entries });
|
|
216
|
+
const inputs = new Map(
|
|
217
|
+
Object.entries(metadata.inputs)
|
|
218
|
+
.filter(([path]) => !path.includes(':'))
|
|
219
|
+
.map(([path, info]) => [resolve(path), info]),
|
|
220
|
+
);
|
|
221
|
+
const occurrences = new Map();
|
|
222
|
+
for (const info of outputs.values()) {
|
|
223
|
+
for (const [path, input] of Object.entries(info.inputs ?? {})) {
|
|
224
|
+
if (input.bytesInOutput > 0) {
|
|
225
|
+
const absolute = resolve(path);
|
|
226
|
+
occurrences.set(absolute, (occurrences.get(absolute) ?? 0) + 1);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const candidates = [];
|
|
231
|
+
for (const [output, info] of outputs) {
|
|
232
|
+
if (info.entryPoint || !depths.has(output) || !Number.isFinite(info.bytes) || info.bytes > maxBytes) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
const sources = Object.entries(info.inputs ?? {})
|
|
236
|
+
.filter(([, input]) => input.bytesInOutput > 0)
|
|
237
|
+
.map(([path]) => resolve(path));
|
|
238
|
+
if (sources.length !== 1) {
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const [path] = sources;
|
|
242
|
+
const input = inputs.get(path);
|
|
243
|
+
if (!inDependencies(path) || !path.endsWith('.js') || occurrences.get(path) !== 1 || !input || input.bytes > maxBytes) {
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
const imports = input.imports;
|
|
247
|
+
if (!imports.length || imports.some((item) => item.original !== 'react/jsx-runtime' || item.kind !== 'import-statement' || item.external) || new Set(imports.map((item) => item.path)).size !== 1) {
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
const source = await readFile(path, 'utf8');
|
|
251
|
+
const bytes = Buffer.byteLength(source);
|
|
252
|
+
const proof = bytes <= maxBytes && bytes === input.bytes && inspect(source);
|
|
253
|
+
if (proof) {
|
|
254
|
+
candidates.push({ path, source, bytes, ...proof, runtime: imports[0].path, depth: depths.get(output) });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const buckets = new Map();
|
|
258
|
+
for (const candidate of candidates.sort(comparePaths)) {
|
|
259
|
+
const key = JSON.stringify([dirname(candidate.path), candidate.runtime, candidate.depth]);
|
|
260
|
+
if (!buckets.has(key)) {
|
|
261
|
+
buckets.set(key, []);
|
|
262
|
+
}
|
|
263
|
+
buckets.get(key).push(candidate);
|
|
264
|
+
}
|
|
265
|
+
const groups = [];
|
|
266
|
+
for (const bucket of buckets.values()) {
|
|
267
|
+
let members = [];
|
|
268
|
+
let bytes = 0;
|
|
269
|
+
let names = new Set();
|
|
270
|
+
const flush = () => {
|
|
271
|
+
if (members.length > 1) {
|
|
272
|
+
const id = createHash('sha256')
|
|
273
|
+
.update(members.map((member) => `${member.path}\0${member.source}`).join('\0'))
|
|
274
|
+
.digest('hex')
|
|
275
|
+
.slice(0, 20);
|
|
276
|
+
groups.push({ members, bytes, path: resolve(dirname(members[0].path), `__eightshift-pure-${id}.js`) });
|
|
277
|
+
}
|
|
278
|
+
members = [];
|
|
279
|
+
bytes = 0;
|
|
280
|
+
names = new Set();
|
|
281
|
+
};
|
|
282
|
+
for (const member of bucket) {
|
|
283
|
+
if (bytes + member.bytes > maxBytes || member.names.some((name) => names.has(name))) {
|
|
284
|
+
flush();
|
|
285
|
+
}
|
|
286
|
+
members.push(member);
|
|
287
|
+
bytes += member.bytes;
|
|
288
|
+
member.names.forEach((name) => names.add(name));
|
|
289
|
+
}
|
|
290
|
+
flush();
|
|
291
|
+
}
|
|
292
|
+
const byPath = new Map(groups.flatMap((group) => group.members.map((member) => [member.path, { group, member }])));
|
|
293
|
+
const byGroup = new Map(groups.map((group) => [group.path, group]));
|
|
294
|
+
const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
295
|
+
// Broad no-op hooks can disable Bun's import optimization for unrelated modules.
|
|
296
|
+
const sourceFilter = new RegExp(`^(?:${[...byPath.keys()].map(escape).join('|')})$`);
|
|
297
|
+
const importFilter = new RegExp(`(?:^|/)(?:${[...new Set([...byPath.keys()].map((path) => basename(path)))].map(escape).join('|')})$`);
|
|
298
|
+
const consumerCache = new Map();
|
|
299
|
+
async function namedOnly(importer, specifier) {
|
|
300
|
+
// Audited discovery only transforms require.context files; those retain native facades.
|
|
301
|
+
if (!isAbsolute(importer) || !importer.endsWith('.js')) {
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
if (!consumerCache.has(importer)) {
|
|
305
|
+
const source = await readFile(importer, 'utf8');
|
|
306
|
+
consumerCache.set(importer, source.includes('require.context') ? undefined : parse(source));
|
|
307
|
+
}
|
|
308
|
+
const ast = consumerCache.get(importer);
|
|
309
|
+
const references = ast?.body.filter((node) => node.source?.value === specifier) ?? [];
|
|
310
|
+
return (
|
|
311
|
+
references.length > 0 &&
|
|
312
|
+
references.every(
|
|
313
|
+
(node) =>
|
|
314
|
+
!node.attributes?.length &&
|
|
315
|
+
((node.type === 'ImportDeclaration' && node.specifiers.length > 0 && node.specifiers.every((item) => item.type === 'ImportSpecifier')) || (node.type === 'ExportNamedDeclaration' && node.specifiers.length > 0 && node.specifiers.every((item) => item.type === 'ExportSpecifier'))),
|
|
316
|
+
)
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const plugin = {
|
|
320
|
+
name: 'eightshift-bounded-pure-jsx',
|
|
321
|
+
setup(builder) {
|
|
322
|
+
builder.onResolve({ filter: /^eightshift-pure:/ }, ({ path }) => {
|
|
323
|
+
const target = path.slice('eightshift-pure:'.length);
|
|
324
|
+
if (byGroup.has(target)) {
|
|
325
|
+
return { path: target, namespace: 'eightshift-pure' };
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
builder.onResolve({ filter: importFilter }, async ({ path, importer, kind }) => {
|
|
329
|
+
if (kind !== 'import-statement') {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const matches = inputs.get(importer)?.imports.filter((item) => item.original === path && item.kind === 'import-statement' && !item.external) ?? [];
|
|
333
|
+
if (matches.length !== 1) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const candidate = byPath.get(resolve(matches[0].path));
|
|
337
|
+
if (candidate && (await namedOnly(importer, path))) {
|
|
338
|
+
return { path: candidate.group.path, namespace: 'eightshift-pure' };
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
builder.onLoad({ filter: sourceFilter }, async ({ path }) => {
|
|
342
|
+
const candidate = byPath.get(path);
|
|
343
|
+
if (!candidate) {
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if ((await readFile(path, 'utf8')) !== candidate.member.source) {
|
|
347
|
+
throw new Error('Pure JSX source changed during compilation');
|
|
348
|
+
}
|
|
349
|
+
return { contents: `export { ${candidate.member.names.join(', ')} } from ${JSON.stringify(`eightshift-pure:${candidate.group.path}`)};`, loader: 'js', resolveDir: dirname(path) };
|
|
350
|
+
});
|
|
351
|
+
builder.onLoad({ filter: /.*/, namespace: 'eightshift-pure' }, async ({ path }) => {
|
|
352
|
+
const group = byGroup.get(path);
|
|
353
|
+
for (const member of group.members) {
|
|
354
|
+
if ((await readFile(member.path, 'utf8')) !== member.source) {
|
|
355
|
+
throw new Error('Pure JSX source changed during compilation');
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return { contents: group.members.map(combine).join('\n'), loader: 'js', resolveDir: dirname(path) };
|
|
359
|
+
});
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
return {
|
|
363
|
+
plugin,
|
|
364
|
+
groups,
|
|
365
|
+
async verify(nextMetadata, nextResult) {
|
|
366
|
+
const next = await analyzeGraph({ result: nextResult, metadata: nextMetadata, directory, entries });
|
|
367
|
+
for (const [source, depth] of next.sourceDepths) {
|
|
368
|
+
if (!source.startsWith('eightshift-pure:') && !byPath.has(source) && depth < (sourceDepths.get(source) ?? Infinity)) {
|
|
369
|
+
throw new Error(`Grouping would advance non-grouped source evaluation: ${source}`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
for (const group of groups) {
|
|
373
|
+
const input = nextMetadata.inputs?.[`eightshift-pure:${group.path}`];
|
|
374
|
+
if (!input || !Array.isArray(input.imports) || !input.imports.length || input.imports.some((item) => item.original !== 'react/jsx-runtime' || item.path !== group.members[0].runtime || item.kind !== 'import-statement' || item.external)) {
|
|
375
|
+
throw new Error('Pure JSX runtime resolution changed during compilation');
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
},
|
|
379
|
+
summary: { maxBytes, groups: groups.map((group) => ({ source: `eightshift-pure:${group.path}`, members: group.members.map((member) => member.path), bytes: group.bytes, depth: group.members[0].depth, runtime: group.members[0].runtime })) },
|
|
380
|
+
};
|
|
381
|
+
}
|
package/bun/editor.mjs
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { eightshiftDiscovery, editorLazyImports } from './eightshift-discovery.mjs';
|
|
5
|
+
import { buildNativeEditorChunks } from './editor-native.mjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Build classic registration with lazy ESM modules, or a unified ESM graph. Discovery, when
|
|
9
|
+
* supplied, is composed with lazy rewriting so both can process one file.
|
|
10
|
+
* Other onLoad plugins that consume the same file must compose the rewrite.
|
|
11
|
+
* Editor output must not require extracted CSS or other emitted assets.
|
|
12
|
+
* sharing: 'native' compiles lazy targets as one ESM graph, separate from
|
|
13
|
+
* synchronous registration. 'unified' includes registration in the ESM graph
|
|
14
|
+
* and requires module-aware PHP readiness integration. The default is independent.
|
|
15
|
+
*/
|
|
16
|
+
export async function buildEditor({ root, directory, entry, buildOptions = {}, plugins = [], chunkDir = 'editor-chunks', filename = 'editor.js', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', discovery, lazy = {}, sharedPackages, sharing = 'independent', pureJsxGroups = false }) {
|
|
17
|
+
if (!['independent', 'native', 'unified'].includes(sharing)) {
|
|
18
|
+
throw new TypeError('editor.sharing must be "independent", "native" or "unified"');
|
|
19
|
+
}
|
|
20
|
+
if (pureJsxGroups !== false && (!pureJsxGroups || typeof pureJsxGroups !== 'object' || Array.isArray(pureJsxGroups) || Object.keys(pureJsxGroups).some((key) => key !== 'maxBytes') || !Number.isSafeInteger(pureJsxGroups.maxBytes) || pureJsxGroups.maxBytes < 1 || pureJsxGroups.maxBytes > 65536)) {
|
|
21
|
+
throw new TypeError('editor.pureJsxGroups must be false or { maxBytes: integer between 1 and 65536 }');
|
|
22
|
+
}
|
|
23
|
+
if (pureJsxGroups && sharing !== 'unified') {
|
|
24
|
+
throw new TypeError('editor.pureJsxGroups requires unified sharing');
|
|
25
|
+
}
|
|
26
|
+
if (sharedPackages !== undefined) {
|
|
27
|
+
throw new TypeError('editor.sharedPackages was removed; use native or unified sharing after checking their initialization and readiness requirements');
|
|
28
|
+
}
|
|
29
|
+
const inside = (path) => {
|
|
30
|
+
if (typeof path !== 'string' || !path || isAbsolute(path)) {
|
|
31
|
+
throw new TypeError('Editor output paths must be relative');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const output = resolve(directory, path);
|
|
35
|
+
const location = relative(directory, output);
|
|
36
|
+
|
|
37
|
+
if (!location || location === '..' || location.startsWith(`..${sep}`) || isAbsolute(location)) {
|
|
38
|
+
throw new Error(`Editor output escapes entry directory: ${path}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return output;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
if (filename.includes('/') || filename.includes('\\')) {
|
|
45
|
+
throw new TypeError('Editor filename must be a basename');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const entryOutput = inside(filename);
|
|
49
|
+
const chunkOutput = inside(chunkDir);
|
|
50
|
+
|
|
51
|
+
if (relative(chunkOutput, entryOutput) === '' || (!relative(chunkOutput, entryOutput).startsWith(`..${sep}`) && relative(chunkOutput, entryOutput) !== '..')) {
|
|
52
|
+
throw new Error('Editor entry cannot be inside its chunk directory');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (buildOptions.sourcemap !== undefined && !['none', 'external'].includes(buildOptions.sourcemap)) {
|
|
56
|
+
throw new TypeError('Editor sourcemap must be "none" or "external"');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (sharing === 'unified') {
|
|
60
|
+
if (!/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
|
|
61
|
+
throw new TypeError('Invalid editor script URL identifier');
|
|
62
|
+
}
|
|
63
|
+
if (Object.keys(lazy).length) {
|
|
64
|
+
throw new TypeError('Unified editor sharing uses native imports and cannot apply lazy import rewriting');
|
|
65
|
+
}
|
|
66
|
+
const target = resolve(root, entry);
|
|
67
|
+
const nativeDiscovery = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery') }) : undefined;
|
|
68
|
+
const {
|
|
69
|
+
names,
|
|
70
|
+
outputs,
|
|
71
|
+
pureJsxGroups: grouping,
|
|
72
|
+
} = await buildNativeEditorChunks({
|
|
73
|
+
pureJsxGroups,
|
|
74
|
+
chunks: new Map([[target, 'entry']]),
|
|
75
|
+
directory: chunkOutput,
|
|
76
|
+
entryOutput,
|
|
77
|
+
scriptUrlIdentifier,
|
|
78
|
+
buildOptions: { ...buildOptions, loader: { ...buildOptions.loader, '.svg': 'text' }, sourcemap: buildOptions.sourcemap ?? 'none' },
|
|
79
|
+
plugins: [...(nativeDiscovery ? [nativeDiscovery] : []), ...plugins],
|
|
80
|
+
});
|
|
81
|
+
const paths = [];
|
|
82
|
+
await mkdir(chunkOutput, { recursive: true });
|
|
83
|
+
for (const output of outputs) {
|
|
84
|
+
let contents = Buffer.from(await output.arrayBuffer());
|
|
85
|
+
if (output.sourcemap) {
|
|
86
|
+
contents = Buffer.from(`${await output.text()}\n//# sourceMappingURL=${basename(output.sourcemap.path)}\n`);
|
|
87
|
+
}
|
|
88
|
+
await writeFile(output.path, contents);
|
|
89
|
+
paths.push(output.path);
|
|
90
|
+
}
|
|
91
|
+
let imported = relative(dirname(entryOutput), resolve(chunkOutput, names.get(target)))
|
|
92
|
+
.split(sep)
|
|
93
|
+
.join('/');
|
|
94
|
+
if (!imported.startsWith('.')) {
|
|
95
|
+
imported = `./${imported}`;
|
|
96
|
+
}
|
|
97
|
+
const source = `import ${JSON.stringify(imported)};\nconst readiness = globalThis.eightshiftEditorModules;\nif (readiness?.version !== 1 || typeof readiness.complete !== 'function') throw new Error('Unified editor requires the Eightshift module readiness integration');\nreadiness.complete(import.meta.url);\n`;
|
|
98
|
+
await writeFile(entryOutput, source);
|
|
99
|
+
paths.push(entryOutput);
|
|
100
|
+
return { entry: entryOutput, paths, format: 'module', readiness: 'eightshift-editor-v1', ...(grouping ? { pureJsxGroups: grouping } : {}) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const chunks = new Map();
|
|
104
|
+
const lazyImports = editorLazyImports({ ...lazy, root, chunks, chunkDir, scriptUrlIdentifier, versioned: sharing !== 'native' });
|
|
105
|
+
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;
|
|
106
|
+
const sourcemap = buildOptions.sourcemap === 'external';
|
|
107
|
+
const options = {
|
|
108
|
+
target: 'browser',
|
|
109
|
+
...buildOptions,
|
|
110
|
+
...(sharing === 'native' ? { minChunkSize: undefined } : {}),
|
|
111
|
+
loader: { ...buildOptions.loader, '.svg': 'text' },
|
|
112
|
+
sourcemap: sourcemap ? 'external' : 'none',
|
|
113
|
+
entrypoints: [resolve(root, entry)],
|
|
114
|
+
format: 'iife',
|
|
115
|
+
splitting: false,
|
|
116
|
+
write: false,
|
|
117
|
+
plugins: [...(discoveryPlugin ? [discoveryPlugin] : []), ...plugins, lazyImports.plugin],
|
|
118
|
+
};
|
|
119
|
+
const paths = [];
|
|
120
|
+
const compile = async (target, format) => {
|
|
121
|
+
const result = await Bun.build({ ...options, entrypoints: [target], format });
|
|
122
|
+
|
|
123
|
+
if (!result.success) {
|
|
124
|
+
throw new AggregateError(result.logs, `Editor build failed: ${target}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const entries = result.outputs.filter((output) => output.kind === 'entry-point');
|
|
128
|
+
const maps = result.outputs.filter((output) => output.kind === 'sourcemap');
|
|
129
|
+
if (entries.length !== 1 || maps.length !== (sourcemap ? 1 : 0) || result.outputs.length !== entries.length + maps.length) {
|
|
130
|
+
throw new Error(`Unexpected editor assets: ${target}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const map = sourcemap ? JSON.parse(await maps[0].text()) : undefined;
|
|
134
|
+
if (map) {
|
|
135
|
+
map.mappings = `;${map.mappings}`;
|
|
136
|
+
}
|
|
137
|
+
return { source: await entries[0].text(), map };
|
|
138
|
+
};
|
|
139
|
+
const write = async (path, source) => {
|
|
140
|
+
await mkdir(dirname(path), { recursive: true });
|
|
141
|
+
await writeFile(path, source);
|
|
142
|
+
paths.push(path);
|
|
143
|
+
};
|
|
144
|
+
let entryBuild = await compile(resolve(root, entry), 'iife');
|
|
145
|
+
const entryMap = `${basename(entryOutput)}.map`;
|
|
146
|
+
if (sharing === 'native') {
|
|
147
|
+
if (chunks.size) {
|
|
148
|
+
const nativeDiscovery = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery') }) : undefined;
|
|
149
|
+
const { names, outputs } = await buildNativeEditorChunks({
|
|
150
|
+
chunks,
|
|
151
|
+
directory: chunkOutput,
|
|
152
|
+
entryOutput,
|
|
153
|
+
scriptUrlIdentifier,
|
|
154
|
+
buildOptions: { ...buildOptions, loader: options.loader, sourcemap: options.sourcemap },
|
|
155
|
+
plugins: [...(nativeDiscovery ? [nativeDiscovery] : []), ...plugins],
|
|
156
|
+
});
|
|
157
|
+
for (const [target, name] of names) {
|
|
158
|
+
chunks.set(target, name);
|
|
159
|
+
}
|
|
160
|
+
// Compile against final URLs rather than rewriting code after source-map generation.
|
|
161
|
+
entryBuild = await compile(resolve(root, entry), 'iife');
|
|
162
|
+
if (chunks.size !== names.size) {
|
|
163
|
+
throw new Error('Editor lazy entries changed during native compilation');
|
|
164
|
+
}
|
|
165
|
+
for (const output of outputs) {
|
|
166
|
+
if (output.sourcemap) {
|
|
167
|
+
await write(output.path, `${await output.text()}\n//# sourceMappingURL=${basename(output.sourcemap.path)}\n`);
|
|
168
|
+
} else {
|
|
169
|
+
await write(output.path, Buffer.from(await output.arrayBuffer()));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${entryBuild.source}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
|
|
174
|
+
if (entryBuild.map) {
|
|
175
|
+
await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
|
|
176
|
+
}
|
|
177
|
+
return { entry: entryOutput, paths };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const lazyPaths = [];
|
|
181
|
+
|
|
182
|
+
for (const [target, name] of chunks) {
|
|
183
|
+
const output = inside(`${chunkDir}/${name}`);
|
|
184
|
+
let entryPath = relative(dirname(output), entryOutput).split(sep).join('/');
|
|
185
|
+
if (!entryPath.startsWith('.')) {
|
|
186
|
+
entryPath = `./${entryPath}`;
|
|
187
|
+
}
|
|
188
|
+
const chunk = await compile(target, 'esm');
|
|
189
|
+
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` : ''}`);
|
|
190
|
+
lazyPaths.push(output);
|
|
191
|
+
if (chunk.map) {
|
|
192
|
+
await write(`${output}.map`, JSON.stringify(chunk.map));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const digest = createHash('sha256').update(entryBuild.source);
|
|
197
|
+
const contents = new Map();
|
|
198
|
+
for (const path of lazyPaths.sort()) {
|
|
199
|
+
const source = await readFile(path, 'utf8');
|
|
200
|
+
contents.set(path, source);
|
|
201
|
+
digest.update(path.slice(directory.length)).update('\0').update(source).update('\0');
|
|
202
|
+
}
|
|
203
|
+
const version = digest.digest('hex').slice(0, 20);
|
|
204
|
+
const withVersion = (source) => source.replaceAll('?v=00000000000000000000', `?v=${version}`);
|
|
205
|
+
for (const [path, source] of contents) {
|
|
206
|
+
await writeFile(path, withVersion(source));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${withVersion(entryBuild.source)}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
|
|
210
|
+
if (entryBuild.map) {
|
|
211
|
+
await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return { entry: entryOutput, paths };
|
|
215
|
+
}
|
|
@@ -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
|
+
}
|