Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): roll back a failed theme add or theme build write completely (#6852)

Joeyc15eda64086e
diff --git a/.changeset/theme-writes-roll-back.md b/.changeset/theme-writes-roll-back.md
new file mode 100644
index 0000000000..f4d8ff760d
--- /dev/null
+++ b/.changeset/theme-writes-roll-back.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme add` and `astryx theme build` now undo a failed write completely. Before, when one file failed to write after others were written, the written files kept their new content. Now every replaced file gets its previous content back, every new file is removed, and the error names any file that could not be restored. Both commands also refuse to replace a destination that is a symbolic link. (#6852)
+
+@josephfarina
diff --git a/packages/cli/api/integration/add-helpers.mjs b/packages/cli/api/integration/add-helpers.mjs
index 2a7a5131fd..0fab6b974d 100644
--- a/packages/cli/api/integration/add-helpers.mjs
+++ b/packages/cli/api/integration/add-helpers.mjs
@@ -5,7 +5,8 @@
*
* Hosts the atomic staged-write transaction, package.json files-array
* maintenance, package-dir resolution, and project-path normalization that
- * every `integration add <kind>` command needs. Stateless and side-effect-free
+ * every `integration add <kind>` command needs. `theme add` and `theme build`
+ * write through the same transaction. Stateless and side-effect-free
* outside of {@link applyWrites}.
*/
@@ -40,7 +41,7 @@ export function findPackageDir(startDir) {
/**
* @typedef {object} WritePlan
* @property {string} path
- * @property {string} contents
+ * @property {string | Buffer} contents a Buffer is written byte for byte
* @property {boolean} createOnly
* @property {Buffer} [expectedOriginal] bytes captured before validation;
* a different current file is a concurrent edit and must never be overwritten
@@ -192,21 +193,29 @@ export function packageJsonUpdate(
// ── Atomic staged-write transaction ─────────────────────────────────
-/** @param {string} file */
+/**
+ * @param {string} file
+ * @returns {boolean} false when the file is still there
+ */
function removeTemporary(file) {
try {
fs.rmSync(file, {force: true});
+ return true;
} catch {
// Best effort. The transaction error remains the actionable failure.
+ return false;
}
}
/**
* Restore writes that already published. Best-effort so callers preserve
- * the original actionable error.
+ * the original actionable error; returns every path it could not put back.
* @param {Array<WritePlan & {temporary: string, original: Buffer|null, mode: number}>} published
+ * @returns {string[]}
*/
function rollbackWrites(published) {
+ /** @type {string[]} */
+ const unrestored = [];
for (const plan of [...published].reverse()) {
let restore = null;
try {
@@ -225,12 +234,18 @@ function rollbackWrites(published) {
fs.renameSync(restore, plan.path);
restore = null;
}
- } catch {
- // Best effort. A concurrent edit belongs to its writer, not this rollback.
+ } catch (error) {
+ // A created file that is already gone needs nothing. Any other failure
+ // leaves this call's bytes, or no bytes, where the original was.
+ const gone =
+ error instanceof Error &&
+ /** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT';
+ if (!(gone && plan.original == null)) unrestored.push(plan.path);
} finally {
if (restore != null) removeTemporary(restore);
}
}
+ return unrestored;
}
/** @param {string} file */
@@ -325,10 +340,22 @@ export function applyWrites(plans) {
}
published.push(plan);
}
- return () => rollbackWrites(published);
+ return () => {
+ rollbackWrites(published);
+ };
} catch (error) {
- for (const plan of staged) removeTemporary(plan.temporary);
- rollbackWrites(published);
+ const leftovers = staged
+ .filter(plan => !removeTemporary(plan.temporary))
+ .map(plan => plan.temporary);
+ const unrestored = rollbackWrites(published);
+ if (error instanceof Error) {
+ if (unrestored.length > 0) {
+ error.message += ` Could not restore: ${unrestored.join(', ')}.`;
+ }
+ if (leftovers.length > 0) {
+ error.message += ` Could not remove temporary files: ${leftovers.join(', ')}.`;
+ }
+ }
throw error;
}
}
diff --git a/packages/cli/api/theme/add/add.mjs b/packages/cli/api/theme/add/add.mjs
index cec140e480..f67d7ae3ed 100644
--- a/packages/cli/api/theme/add/add.mjs
+++ b/packages/cli/api/theme/add/add.mjs
@@ -15,6 +15,7 @@ import {
import {AstryxError} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {listAvailableThemes, findTheme} from '../_adapter.mjs';
+import {applyWrites} from '../../integration/add-helpers.mjs';
// Scaffolded files must not carry our repo boilerplate into a consumer's tree.
import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
@@ -136,37 +137,28 @@ export async function themeAdd(slug, options = {}) {
}
}
- // Stage to temp files then rename, rolling back partials on failure so a
- // failed write never leaves a half-written theme. mkdir is inside the try so
- // a failure (e.g. an ancestor is a file → EEXIST/ENOTDIR) surfaces as a
- // stable ERR_WRITE_FAILED rather than leaking a raw fs errno + absolute path.
- const staged = [];
+ // One transaction: every file publishes, or every replaced file gets its
+ // previous bytes back and every created file is removed. mkdir is inside the
+ // try so a failure (e.g. an ancestor is a file → EEXIST/ENOTDIR) surfaces as
+ // a stable ERR_WRITE_FAILED rather than leaking a raw fs errno + absolute path.
try {
fs.mkdirSync(resolvedDir, {recursive: true});
- for (const w of writes) {
+ const plans = writes.map(w => {
+ fs.mkdirSync(path.dirname(w.dest), {recursive: true});
+ // Confine again once the directories exist: one may have been swapped
+ // for a link since the destination was first checked.
const dest = assertWithin(w.name, resolvedDir, {
label: `theme destination for ${w.name}`,
});
- fs.mkdirSync(path.dirname(dest), {recursive: true});
- // The staging file is an output path too: confine it, and never write
- // through an entry that already exists under its name.
- const tmp = assertWithin(`${w.name}.${process.pid}.tmp`, resolvedDir, {
- label: `theme staging file for ${w.name}`,
- });
- fs.writeFileSync(tmp, scaffoldContents(fs.readFileSync(w.src)), {flag: 'wx'});
- staged.push({tmp, dest});
- }
- for (const s of staged) {
- fs.renameSync(s.tmp, s.dest);
- }
+ return {
+ path: dest,
+ contents: scaffoldContents(fs.readFileSync(w.src)),
+ createOnly: !overwrite,
+ };
+ });
+ applyWrites(plans);
} catch (err) {
- for (const s of staged) {
- try {
- fs.rmSync(s.tmp, {force: true});
- } catch {
- /* best-effort */
- }
- }
+ if (err instanceof AstryxError) throw err;
if (err instanceof PathSafetyError) {
throw new AstryxError(
err.message,
diff --git a/packages/cli/api/theme/add/add.rollback.test.mjs b/packages/cli/api/theme/add/add.rollback.test.mjs
new file mode 100644
index 0000000000..609468d64f
--- /dev/null
+++ b/packages/cli/api/theme/add/add.rollback.test.mjs
@@ -0,0 +1,158 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * `theme add` writes a theme as one transaction: when a later file fails to
+ * publish, every file it already replaced gets its previous bytes back and
+ * every file it created is removed. Publishing is forced to fail by wrapping
+ * the two calls that publish a staged file: `linkSync` for a new file and
+ * `renameSync` for a replacement.
+ *
+ * Separate file because vi.mock is hoisted and affects the whole module.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+const failures = vi.hoisted(() => ({
+ /** Fail the Nth staged-file publish (1-based); 0 disables. */
+ publish: 0,
+ /** Also fail every rollback restore. */
+ restore: false,
+ count: 0,
+}));
+
+vi.mock('node:fs', async importOriginal => {
+ const actual = /** @type {typeof import('node:fs')} */ (
+ await importOriginal()
+ );
+ /** @param {string} source */
+ const isStaged = source => path.basename(String(source)).includes('.tmp');
+ /** @param {string} source */
+ const isRestore = source =>
+ path.basename(String(source)).includes('.restore-');
+ /** @param {string} source @param {string} op */
+ const maybeFail = (source, op) => {
+ if (isStaged(source) && failures.publish > 0) {
+ failures.count++;
+ if (failures.count === failures.publish) {
+ throw Object.assign(new Error(`EIO: forced ${op} failure`), {
+ code: 'EIO',
+ });
+ }
+ }
+ if (isRestore(source) && failures.restore) {
+ throw Object.assign(new Error(`EIO: forced restore failure`), {
+ code: 'EIO',
+ });
+ }
+ };
+ return {
+ ...actual,
+ linkSync: vi.fn((source, destination) => {
+ maybeFail(source, 'link');
+ return actual.linkSync(source, destination);
+ }),
+ renameSync: vi.fn((source, destination) => {
+ maybeFail(source, 'rename');
+ return actual.renameSync(source, destination);
+ }),
+ };
+});
+
+const fs = await import('node:fs');
+const {themeAdd} = await import('./add.mjs');
+const {listThemes} = await import('../_adapter.mjs');
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-rollback-'));
+ failures.publish = 0;
+ failures.restore = false;
+ failures.count = 0;
+});
+
+afterEach(() => {
+ failures.publish = 0;
+ failures.restore = false;
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+function stoneFiles() {
+ const theme = listThemes().find(entry => entry.slug === 'stone');
+ if (!theme) throw new Error('missing bundled theme stone');
+ expect(theme.files.length).toBeGreaterThanOrEqual(2);
+ return theme.files.map(name =>
+ path.join(tmpDir, 'src', 'themes', 'stone', name),
+ );
+}
+
+/** Entries staging or rollback left behind in the theme directory. */
+function strays() {
+ const dir = path.join(tmpDir, 'src', 'themes', 'stone');
+ if (!fs.existsSync(dir)) return [];
+ return fs
+ .readdirSync(dir, {recursive: true})
+ .map(String)
+ .filter(name => name.includes('.tmp') || name.includes('.restore-'));
+}
+
+describe('themeAdd rolls back a partial write', () => {
+ it('removes every created file when the second publish fails', async () => {
+ const files = stoneFiles();
+ failures.publish = 2;
+
+ await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_WRITE_FAILED',
+ });
+
+ for (const file of files) expect(fs.existsSync(file)).toBe(false);
+ expect(strays()).toEqual([]);
+ });
+
+ it('restores every replaced byte when the second publish fails', async () => {
+ const files = stoneFiles();
+ fs.mkdirSync(path.dirname(files[0]), {recursive: true});
+ const before = Buffer.from([0x00, 0xff, 0x0a, 0x62, 0x65, 0x66]);
+ fs.writeFileSync(files[0], before);
+ failures.publish = 2;
+
+ await expect(
+ themeAdd('stone', {cwd: tmpDir, overwrite: true}),
+ ).rejects.toMatchObject({code: 'ERR_WRITE_FAILED'});
+
+ expect(fs.readFileSync(files[0]).equals(before)).toBe(true);
+ for (const file of files.slice(1)) expect(fs.existsSync(file)).toBe(false);
+ expect(strays()).toEqual([]);
+ });
+
+ it('names a file it could not restore', async () => {
+ const files = stoneFiles();
+ fs.mkdirSync(path.dirname(files[0]), {recursive: true});
+ fs.writeFileSync(files[0], 'before\n');
+ failures.publish = 2;
+ failures.restore = true;
+
+ let error;
+ try {
+ await themeAdd('stone', {cwd: tmpDir, overwrite: true});
+ } catch (caught) {
+ error = caught;
+ }
+
+ expect(error?.code).toBe('ERR_WRITE_FAILED');
+ expect(error?.message).toContain('Could not restore');
+ expect(error?.message).toContain(files[0]);
+ });
+
+ it('writes every file when nothing fails', async () => {
+ const files = stoneFiles();
+
+ const result = await themeAdd('stone', {cwd: tmpDir});
+
+ expect(result.type).toBe('theme.add');
+ for (const file of files) expect(fs.existsSync(file)).toBe(true);
+ expect(strays()).toEqual([]);
+ });
+});
diff --git a/packages/cli/api/theme/add/add.staging.test.mjs b/packages/cli/api/theme/add/add.staging.test.mjs
index aab774b4ae..9206b9e4cf 100644
--- a/packages/cli/api/theme/add/add.staging.test.mjs
+++ b/packages/cli/api/theme/add/add.staging.test.mjs
@@ -6,14 +6,15 @@ import * as os from 'node:os';
import * as path from 'node:path';
import {themeAdd} from './add.mjs';
import {listThemes} from '../_adapter.mjs';
-import {isErrorCode} from '../../../foundation/response/error-codes.mjs';
let tmpDir;
let outsideDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-staging-'));
- outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-themeadd-outside-'));
+ outsideDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-themeadd-outside-'),
+ );
});
afterEach(() => {
@@ -22,45 +23,61 @@ afterEach(() => {
});
/**
- * Put a symlink where `theme add` stages the first file of `slug`.
+ * Where `theme add` writes the first file of `slug`.
* @param {string} slug
- * @param {string} target
*/
-function plantStagingLink(slug, target) {
+function firstDestination(slug) {
const theme = listThemes().find(entry => entry.slug === slug);
if (!theme) throw new Error(`missing bundled theme ${slug}`);
- const first = theme.files[0];
- const dest = path.join(tmpDir, 'src', 'themes', slug, first);
+ const dest = path.join(tmpDir, 'src', 'themes', slug, theme.files[0]);
fs.mkdirSync(path.dirname(dest), {recursive: true});
- fs.symlinkSync(target, `${dest}.${process.pid}.tmp`);
return dest;
}
+// Staging names are unpredictable and created exclusively, so an entry planted
+// at a predictable name beside the destination is never written through.
describe('themeAdd staging writes stay inside the project', () => {
- it('refuses a staging path that links outside the project', async () => {
+ it('never writes through a link planted at a predictable staging name', async () => {
const victim = path.join(outsideDir, 'victim.txt');
fs.writeFileSync(victim, 'outside\n');
- const dest = plantStagingLink('stone', victim);
+ const dest = firstDestination('stone');
+ fs.symlinkSync(victim, `${dest}.${process.pid}.tmp`);
+
+ await themeAdd('stone', {cwd: tmpDir});
- await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({
- code: 'ERR_PATH_TRAVERSAL',
- });
expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');
- expect(fs.existsSync(dest)).toBe(false);
+ expect(fs.lstatSync(dest).isFile()).toBe(true);
});
- it('never creates a file through a dangling staging link', async () => {
+ it('never creates a file through a dangling link at a predictable staging name', async () => {
const victim = path.join(outsideDir, 'created.txt');
- plantStagingLink('stone', victim);
+ fs.symlinkSync(victim, `${firstDestination('stone')}.${process.pid}.tmp`);
+
+ await themeAdd('stone', {cwd: tmpDir});
+
+ expect(fs.existsSync(victim)).toBe(false);
+ });
+
+ it('refuses to replace a destination that links outside the project', async () => {
+ const victim = path.join(outsideDir, 'victim.txt');
+ fs.writeFileSync(victim, 'outside\n');
+ const dest = firstDestination('stone');
+ fs.symlinkSync(victim, dest);
- let error;
- try {
- await themeAdd('stone', {cwd: tmpDir});
- } catch (caught) {
- error = caught;
- }
+ await expect(
+ themeAdd('stone', {cwd: tmpDir, overwrite: true}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ expect(fs.readFileSync(victim, 'utf-8')).toBe('outside\n');
+ expect(fs.lstatSync(dest).isSymbolicLink()).toBe(true);
+ });
- expect(isErrorCode(error?.code)).toBe(true);
+ it('never creates a file through a dangling destination link', async () => {
+ const victim = path.join(outsideDir, 'created.txt');
+ fs.symlinkSync(victim, firstDestination('stone'));
+
+ await expect(themeAdd('stone', {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_PATH_TRAVERSAL',
+ });
expect(fs.existsSync(victim)).toBe(false);
});
});
diff --git a/packages/cli/api/theme/build/build.family.test.mjs b/packages/cli/api/theme/build/build.family.test.mjs
index d746c1011a..2b6c3791d9 100644
--- a/packages/cli/api/theme/build/build.family.test.mjs
+++ b/packages/cli/api/theme/build/build.family.test.mjs
@@ -251,23 +251,18 @@ describe('themeBuildFamily()', () => {
const dir = makeDir();
const files = writeFamily(dir);
const outputDir = path.join(dir, 'themes');
- const blockedTmp = path.join(
- outputDir,
- `${FAMILY_KEY}.js.${process.pid}.tmp`,
- );
- fs.mkdirSync(blockedTmp);
+ // A directory where the JS output goes fails its staging after the CSS
+ // output was already staged.
+ fs.mkdirSync(path.join(outputDir, `${FAMILY_KEY}.js`));
await expect(build(dir, files)).rejects.toThrow(
/Failed to write theme outputs/,
);
- for (const output of OUTPUTS) {
- expect(fs.existsSync(path.join(outputDir, output))).toBe(false);
- }
+ expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.css`))).toBe(false);
+ expect(fs.existsSync(path.join(outputDir, `${FAMILY_KEY}.d.ts`))).toBe(false);
expect(
- fs.existsSync(
- path.join(outputDir, `${FAMILY_KEY}.css.${process.pid}.tmp`),
- ),
- ).toBe(false);
+ fs.readdirSync(outputDir).filter(name => name.includes('.tmp-')),
+ ).toEqual([]);
});
it('rejects invalid graphs and keys before touching an existing trio', async () => {
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 1a2281bc52..a060bf3d2b 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -53,6 +53,7 @@ import {
} from '../../../foundation/fs/path-safety.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {AstryxError} from '../../error.mjs';
+import {applyWrites} from '../../integration/add-helpers.mjs';
import {logger} from '../../logger.mjs';
import {loadComponentDoc} from '../../../foundation/discovery/component-loader.mjs';
import {
@@ -224,26 +225,15 @@ function staleBuildOutputs(writes, cwd) {
/** @param {Array<{dest: string, content: string}>} writes */
function writeBuildOutputs(writes) {
if (writes.length === 0) return;
- /** @type {Array<{tmp: string, dest: string}>} */
- const staged = [];
try {
- fs.mkdirSync(path.dirname(writes[0].dest), {recursive: true});
- for (const write of writes) {
- const tmp = `${write.dest}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, write.content);
- staged.push({tmp, dest: write.dest});
- }
- for (const stagedWrite of staged) {
- fs.renameSync(stagedWrite.tmp, stagedWrite.dest);
- }
+ applyWrites(
+ writes.map(write => ({
+ path: write.dest,
+ contents: write.content,
+ createOnly: false,
+ })),
+ );
} catch (error) {
- for (const stagedWrite of staged) {
- try {
- fs.rmSync(stagedWrite.tmp, {force: true});
- } catch {
- // Best effort: the command still fails and never reports success.
- }
- }
const message = `Failed to write theme outputs: ${/** @type {Error} */ (error).message}`;
throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
}
diff --git a/packages/cli/api/theme/build/build.rollback.test.mjs b/packages/cli/api/theme/build/build.rollback.test.mjs
new file mode 100644
index 0000000000..23eeac0302
--- /dev/null
+++ b/packages/cli/api/theme/build/build.rollback.test.mjs
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * `theme build` writes its CSS, JS, and declarations as one transaction: when
+ * a later output fails to publish, every output it already replaced gets its
+ * previous bytes back and every output it created is removed. Publishing is
+ * forced to fail by wrapping the two calls that publish a staged file:
+ * `linkSync` for a new file and `renameSync` for a replacement.
+ *
+ * Separate file because vi.mock is hoisted and affects the whole module.
+ * `themeBuild` needs a built core; the `node` project's globalSetup builds it.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+const failures = vi.hoisted(() => ({
+ /** Fail the Nth staged-file publish (1-based); 0 disables. */
+ publish: 0,
+ count: 0,
+}));
+
+vi.mock('node:fs', async importOriginal => {
+ const actual = /** @type {typeof import('node:fs')} */ (
+ await importOriginal()
+ );
+ /** @param {string} source @param {string} op */
+ const maybeFail = (source, op) => {
+ if (!path.basename(String(source)).includes('.tmp')) return;
+ if (failures.publish === 0) return;
+ failures.count++;
+ if (failures.count === failures.publish) {
+ throw Object.assign(new Error(`EIO: forced ${op} failure`), {
+ code: 'EIO',
+ });
+ }
+ };
+ return {
+ ...actual,
+ linkSync: vi.fn((source, destination) => {
+ maybeFail(source, 'link');
+ return actual.linkSync(source, destination);
+ }),
+ renameSync: vi.fn((source, destination) => {
+ maybeFail(source, 'rename');
+ return actual.renameSync(source, destination);
+ }),
+ };
+});
+
+const fs = await import('node:fs');
+const {themeBuild} = await import('./build.mjs');
+
+vi.setConfig({testTimeout: 30000});
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-theme-build-rollback-'),
+ );
+ failures.publish = 0;
+ failures.count = 0;
+});
+
+afterEach(() => {
+ failures.publish = 0;
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * Write a source for the theme named `rollbacktheme`. Each call uses a new
+ * file so the loader cannot serve an earlier version from its cache.
+ * @param {string} file @param {string} background
+ */
+function writeTheme(file, background) {
+ fs.writeFileSync(
+ path.join(tmpDir, file),
+ `export default { name: 'rollbacktheme', tokens: { '--color-bg': '${background}' } };\n`,
+ );
+ return file;
+}
+
+const OUTPUTS = ['rollbacktheme.css', 'rollbacktheme.js', 'rollbacktheme.d.ts'];
+
+/** @returns {Map<string, Buffer | null>} */
+function readOutputs() {
+ return new Map(
+ OUTPUTS.map(name => {
+ const file = path.join(tmpDir, name);
+ return [name, fs.existsSync(file) ? fs.readFileSync(file) : null];
+ }),
+ );
+}
+
+function strays() {
+ return fs
+ .readdirSync(tmpDir)
+ .filter(name => name.includes('.tmp') || name.includes('.restore-'));
+}
+
+describe('themeBuild rolls back a partial write', () => {
+ it('removes every created output when the second publish fails', async () => {
+ const source = writeTheme('first.mjs', '#0a0a0a');
+ failures.publish = 2;
+
+ await expect(themeBuild(source, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_WRITE_FAILED',
+ });
+
+ for (const bytes of readOutputs().values()) expect(bytes).toBeNull();
+ expect(strays()).toEqual([]);
+ });
+
+ it('restores every replaced output when the second publish fails', async () => {
+ const first = await themeBuild(
+ writeTheme('first.mjs', '#0a0a0a'),
+ {},
+ {cwd: tmpDir},
+ );
+ expect(first?.type).toBe('theme.build');
+ const before = readOutputs();
+ for (const bytes of before.values()) expect(bytes).not.toBeNull();
+
+ const next = writeTheme('next.mjs', '#fafafa');
+ failures.publish = 2;
+ await expect(themeBuild(next, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_WRITE_FAILED',
+ });
+
+ const after = readOutputs();
+ for (const name of OUTPUTS) {
+ expect(
+ after.get(name)?.equals(/** @type {Buffer} */ (before.get(name))),
+ ).toBe(true);
+ }
+
+ // The failed build really had different bytes to write.
+ failures.publish = 0;
+ await themeBuild(next, {}, {cwd: tmpDir});
+ const css = readOutputs().get('rollbacktheme.css');
+ expect(
+ css?.equals(/** @type {Buffer} */ (before.get('rollbacktheme.css'))),
+ ).toBe(false);
+ expect(strays()).toEqual([]);
+ });
+});