@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.
@@ -0,0 +1,140 @@
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
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
8
+
9
+ /**
10
+ * Migrate literal webpack require.context calls in selected source files.
11
+ * Generated modules live in outputDir and must be regenerated on rebuild.
12
+ * Set lazyContexts to match contexts whose callers expect promises, and
13
+ * omitContexts to match contexts handled separately (for example CSS).
14
+ * Template-literal imports and nonliteral require.context calls are not rewritten.
15
+ */
16
+ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/, lazyContexts = () => false, omitContexts = () => false, transformSource } = {}) {
17
+ if (!root || !outputDir) {
18
+ throw new TypeError('root and outputDir are required');
19
+ }
20
+
21
+ outputDir = resolve(root, outputDir);
22
+ root = realpathSync(root);
23
+
24
+ const plugin = {
25
+ name: 'eightshift-discovery',
26
+ setup(builder) {
27
+ builder.onLoad({ filter }, async ({ path }) => {
28
+ if (!path.startsWith(`${root}${sep}`)) {
29
+ return;
30
+ }
31
+
32
+ const source = await readFile(path, 'utf8');
33
+
34
+ if (!source.includes('require.context')) {
35
+ return;
36
+ }
37
+
38
+ const pattern = /require\.context\(\s*(['"])([^'"\n]+)\1\s*,\s*(true|false)\s*,\s*\/(?!\*)(?!\/)((?:\\.|[^/\n])+)\/([dgimsuvy]*)\s*(?:,\s*(['"])(sync|lazy)\6\s*)?\)/g;
39
+ const matches = [...source.matchAll(pattern)];
40
+
41
+ if (!matches.length) {
42
+ throw new Error(`Unsupported require.context in ${path}`);
43
+ }
44
+
45
+ const definitions = [];
46
+ let contents = '';
47
+ let offset = 0;
48
+
49
+ for (const match of matches) {
50
+ const [, , directory, recursive, expression, flags, , webpackMode] = match;
51
+
52
+ if (recursive !== 'true') {
53
+ throw new Error(`Nonrecursive require.context is unsupported in ${path}`);
54
+ }
55
+
56
+ const context = { path, directory, pattern: new RegExp(expression, flags), mode: webpackMode || 'sync' };
57
+ const name = `context${definitions.length}`;
58
+
59
+ contents += source.slice(offset, match.index);
60
+
61
+ if (omitContexts(context)) {
62
+ contents += 'Object.assign(() => ({}), { keys: () => [] })';
63
+ } else {
64
+ definitions.push({ name, directory: resolve(dirname(path), directory), pattern: context.pattern, mode: lazyContexts(context) ? 'lazy' : context.mode });
65
+ contents += name;
66
+ }
67
+
68
+ offset = match.index + match[0].length;
69
+ }
70
+
71
+ contents += source.slice(offset);
72
+
73
+ if (contents.includes('require.context')) {
74
+ throw new Error(`Unsupported require.context remains in ${path}`);
75
+ }
76
+
77
+ if (definitions.length) {
78
+ const id = createHash('sha256').update(relative(root, path)).digest('hex').slice(0, 20);
79
+ const output = resolve(outputDir, `${id}.mjs`);
80
+
81
+ await generateDiscovery({ root, output, definitions });
82
+ contents = `import { ${definitions.map(({ name }) => name).join(', ')} } from ${JSON.stringify(output)};\n${contents}`;
83
+ }
84
+
85
+ contents = transformSource ? transformSource(contents, path) : contents;
86
+
87
+ return { contents, loader: 'jsx', resolveDir: dirname(path) };
88
+ });
89
+ },
90
+ };
91
+ return transformSource ? plugin : allowPureJsxGrouping(plugin);
92
+ }
93
+
94
+ /** Rewrite literal relative dynamic imports for a synchronous IIFE editor build.
95
+ * Build collected targets as ESM entries, then wrap the IIFE in a function
96
+ * receiving scriptUrlIdentifier from currentScript.src. Chunk URLs are relative
97
+ * to that script. The caller owns chunk output/builds.
98
+ * Pass transformSource to eightshiftDiscovery to compose both onLoad hooks.
99
+ * Existing chunks Map names are reused. Set versioned: false when those names
100
+ * already contain content hashes, as in native editor sharing.
101
+ */
102
+ export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', filter = /\.[cm]?jsx?$/, include = (path) => !path.split(sep).includes('node_modules'), versioned = true } = {}) {
103
+ if (!root || !(chunks instanceof Map) || !/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
104
+ throw new TypeError('Expected root, chunks Map and valid script URL identifier');
105
+ }
106
+
107
+ root = realpathSync(resolve(root));
108
+ const require = createRequire(import.meta.url);
109
+ const transformSource = (source, path) =>
110
+ !include(path)
111
+ ? source
112
+ : source.replace(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])(\.[^'"\n]+)\1\s*\)/g, (_match, _quote, specifier) => {
113
+ const target = require.resolve(resolve(dirname(path), specifier));
114
+ const name = chunks.get(target) ?? `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
115
+
116
+ chunks.set(target, name);
117
+ const version = versioned ? '?v=00000000000000000000' : '';
118
+
119
+ return `import(new URL(${JSON.stringify(`${chunkDir}/${name}${version}`)}, ${scriptUrlIdentifier}).href)`;
120
+ });
121
+ const plugin = {
122
+ name: 'eightshift-editor-lazy-imports',
123
+ setup(builder) {
124
+ builder.onLoad({ filter }, async ({ path }) => {
125
+ if (!path.startsWith(`${root}${sep}`)) {
126
+ return;
127
+ }
128
+
129
+ const source = await readFile(path, 'utf8');
130
+ const contents = transformSource(source, path);
131
+
132
+ if (contents !== source) {
133
+ return { contents, loader: 'jsx', resolveDir: dirname(path) };
134
+ }
135
+ });
136
+ },
137
+ };
138
+
139
+ return { plugin, transformSource };
140
+ }
@@ -0,0 +1,411 @@
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 rewriteLegacy = (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
+ source = source.replaceAll(`${quote}${value}?`, `${quote}./${basename(target)}?`);
84
+ source = source.replaceAll(`${quote}${value}#`, `${quote}./${basename(target)}#`);
85
+ }
86
+
87
+ source = source.replaceAll(`sourceMappingURL=${value}`, `sourceMappingURL=./${basename(target)}`);
88
+ }
89
+ }
90
+
91
+ return source;
92
+ };
93
+
94
+ const referencePatterns = new Map();
95
+ const rewrite = (input, path) => {
96
+ // Keep the existing source-map comment handling for map-bearing files.
97
+ if (input.includes('sourceMappingURL=')) {
98
+ return rewriteLegacy(input, path);
99
+ }
100
+
101
+ const directory = posix.dirname(path);
102
+ const editorPath = path.startsWith('editor/');
103
+ const cacheKey = `${directory}:${editorPath}`;
104
+ let cached = referencePatterns.get(cacheKey);
105
+
106
+ if (!cached) {
107
+ const references = new Map();
108
+
109
+ for (const target of sources.keys()) {
110
+ const reference = posix.relative(directory, target);
111
+ if (!reference) {
112
+ continue;
113
+ }
114
+
115
+ const variants = [reference];
116
+ if (!reference.startsWith('.')) {
117
+ variants.push(`./${reference}`);
118
+ }
119
+ if (target.startsWith('editor/editor-assets/') || (target.startsWith('editor/') && editorPath)) {
120
+ variants.push(target.slice('editor/'.length));
121
+ }
122
+ for (const value of variants) {
123
+ references.set(value, `./${basename(target)}`);
124
+ }
125
+ }
126
+
127
+ const alternatives = [...references.keys()].map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
128
+ let pattern;
129
+ let fallback = alternatives.length > 200000;
130
+
131
+ if (alternatives && !fallback) {
132
+ try {
133
+ pattern = new RegExp(`(["'])(?:${alternatives})(?=\\1|[?#])`, 'g');
134
+ } catch (error) {
135
+ if (!(error instanceof SyntaxError)) {
136
+ throw error;
137
+ }
138
+ fallback = true;
139
+ }
140
+ }
141
+ cached = { references, pattern, fallback };
142
+ referencePatterns.set(cacheKey, cached);
143
+ }
144
+
145
+ if (cached.fallback) {
146
+ return rewriteLegacy(input, path);
147
+ }
148
+ if (!cached.pattern) {
149
+ return input;
150
+ }
151
+ return input.replace(cached.pattern, (match, quote) => `${quote}${cached.references.get(match.slice(1))}`);
152
+ };
153
+
154
+ const contentFor = async (path) => {
155
+ const content = await readFile(sources.get(path));
156
+ return /\.(?:js|css|map)$/.test(basename(path)) ? Buffer.from(rewrite(content.toString(), path)) : content;
157
+ };
158
+ const outputNames = new Map();
159
+ for (const path of sources.keys()) {
160
+ if (path === editorEntry) {
161
+ continue;
162
+ }
163
+ const name = basename(path);
164
+ const previous = outputNames.get(name);
165
+ if (previous !== undefined) {
166
+ if (!(await contentFor(path)).equals(await contentFor(previous))) {
167
+ throw new Error(`Flat output collision: ${path} and ${previous}`);
168
+ }
169
+ } else {
170
+ outputNames.set(name, path);
171
+ }
172
+ }
173
+
174
+ await mkdir(flatDir);
175
+
176
+ for (const [path] of sources) {
177
+ const name = basename(path);
178
+
179
+ if (path === editorEntry || outputNames.get(name) !== path) {
180
+ continue;
181
+ }
182
+
183
+ await writeFile(resolve(flatDir, name), await contentFor(path), { flag: 'wx' });
184
+ }
185
+
186
+ if (editorEntry !== undefined) {
187
+ await writeFile(resolve(flatDir, 'editor-entry.js'), rewrite(editorScript, editorEntry), { flag: 'wx' });
188
+ }
189
+
190
+ return { sources, rewrite };
191
+ }
192
+
193
+ /** Package flattened files, optional SSR files and standalone assets. */
194
+ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, outputDirectory, removeIntermediates = false }) {
195
+ const files = [];
196
+
197
+ for (const name of await readdir(flatDir)) {
198
+ files.push({ source: resolve(flatDir, name), destination: name });
199
+ }
200
+
201
+ const extraAliases = {};
202
+
203
+ for (const name of [...ssrNames].sort()) {
204
+ pathName(name);
205
+
206
+ if (name.includes('/')) {
207
+ throw new Error(`Invalid SSR name: ${name}`);
208
+ }
209
+
210
+ files.push({ source: resolve(ssrDir, `${name}.js`), destination: `ssr/${name}.js` });
211
+ extraAliases[`ssr/${name}.js`] = `ssr/${name}.js`;
212
+ }
213
+
214
+ for (const [name, source] of standaloneAssets) {
215
+ pathName(name);
216
+ files.push({ source, destination: name });
217
+ extraAliases[name] = name;
218
+ }
219
+
220
+ const omitted = removeIntermediates ? entries.flatMap((entry) => [entry.style, ...(entry.script !== undefined ? [entry.entry] : [])]) : [];
221
+ for (const entry of entries) {
222
+ if (entry.script === undefined && omitted.includes(entry.entry)) {
223
+ throw new Error(`Cannot omit a script bootstrap target: ${entry.entry}`);
224
+ }
225
+ }
226
+ return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory, omit: [...new Set(omitted)] });
227
+ }
228
+
229
+ /** Publish a flat release and synchronize an existing PHP asset cache.
230
+ * Staged publication restores the previous public directory on cache failure.
231
+ * Direct publication writes in public and does not roll back. Missing caches are ignored.
232
+ */
233
+ export async function publishFlatRelease({ root, wpRoot, release, manifest, version, direct = false, publicPrefix }) {
234
+ root = resolve(root);
235
+ wpRoot = resolve(wpRoot);
236
+ release = resolve(release);
237
+ const publicDir = resolve(root, 'public');
238
+ const within = (parent, child) => {
239
+ const path = relative(parent, child);
240
+
241
+ return !path || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));
242
+ };
243
+
244
+ if ((!direct && (within(publicDir, release) || within(release, publicDir) || within(release, root))) || (direct && release !== publicDir)) {
245
+ throw new Error('Release, root and public directory must be distinct');
246
+ }
247
+
248
+ if (publicPrefix === undefined) {
249
+ const themePath = relative(wpRoot, root);
250
+
251
+ if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
252
+ throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
253
+ }
254
+
255
+ publicPrefix = `/${themePath.split(sep).join('/')}/public/`;
256
+ }
257
+
258
+ if (typeof publicPrefix !== 'string' || !publicPrefix.startsWith('/') || publicPrefix.startsWith('//') || !publicPrefix.endsWith('/') || publicPrefix.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPrefix) || publicPrefix.split('/').some((part) => part === '.' || part === '..')) {
259
+ throw new Error('publicPrefix must be a root-relative URL path ending in /');
260
+ }
261
+
262
+ const info = await lstat(release);
263
+
264
+ if (!info.isDirectory() || info.isSymbolicLink()) {
265
+ throw new Error('Release must be a directory');
266
+ }
267
+
268
+ const result = { ...manifest };
269
+
270
+ for (const [key, value] of Object.entries(result)) {
271
+ pathName(key);
272
+ pathName(value);
273
+ let current = release;
274
+
275
+ for (const part of value.split('/')) {
276
+ current = resolve(current, part);
277
+ const entry = await lstat(current);
278
+
279
+ if (entry.isSymbolicLink()) {
280
+ throw new Error(`Symlink in release path: ${value}`);
281
+ }
282
+ }
283
+
284
+ if (!(await lstat(current)).isFile()) {
285
+ throw new Error(`Manifest target is not a file: ${value}`);
286
+ }
287
+ }
288
+
289
+ for (const name of await readdir(release)) {
290
+ const entry = await lstat(resolve(release, name));
291
+
292
+ if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) {
293
+ throw new Error(`Unsupported release output: ${name}`);
294
+ }
295
+
296
+ if (name !== 'manifest.json' && name !== 'ssr' && !(direct && name === '.build') && !Object.hasOwn(result, name)) {
297
+ result[name] = name;
298
+ }
299
+ }
300
+
301
+ const publicManifest = Object.fromEntries(Object.entries(result).map(([key, value]) => [key, `${publicPrefix}${value}`]));
302
+
303
+ await writeFile(resolve(release, 'manifest.json'), `${JSON.stringify(publicManifest, null, 2)}\n`);
304
+ const backup = resolve(root, `.public-previous-${randomUUID()}`);
305
+ let hadPublic = false;
306
+
307
+ if (!direct) {
308
+ try {
309
+ const publicInfo = await lstat(publicDir);
310
+
311
+ if (!publicInfo.isDirectory() || publicInfo.isSymbolicLink()) {
312
+ throw new Error('Refusing to replace non-directory public path');
313
+ }
314
+
315
+ await rename(publicDir, backup);
316
+ hadPublic = true;
317
+ } catch (error) {
318
+ if (error.code !== 'ENOENT') {
319
+ throw error;
320
+ }
321
+ }
322
+ }
323
+
324
+ try {
325
+ if (!direct) {
326
+ await rename(release, publicDir);
327
+ }
328
+ const cachePath = resolve(root, 'eightshift/manifests.json');
329
+ let cacheExists = false;
330
+
331
+ try {
332
+ const cacheInfo = await lstat(cachePath);
333
+ if (!cacheInfo.isFile() || cacheInfo.isSymbolicLink()) {
334
+ throw new Error(`Manifest cache must be a regular file: ${cachePath}`);
335
+ }
336
+ cacheExists = true;
337
+ } catch (error) {
338
+ if (error.code !== 'ENOENT') {
339
+ throw error;
340
+ }
341
+ }
342
+
343
+ if (cacheExists) {
344
+ let temporary;
345
+
346
+ try {
347
+ const cacheInfo = await lstat(cachePath);
348
+ if (!cacheInfo.isFile() || cacheInfo.isSymbolicLink()) {
349
+ throw new Error(`Manifest cache must be a regular file: ${cachePath}`);
350
+ }
351
+ const data = JSON.parse(await readFile(cachePath, 'utf8'));
352
+
353
+ if (!data?.assets || Array.isArray(data.assets) || typeof data.assets !== 'object' || !data.assets.assets || Array.isArray(data.assets.assets) || typeof data.assets.assets !== 'object') {
354
+ throw new Error('Invalid manifest cache structure');
355
+ }
356
+
357
+ data.assets.assets = publicManifest;
358
+ temporary = `${cachePath}.${randomUUID()}`;
359
+ await writeFile(temporary, JSON.stringify(data), { flag: 'wx', mode: cacheInfo.mode & 0o7777 });
360
+ await chmod(temporary, cacheInfo.mode & 0o7777);
361
+ await rename(temporary, cachePath);
362
+ temporary = undefined;
363
+ } finally {
364
+ if (temporary) {
365
+ await unlink(temporary).catch((error) => {
366
+ if (error.code !== 'ENOENT') {
367
+ throw error;
368
+ }
369
+ });
370
+ }
371
+ }
372
+ }
373
+ } catch (error) {
374
+ if (direct) {
375
+ throw error;
376
+ }
377
+ try {
378
+ await rename(publicDir, release);
379
+ } catch (rollbackError) {
380
+ if (rollbackError.code !== 'ENOENT') {
381
+ throw rollbackError;
382
+ }
383
+ }
384
+
385
+ if (hadPublic) {
386
+ await rename(backup, publicDir);
387
+ }
388
+
389
+ throw error;
390
+ }
391
+
392
+ const removeTree = async (path) => {
393
+ const entry = await lstat(path);
394
+
395
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
396
+ for (const name of await readdir(path)) {
397
+ await removeTree(resolve(path, name));
398
+ }
399
+
400
+ await rmdir(path);
401
+ } else {
402
+ await unlink(path);
403
+ }
404
+ };
405
+
406
+ if (hadPublic) {
407
+ await removeTree(backup);
408
+ }
409
+
410
+ return { publicDir, manifest: publicManifest, version };
411
+ }
package/bun/index.mjs ADDED
@@ -0,0 +1,118 @@
1
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
2
+ import { buildPreset, createPreset } from './preset.mjs';
3
+ import { watchBuild } from './watch.mjs';
4
+
5
+ /**
6
+ * Define a reusable build. `preset` may be an object or a function of the
7
+ * invocation context. `ssr` and `publish` run after the browser build, in that
8
+ * order; neither is included in the browser build's atomic publication.
9
+ * Watch options are passed to watchBuild, with root and build controlled here.
10
+ */
11
+ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch = {} } = {}) {
12
+ if (typeof root !== 'string' || !root) {
13
+ throw new TypeError('root must be a non-empty string');
14
+ }
15
+
16
+ if (!preset || (typeof preset !== 'object' && typeof preset !== 'function') || Array.isArray(preset)) {
17
+ throw new TypeError('preset must be an object or function');
18
+ }
19
+
20
+ if (ssr !== undefined && typeof ssr !== 'function') {
21
+ throw new TypeError('ssr must be a function');
22
+ }
23
+
24
+ if (publish !== undefined && typeof publish !== 'function') {
25
+ throw new TypeError('publish must be a function');
26
+ }
27
+
28
+ if (!watch || typeof watch !== 'object' || Array.isArray(watch)) {
29
+ throw new TypeError('watch must be an object');
30
+ }
31
+
32
+ if (watch.ignore !== undefined && typeof watch.ignore !== 'function') {
33
+ throw new TypeError('watch.ignore must be a function');
34
+ }
35
+
36
+ root = resolve(root);
37
+ let active;
38
+ const outputs = new Set();
39
+ const run = async (options = {}) => {
40
+ if (active) {
41
+ throw new Error('A build is already running');
42
+ }
43
+
44
+ active = (async () => {
45
+ const context = { ...options, root };
46
+ const configured = typeof preset === 'function' ? await preset(context) : preset;
47
+ outputs.clear();
48
+ const output = typeof configured?.outdir === 'string' && configured.outdir ? resolve(root, configured.outdir) : undefined;
49
+ if (output) {
50
+ const rootFromOutput = relative(output, root);
51
+ if (!rootFromOutput || (!isAbsolute(rootFromOutput) && rootFromOutput !== '..' && !rootFromOutput.startsWith(`..${sep}`))) {
52
+ throw new Error('outdir must not contain the project root');
53
+ }
54
+ outputs.add(output);
55
+ }
56
+ const result = await buildPreset({ ...configured, root });
57
+ const state = { ...context, result };
58
+
59
+ if (ssr) {
60
+ state.ssr = await ssr(state);
61
+ }
62
+
63
+ if (publish) {
64
+ state.publication = await publish(state);
65
+ }
66
+
67
+ return state;
68
+ })();
69
+
70
+ try {
71
+ return await active;
72
+ } finally {
73
+ active = undefined;
74
+ }
75
+ };
76
+
77
+ return {
78
+ build: run,
79
+ watch: (options = {}) => {
80
+ if ((ssr || publish) && watch.sources === undefined && !watch.ignored?.length) {
81
+ throw new Error('Watch builds with ssr or publish callbacks require explicit watch.sources or watch.ignored');
82
+ }
83
+
84
+ return watchBuild({
85
+ sources: ['.'],
86
+ ...watch,
87
+ projectDir: root,
88
+ ignore: (path) => {
89
+ if (watch.ignore?.(path)) {
90
+ return true;
91
+ }
92
+ for (const output of outputs) {
93
+ const location = relative(output, path);
94
+ if (!location || (!isAbsolute(location) && location !== '..' && !location.startsWith(`..${sep}`))) {
95
+ return true;
96
+ }
97
+ const sibling = relative(dirname(output), path).split(sep)[0];
98
+ if (sibling.startsWith(`.${basename(output)}-stage-`) || sibling.startsWith(`.${basename(output)}-backup-`)) {
99
+ return true;
100
+ }
101
+ }
102
+ return false;
103
+ },
104
+ build: async () => {
105
+ while (active) {
106
+ await active.catch(() => {});
107
+ }
108
+ return run(options);
109
+ },
110
+ });
111
+ },
112
+ };
113
+ }
114
+
115
+ export { buildPreset, createPreset } from './preset.mjs';
116
+ export { build } from './build.mjs';
117
+ export { watchBuild } from './watch.mjs';
118
+ export { packageRelease } from './release.mjs';