@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/bun/cli.mjs ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env bun
2
+ import { delimiter, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ const projectModules = resolve('node_modules');
6
+
7
+ if (!(process.env.NODE_PATH ?? '').split(delimiter).includes(projectModules)) {
8
+ const child = Bun.spawn([process.execPath, ...process.argv.slice(1)], {
9
+ cwd: process.cwd(),
10
+ env: { ...process.env, NODE_PATH: [projectModules, process.env.NODE_PATH].filter(Boolean).join(delimiter) },
11
+ stdin: 'inherit',
12
+ stdout: 'inherit',
13
+ stderr: 'inherit',
14
+ });
15
+
16
+ const forwardInt = () => child.kill('SIGINT');
17
+ const forwardTerm = () => child.kill('SIGTERM');
18
+ process.on('SIGINT', forwardInt);
19
+ process.on('SIGTERM', forwardTerm);
20
+ const exitCode = await child.exited;
21
+ process.removeListener('SIGINT', forwardInt);
22
+ process.removeListener('SIGTERM', forwardTerm);
23
+ process.exit(exitCode);
24
+ }
25
+
26
+ const args = process.argv.slice(2);
27
+ const command = args.shift();
28
+
29
+ if (!['build', 'watch'].includes(command)) {
30
+ throw new Error('Usage: eightshift-build <build|watch> [--config path] [--sourcemaps]');
31
+ }
32
+
33
+ let config = 'eightshift.build.mjs';
34
+ const options = { sourcemaps: false };
35
+
36
+ while (args.length) {
37
+ const arg = args.shift();
38
+
39
+ if (arg === '--config') {
40
+ config = args.shift();
41
+
42
+ if (!config || config.startsWith('--')) {
43
+ throw new Error('--config requires a path');
44
+ }
45
+ } else if (arg === '--sourcemaps') {
46
+ options.sourcemaps = true;
47
+ } else {
48
+ throw new Error(`Unknown option: ${arg}`);
49
+ }
50
+ }
51
+
52
+ const { default: definition } = await import(pathToFileURL(resolve(config)).href);
53
+
54
+ if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
55
+ throw new TypeError('Config default export must be a defineBuild result');
56
+ }
57
+
58
+ if (command === 'build') {
59
+ await definition.build(options);
60
+ } else {
61
+ const watcher = definition.watch(options);
62
+ let stopping;
63
+ const stop = () => {
64
+ if (!stopping) {
65
+ stopping = Promise.resolve()
66
+ .then(() => watcher.stop())
67
+ .finally(() => {
68
+ process.removeListener('SIGINT', stop);
69
+ process.removeListener('SIGTERM', stop);
70
+ });
71
+ }
72
+ return stopping;
73
+ };
74
+
75
+ process.on('SIGINT', stop);
76
+ process.on('SIGTERM', stop);
77
+ }
package/bun/css.mjs ADDED
@@ -0,0 +1,145 @@
1
+ import { compile, Polyfills } from '@tailwindcss/node';
2
+ import { Scanner } from '@tailwindcss/oxide';
3
+ import { createHash } from 'node:crypto';
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { dirname, extname, relative, resolve } from 'node:path';
7
+ import browserslist from 'browserslist';
8
+ import { browserslistToTargets, transform } from 'lightningcss';
9
+ import postcss from 'postcss';
10
+ import valueParser from 'postcss-value-parser';
11
+
12
+ const require = createRequire(import.meta.url);
13
+
14
+ /**
15
+ * Compile ordered stylesheets to one CSS file.
16
+ * Paths are relative to projectDir unless absolute. Each files entry is a path
17
+ * or { file, scan, sources, scanFiles, removeSources }; scan enables Tailwind
18
+ * candidate scanning, sources extends its detected sources, scanFiles adds
19
+ * explicit candidate files, and removeSources removes exact @source rules.
20
+ * Assets are copied beside outputFile with content-hashed names.
21
+ */
22
+ export async function processCss({ projectDir, outputFile, files, production = false, browsers = '>= 0.25%' }) {
23
+ if (!projectDir || !outputFile || !Array.isArray(files) || files.length === 0) {
24
+ throw new Error('processCss requires projectDir, outputFile and a non-empty files array.');
25
+ }
26
+
27
+ const root = resolve(projectDir);
28
+ const output = resolve(root, outputFile);
29
+ const outdir = dirname(output);
30
+
31
+ await mkdir(outdir, { recursive: true });
32
+
33
+ const rewriteAssets = async (css, base) => {
34
+ const tree = postcss.parse(css);
35
+ const pending = [];
36
+
37
+ tree.walkDecls((declaration) => {
38
+ const value = valueParser(declaration.value);
39
+ const assets = [];
40
+
41
+ value.walk((node) => {
42
+ if (node.type !== 'function' || node.value.toLowerCase() !== 'url') {
43
+ return;
44
+ }
45
+
46
+ const url = valueParser
47
+ .stringify(node.nodes)
48
+ .trim()
49
+ .replace(/^(['"])(.*)\1$/, '$2');
50
+
51
+ if (!url || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url)) {
52
+ return;
53
+ }
54
+
55
+ assets.push(
56
+ (async () => {
57
+ const suffixIndex = url.search(/[?#]/);
58
+ const pathname = suffixIndex < 0 ? url : url.slice(0, suffixIndex);
59
+ const suffix = suffixIndex < 0 ? '' : url.slice(suffixIndex);
60
+ let asset = resolve(base, pathname);
61
+ let content;
62
+
63
+ try {
64
+ content = await readFile(asset);
65
+ } catch (error) {
66
+ if (error.code !== 'ENOENT' || pathname.startsWith('.')) {
67
+ throw error;
68
+ }
69
+
70
+ asset = require.resolve(pathname, { paths: [base] });
71
+ content = await readFile(asset);
72
+ }
73
+
74
+ const name = `${createHash('sha256').update(content).digest('hex').slice(0, 20)}${extname(asset)}`;
75
+
76
+ await writeFile(resolve(outdir, name), content);
77
+ node.nodes = [{ type: 'string', quote: '"', value: `./${name}${suffix}` }];
78
+ })(),
79
+ );
80
+ });
81
+ pending.push(
82
+ Promise.all(assets).then(() => {
83
+ declaration.value = value.toString();
84
+ }),
85
+ );
86
+ });
87
+ await Promise.all(pending);
88
+
89
+ return tree.toString();
90
+ };
91
+
92
+ const parts = [];
93
+ const dependencies = new Set();
94
+
95
+ for (const entry of files) {
96
+ const options = typeof entry === 'string' ? { file: entry } : entry;
97
+
98
+ if (!options?.file) {
99
+ throw new Error('Each CSS entry requires a file path.');
100
+ }
101
+
102
+ const file = resolve(root, options.file);
103
+ let input = await readFile(file, 'utf8');
104
+
105
+ dependencies.add(file);
106
+
107
+ for (const source of options.removeSources ?? []) {
108
+ if (!input.includes(source)) {
109
+ throw new Error(`Missing source rule in ${file}: ${source}`);
110
+ }
111
+
112
+ input = input.replace(source, '');
113
+ }
114
+
115
+ const compiler = await compile(input, {
116
+ base: dirname(file),
117
+ from: file,
118
+ shouldRewriteUrls: true,
119
+ polyfills: Polyfills.All,
120
+ onDependency: (dependency) => dependencies.add(dependency),
121
+ });
122
+ let candidates = [];
123
+
124
+ if (options.scan) {
125
+ const sources = (compiler.root === 'none' ? [] : compiler.root === null ? [{ base: root, pattern: '**/*', negated: false }] : [{ ...compiler.root, negated: false }]).concat(
126
+ compiler.sources,
127
+ (options.sources ?? []).map((source) => ({ ...source, base: resolve(root, source.base ?? '.') })),
128
+ );
129
+ const scanner = new Scanner({ sources });
130
+ const explicit = (options.scanFiles ?? []).map((item) => (typeof item === 'string' ? { file: resolve(root, item), extension: extname(item).slice(1) } : { ...item, file: resolve(root, item.file) }));
131
+
132
+ explicit.forEach(({ file: candidateFile }) => dependencies.add(candidateFile));
133
+ candidates = [...new Set([...scanner.scan(), ...(explicit.length ? scanner.scanFiles(explicit) : [])])];
134
+ }
135
+
136
+ parts.push(`/* ${relative(root, file)} */\n${await rewriteAssets(compiler.build(candidates), dirname(file))}`);
137
+ }
138
+
139
+ const css = parts.join('\n');
140
+ const result = production ? transform({ filename: output, code: Buffer.from(css), minify: true, targets: browserslistToTargets(browserslist(browsers)) }).code : css;
141
+
142
+ await writeFile(output, result);
143
+
144
+ return { outputFile: output, dependencies: [...dependencies] };
145
+ }
@@ -0,0 +1,121 @@
1
+ import { mkdir, readdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, relative, resolve, sep } from 'node:path';
3
+
4
+ /**
5
+ * Generate Bun-compatible context modules from caller-supplied definitions.
6
+ *
7
+ * `root` is the base for definition directories; `output` is the generated
8
+ * module path. Each definition has `name`, `directory`, `pattern` (RegExp),
9
+ * and optional `mode` (`sync`, the default, or `lazy`). Lazy contexts return
10
+ * promises and do not import their modules until called. CSS is supported only
11
+ * in synchronous contexts, where it is imported for side effects and resolves
12
+ * to an empty object. JSON contexts return parsed values; other synchronous
13
+ * imports return module namespaces. Regenerate after changing source files.
14
+ * Symlinks are skipped. Missing directories are treated as empty contexts.
15
+ */
16
+ export async function generateDiscovery({ root, output, definitions }) {
17
+ if (typeof root !== 'string' || typeof output !== 'string' || !Array.isArray(definitions)) {
18
+ throw new TypeError('Expected root, output, and definitions');
19
+ }
20
+
21
+ const baseRoot = resolve(root);
22
+ const outputFile = resolve(baseRoot, output);
23
+ const outputDirectory = dirname(outputFile);
24
+ const names = new Set();
25
+ const imports = [];
26
+ const contexts = [];
27
+ let counter = 0;
28
+
29
+ for (const definition of definitions) {
30
+ const { name, directory, pattern, mode = 'sync' } = definition;
31
+
32
+ if (typeof name !== 'string' || !/^[$A-Z_a-z][$\w]*$/.test(name) || !isValidExportName(name) || name === 'createContext' || /^module\d+$/.test(name) || names.has(name) || typeof directory !== 'string' || !(pattern instanceof RegExp) || !['sync', 'lazy'].includes(mode)) {
33
+ throw new TypeError('Invalid or duplicate discovery definition');
34
+ }
35
+
36
+ names.add(name);
37
+ const base = resolve(baseRoot, directory);
38
+ const entries = [];
39
+
40
+ for (const file of await filesIn(base)) {
41
+ const key = `./${file}`;
42
+
43
+ pattern.lastIndex = 0;
44
+
45
+ if (!pattern.test(key)) {
46
+ continue;
47
+ }
48
+
49
+ let specifier = relative(outputDirectory, resolve(base, file)).split(sep).join('/');
50
+
51
+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) {
52
+ specifier = `./${specifier}`;
53
+ }
54
+
55
+ const quoted = JSON.stringify(specifier);
56
+
57
+ if (mode === 'lazy') {
58
+ if (file.endsWith('.css')) {
59
+ throw new TypeError(`Lazy CSS context is not supported: ${name}`);
60
+ }
61
+
62
+ entries.push(`[${JSON.stringify(key)}, () => import(${quoted})]`);
63
+ } else if (file.endsWith('.css')) {
64
+ imports.push(`import ${quoted};`);
65
+ entries.push(`[${JSON.stringify(key)}, {}]`);
66
+ } else {
67
+ const variable = `module${counter++}`;
68
+
69
+ imports.push(file.endsWith('.json') ? `import ${variable} from ${quoted};` : `import * as ${variable} from ${quoted};`);
70
+ entries.push(`[${JSON.stringify(key)}, ${variable}]`);
71
+ }
72
+ }
73
+
74
+ contexts.push(`export const ${name} = createContext([${entries.join(',\n')}], ${mode === 'lazy'});`);
75
+ }
76
+
77
+ const source = `// Generated by Bun discovery; do not edit.\n${imports.join('\n')}\n\nfunction createContext(entries, lazy) {\n\tconst modules = new Map(entries);\n\tconst context = (key) => {\n\t\tif (!modules.has(key)) {\n\t\t\tconst error = new Error(\`Cannot find module '\${key}'\`);\n\t\t\terror.code = 'MODULE_NOT_FOUND';\n\t\t\tif (lazy) return Promise.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\treturn lazy ? modules.get(key)() : modules.get(key);\n\t};\n\tcontext.keys = () => [...modules.keys()];\n\treturn context;\n}\n\n${contexts.join('\n\n')}\n`;
78
+
79
+ await mkdir(outputDirectory, { recursive: true });
80
+ await writeFile(outputFile, source);
81
+
82
+ return { output: outputFile, contexts: definitions.length };
83
+ }
84
+
85
+ function isValidExportName(name) {
86
+ try {
87
+ new Function(`"use strict"; let ${name};`);
88
+
89
+ return true;
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ async function filesIn(directory, prefix = '') {
96
+ let entries;
97
+
98
+ try {
99
+ entries = await readdir(directory, { withFileTypes: true });
100
+ } catch (error) {
101
+ if (error.code === 'ENOENT') {
102
+ return [];
103
+ }
104
+
105
+ throw error;
106
+ }
107
+
108
+ const files = [];
109
+
110
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
111
+ const name = prefix ? `${prefix}/${entry.name}` : entry.name;
112
+
113
+ if (entry.isDirectory()) {
114
+ files.push(...(await filesIn(resolve(directory, entry.name), name)));
115
+ } else if (entry.isFile()) {
116
+ files.push(name);
117
+ }
118
+ }
119
+
120
+ return files;
121
+ }
@@ -0,0 +1,191 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readdir, rmdir, unlink } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { supportsPureJsxGrouping } from './plugin-capabilities.mjs';
5
+
6
+ const removePassDirectory = async (directory) => {
7
+ for (const item of await readdir(directory, { withFileTypes: true })) {
8
+ const path = resolve(directory, item.name);
9
+ if (item.isDirectory()) {
10
+ await removePassDirectory(path);
11
+ } else {
12
+ await unlink(path);
13
+ }
14
+ }
15
+ await rmdir(directory);
16
+ };
17
+
18
+ /** Build lazy targets together without replacing their native import namespaces. */
19
+ export async function buildNativeEditorChunks(options) {
20
+ const directory = resolve(options.directory);
21
+ await mkdir(dirname(directory), { recursive: true });
22
+ // Some Bun versions write outdir despite write:false. Never expose discarded passes.
23
+ const privateDirectory = resolve(dirname(directory), `.eightshift-native-${randomUUID()}`);
24
+ await mkdir(privateDirectory);
25
+ try {
26
+ const result = await compileNativeEditorChunks({ ...options, directory: privateDirectory, scriptDirectory: directory });
27
+ const mapPath = (path) => {
28
+ const location = relative(privateDirectory, path);
29
+ if (!location || isAbsolute(location) || location === '..' || location.startsWith(`..${sep}`)) {
30
+ throw new Error(`Native editor output escapes its private directory: ${path}`);
31
+ }
32
+ return resolve(directory, location);
33
+ };
34
+ const outputs = [];
35
+ const byPath = new Map();
36
+ for (const output of result.outputs) {
37
+ // Materialize before cleanup: a BuildArtifact may be backed by its emitted file.
38
+ const bytes = await output.arrayBuffer();
39
+ const artifact = new Blob([bytes], { type: output.type });
40
+ Object.assign(artifact, { path: mapPath(output.path), kind: output.kind, loader: output.loader, hash: output.hash });
41
+ outputs.push(artifact);
42
+ byPath.set(output.path, artifact);
43
+ }
44
+ for (const [index, output] of result.outputs.entries()) {
45
+ if (output.sourcemap) {
46
+ const map = byPath.get(output.sourcemap.path);
47
+ if (!map) {
48
+ throw new Error('Missing native editor source map artifact');
49
+ }
50
+ outputs[index].sourcemap = map;
51
+ }
52
+ }
53
+ const metafile = {
54
+ ...result.metafile,
55
+ outputs: Object.fromEntries(Object.entries(result.metafile.outputs).map(([path, info]) => [mapPath(resolve(privateDirectory, path)), { ...info, imports: info.imports?.map((item) => ({ ...item, path: isAbsolute(item.path) && !item.external ? mapPath(item.path) : item.path })) }])),
56
+ };
57
+ return { ...result, outputs, metafile };
58
+ } finally {
59
+ await removePassDirectory(privateDirectory);
60
+ }
61
+ }
62
+
63
+ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, entryOutput, scriptUrlIdentifier, buildOptions, plugins, pureJsxGroups = false }) {
64
+ let entryPath = relative(scriptDirectory, entryOutput).split(sep).join('/');
65
+ if (!entryPath.startsWith('.')) {
66
+ entryPath = `./${entryPath}`;
67
+ }
68
+
69
+ const options = {
70
+ target: 'browser',
71
+ ...buildOptions,
72
+ entrypoints: [...chunks.keys()],
73
+ outdir: directory,
74
+ format: 'esm',
75
+ splitting: true,
76
+ write: false,
77
+ metafile: true,
78
+ publicPath: '',
79
+ naming: { entry: 'editor-lazy-[name]-[hash].[ext]', chunk: 'editor-shared-[hash].[ext]', asset: 'editor-asset-[hash].[ext]' },
80
+ banner: `const ${scriptUrlIdentifier} = new URL(${JSON.stringify(entryPath)}, import.meta.url).href;\n${buildOptions.banner ?? ''}`,
81
+ plugins,
82
+ };
83
+ let result = await Bun.build(options);
84
+
85
+ if (!result.success) {
86
+ throw new AggregateError(result.logs, 'Native editor sharing build failed');
87
+ }
88
+
89
+ const readMetadata = (build) => {
90
+ let metadata;
91
+ try {
92
+ metadata = typeof build.metafile === 'string' ? JSON.parse(build.metafile) : build.metafile;
93
+ if (!metadata?.outputs || typeof metadata.outputs !== 'object') {
94
+ throw new Error('Missing output metadata');
95
+ }
96
+ } catch (cause) {
97
+ throw new Error('Cannot map native editor entries: Bun returned unreadable build metadata', { cause });
98
+ }
99
+ if (!metadata.inputs || typeof metadata.inputs !== 'object') {
100
+ throw new Error('Cannot verify native editor dynamic imports: missing input metadata');
101
+ }
102
+ for (const [source, info] of Object.entries(metadata.inputs)) {
103
+ if (!Array.isArray(info?.imports)) {
104
+ throw new Error(`Cannot verify native editor dynamic imports in ${source}`);
105
+ }
106
+ // Inlined dynamic imports can return plain objects or broken self-import helpers.
107
+ for (const imported of info.imports) {
108
+ if (imported.kind === 'dynamic-import' && !imported.external) {
109
+ throw new Error(`Native editor sharing cannot preserve an inlined dynamic import in ${source}: ${imported.original ?? imported.path}`);
110
+ }
111
+ }
112
+ }
113
+ return metadata;
114
+ };
115
+ let metadata = readMetadata(result);
116
+ let grouping;
117
+ if (pureJsxGroups) {
118
+ let reason;
119
+ if (options.sourcemap && options.sourcemap !== 'none') {
120
+ reason = 'source maps require original ungrouped sources';
121
+ } else if (plugins.some((plugin) => !supportsPureJsxGrouping(plugin))) {
122
+ reason = 'custom plugins/transforms are not supported';
123
+ } else if (buildOptions.alias && Object.keys(buildOptions.alias).length) {
124
+ reason = 'custom resolution aliases are not supported';
125
+ } else if (buildOptions.define?.['process.env.NODE_ENV'] !== '"production"') {
126
+ reason = 'only the standard production JSX runtime is supported';
127
+ }
128
+ if (!reason) {
129
+ try {
130
+ const { createPureJsxGroups } = await import('./editor-pure-jsx.mjs');
131
+ const plan = await createPureJsxGroups({ result, metadata, directory, entries: chunks, maxBytes: pureJsxGroups.maxBytes });
132
+ grouping = plan.summary;
133
+ if (plan.groups.length) {
134
+ const grouped = await Bun.build({ ...options, plugins: [plan.plugin, ...plugins] });
135
+ if (!grouped.success) {
136
+ throw new AggregateError(grouped.logs, 'Grouped native editor compilation failed');
137
+ }
138
+ const groupedMetadata = readMetadata(grouped);
139
+ await plan.verify(groupedMetadata, grouped);
140
+ result = grouped;
141
+ metadata = groupedMetadata;
142
+ }
143
+ } catch (error) {
144
+ reason = error.message;
145
+ }
146
+ }
147
+ if (reason) {
148
+ console.warn(`[eightshift] Pure JSX grouping disabled: ${reason}. Using the ungrouped native build.`);
149
+ grouping = { maxBytes: pureJsxGroups.maxBytes, groups: [], disabled: reason };
150
+ }
151
+ }
152
+
153
+ const outputPaths = new Set();
154
+ for (const output of result.outputs) {
155
+ const location = relative(directory, output.path);
156
+ if (!location || isAbsolute(location) || location === '..' || location.startsWith(`..${sep}`)) {
157
+ throw new Error(`Native editor output escapes its directory: ${output.path}`);
158
+ }
159
+ if (!['entry-point', 'chunk', 'sourcemap'].includes(output.kind) || !/\.js(?:\.map)?$/.test(location)) {
160
+ throw new Error(`Unexpected native editor asset: ${output.path}`);
161
+ }
162
+ if (outputPaths.has(output.path)) {
163
+ throw new Error(`Duplicate native editor output: ${output.path}`);
164
+ }
165
+ outputPaths.add(output.path);
166
+ }
167
+
168
+ const names = new Map();
169
+ const entries = new Set();
170
+ for (const [file, info] of Object.entries(metadata.outputs)) {
171
+ if (!info.entryPoint) {
172
+ continue;
173
+ }
174
+ const target = resolve(info.entryPoint);
175
+ if (!chunks.has(target)) {
176
+ continue;
177
+ }
178
+ const output = resolve(directory, file);
179
+ if (!outputPaths.has(output) || entries.has(output)) {
180
+ throw new Error(`Missing or ambiguous native editor entry: ${target}`);
181
+ }
182
+ entries.add(output);
183
+ names.set(target, relative(directory, output).split(sep).join('/'));
184
+ }
185
+
186
+ if (names.size !== chunks.size) {
187
+ throw new Error(`Expected ${chunks.size} native editor entries, found ${names.size}`);
188
+ }
189
+
190
+ return { names, outputs: result.outputs, metafile: metadata, ...(grouping ? { pureJsxGroups: grouping } : {}) };
191
+ }