Skip to content

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

TypeScript

fix(cli): theme build --check compares outputs outside the working directory read-only (#7652)

Joeyf8f7cf1bd4c6
diff --git a/.changeset/theme-build-check-reads-outside.md b/.changeset/theme-build-check-reads-outside.md
new file mode 100644
index 0000000000..adfc567be9
--- /dev/null
+++ b/.changeset/theme-build-check-reads-outside.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme build --check` and `themeBuild({check: true})` keep comparing outputs outside the working directory, as the latest release does, rather than refusing them with `ERR_PATH_TRAVERSAL` the way a build does. Check mode writes nothing, so the write confinement of `architecture:cli-surface/INV10` and `INV10a` does not apply to it: an absolute `--out` path outside the working directory, a theme file outside it whose outputs sit beside it, and `--family` with its root theme file outside it are each checked read-only. A relative `--out` path that escapes the working directory is still refused, as before. Builds keep refusing every one of these writes, so when such outputs are stale, the report no longer ends with a `Rebuild with:` command the build refuses. It names the nearest directory that contains the theme files and the outputs, and the build and check commands to run from there: each output's `Source:` header records the directory its build ran from, so the check passes only from that same directory. Stale outputs inside the working directory keep the `Rebuild with:` line.
+
+@josephfarina
diff --git a/.changeset/theme-build-confine-outputs.md b/.changeset/theme-build-confine-outputs.md
index adaf4cdfaa..3416316a91 100644
--- a/.changeset/theme-build-confine-outputs.md
+++ b/.changeset/theme-build-confine-outputs.md
@@ -2,6 +2,6 @@
'@astryxdesign/cli': patch
---
-[fix] `astryx theme build` and `themeBuild()` now write only inside the working directory (`cwd` for the API), as `architecture:cli-surface/INV10` requires; under `architecture:cli-surface/INV10a` the refusal is a compatible fix. Each of these now fails with `ERR_PATH_TRAVERSAL` before anything is written, and `--check` refuses the same paths: an absolute `--out` path outside the working directory, a theme file outside it whose outputs would go beside it, and `--family` with its root theme file outside it. Paths inside the working directory still build, including through a symlink. To migrate, run the build from a folder that holds the theme file and its outputs, or pass an `--out` path inside that folder; API callers pass a `cwd` that holds them.
+[fix] `astryx theme build` and `themeBuild()` now write only inside the working directory (`cwd` for the API), as `architecture:cli-surface/INV10` requires; under `architecture:cli-surface/INV10a` the refusal is a compatible fix. Each of these builds now fails with `ERR_PATH_TRAVERSAL` before anything is written: an absolute `--out` path outside the working directory, a theme file outside it whose outputs would go beside it, and `--family` with its root theme file outside it. Paths inside the working directory still build, including through a symlink. To migrate, run the build from a folder that holds the theme file and its outputs, or pass an `--out` path inside that folder; API callers pass a `cwd` that holds them.
@josephfarina
diff --git a/packages/cli/api/theme/build/build.family.test.mjs b/packages/cli/api/theme/build/build.family.test.mjs
index a85c49e95c..90234ca2db 100644
--- a/packages/cli/api/theme/build/build.family.test.mjs
+++ b/packages/cli/api/theme/build/build.family.test.mjs
@@ -13,6 +13,7 @@ import {themeBuild, themeBuildFamily} from './build.mjs';
import {interceptCore} from './core-interception.mjs';
import {ensureCoreBuilt} from '../../../clients/cli/commands/ensure-core-built.mjs';
import {runCli} from '../../../test-utils/run-cli.mjs';
+import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
vi.setConfig({testTimeout: 120_000});
const CLI_ROOT = path.resolve(import.meta.dirname, '../../..');
const FAMILY_KEY = 'ocean-family';
@@ -252,22 +253,69 @@ describe('themeBuildFamily()', () => {
expect(fs.existsSync(dtsPath)).toBe(false);
});
- it('refuses family outputs outside cwd before checking or writing', async () => {
+ it('refuses to write family outputs outside cwd, and checks them read-only', async () => {
const dir = makeDir();
const files = writeFamily(dir).map(file => path.join(dir, file));
const app = path.join(dir, 'app');
fs.mkdirSync(app);
- for (const check of [false, true]) {
- await expect(
- themeBuildFamily(files, {familyKey: FAMILY_KEY, check}, {cwd: app}),
- ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
- }
+ await expect(
+ themeBuildFamily(files, {familyKey: FAMILY_KEY}, {cwd: app}),
+ ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
+ const checked = await themeBuildFamily(
+ files,
+ {familyKey: FAMILY_KEY, check: true},
+ {cwd: app},
+ );
+ expect(checked?.type).toBe('theme.build.check');
+ expect(checked?.data.upToDate).toBe(false);
+ // The `.css.d.ts` import stub may be absent in check mode.
+ expect(checked?.data.stale).toEqual(
+ OUTPUTS.filter(file => !file.endsWith('.css.d.ts')).map(file => ({
+ path: `../themes/${file}`,
+ reason: 'missing',
+ })),
+ );
for (const output of OUTPUTS) {
expect(fs.existsSync(path.join(dir, 'themes', output))).toBe(false);
}
});
+ it('ends a stale family report for outputs outside cwd with a remedy that works', async () => {
+ const dir = makeDir();
+ const files = writeFamily(dir).map(file => path.join(dir, file));
+ const app = path.join(dir, 'app');
+ fs.mkdirSync(app);
+ const family = ['--family', ...files, '--family-key', FAMILY_KEY];
+
+ const stale = await runCli(['theme', 'build', ...family, '--check'], app);
+ expect(stale.code).toBe(1);
+ // The old remedy ran the build from cwd, which refuses these outputs.
+ expect(stale.stderr).not.toContain('Rebuild with:');
+
+ const lines = stale.stderr.split('\n').map(line => line.trim());
+ const runDir = lines.find(line => line.startsWith('cd '))?.slice(3);
+ expect(runDir).toBe(fs.realpathSync(path.join(dir, 'themes')));
+ const stem = `${getCliInvocation(runDir)} theme build `;
+ const [buildArgs, checkArgs] = lines
+ .filter(line => line.startsWith(stem))
+ .map(line => line.slice(stem.length).split(' '));
+ expect(checkArgs).toEqual([...buildArgs, '--check']);
+
+ // Following the remedy builds, and the check from there passes.
+ const built = await runCli(['theme', 'build', ...buildArgs], runDir);
+ expect(built.code).toBe(0);
+ for (const output of OUTPUTS) {
+ expect(fs.existsSync(path.join(dir, 'themes', output))).toBe(true);
+ }
+ const checked = await runCli(
+ ['--json', 'theme', 'build', ...checkArgs],
+ runDir,
+ );
+ expect(checked.code).toBe(0);
+ expect(JSON.parse(checked.stdout).data.upToDate).toBe(true);
+ });
+
it('fails without publishing a mixed trio when staging a write fails', async () => {
const dir = makeDir();
const files = writeFamily(dir);
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 3823063d49..f573bccdf0 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -27,8 +27,10 @@
* files; an internal callback lets the CLI make only the process status fail.
* Human progress is emitted through the shared `logger` (silent by default), so
* the CLI keeps its exact output while a programmatic caller stays quiet.
- * Every output, explicit or beside the theme file, stays inside `cwd`
- * (`ERR_PATH_TRAVERSAL` otherwise), in check mode too.
+ * Every output a build writes, explicit or beside the theme file, stays inside
+ * `cwd` (`ERR_PATH_TRAVERSAL` otherwise). Check mode writes nothing, so it
+ * compares outputs outside `cwd` read-only; only a relative `out` path that
+ * escapes `cwd` is refused there too.
*
* The installed `@astryxdesign/core` is an independently versioned optional
* peer, so it can be older than the CLI. A theme that uses only baseline
@@ -60,7 +62,10 @@ import {isBuiltin} from 'node:module';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {parse} from '@babel/parser';
import {createJiti} from 'jiti';
-import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
+import {
+ formatCliCommand,
+ getCliInvocation,
+} from '../../../foundation/env/package-manager.mjs';
import {
CLI_ROOT,
findCoreDir,
@@ -568,6 +573,86 @@ function confineOutputs(writes, root, remedy) {
for (const write of writes) confineOutput(write.dest, root, remedy);
}
+/** @param {string} dest absolute output path @param {string} root @returns {boolean} whether a build at `root` refuses to write `dest` */
+function refusedOutput(dest, root) {
+ try {
+ confineOutput(dest, root, '');
+ return false;
+ } catch (err) {
+ if (
+ err instanceof AstryxError &&
+ err.code === ERROR_CODES.ERR_PATH_TRAVERSAL
+ )
+ return true;
+ throw err;
+ }
+}
+
+/** @param {string[]} dirs absolute directories @returns {string | null} the deepest directory containing all of them, or null across roots */
+function commonDirectory(dirs) {
+ let common = dirs[0];
+ for (const dir of dirs.slice(1)) {
+ while (
+ path.relative(common, dir).startsWith('..') ||
+ path.isAbsolute(path.relative(common, dir))
+ ) {
+ const parent = path.dirname(common);
+ if (parent === common) return null;
+ common = parent;
+ }
+ }
+ return common;
+}
+
+/** @param {string} value @returns {string} `value` as one shell word */
+function shellWord(value) {
+ if (/^[A-Za-z0-9@%+=:,./_-]+$/.test(value)) return value;
+ return `'${value.replace(/'/g, `'\\''`)}'`;
+}
+
+/**
+ * How a stale check report ends when outputs sit outside the write root. A
+ * build there refuses them, and each output's `Source:` header records the
+ * directory its build ran from, so the build and the check both run from the
+ * nearest directory that contains every theme file and output.
+ * @param {Array<{dest: string}>} writes
+ * @param {string[]} sources absolute theme files the build reads
+ * @param {string} root the directory a build here keeps its writes inside
+ * @param {(relative: (file: string) => string) => string[]} args the arguments after `theme build`, given each path relative to the directory to run from
+ * @returns {string[] | null} report lines, or null when every output is inside `root`
+ */
+function outsideCheckRemedy(writes, sources, root, args) {
+ if (!writes.some(write => refusedOutput(write.dest, root))) return null;
+ const real = (/** @type {string} */ file) => realLocation(path.resolve(file));
+ const dir = commonDirectory([
+ ...sources.map(file => path.dirname(real(file))),
+ ...writes.map(write => path.dirname(real(write.dest))),
+ ]);
+ if (!dir) {
+ return [
+ 'These outputs are outside the working directory, so a build here refuses them. Build and check them from one directory that contains the theme files and the outputs.',
+ ];
+ }
+ const command = (/** @type {string[]} */ extra) =>
+ formatCliCommand(
+ [
+ 'theme',
+ 'build',
+ ...args(file => path.relative(dir, real(file))),
+ ...extra,
+ ]
+ .map(shellWord)
+ .join(' '),
+ dir,
+ );
+ return [
+ 'These outputs are outside the working directory, so a build here refuses them, and each output records the directory it was built from. Build and check them from a directory that contains them:',
+ ` cd ${shellWord(dir)}`,
+ ` ${command([])}`,
+ ` ${command(['--check'])}`,
+ ];
+}
+
/** @param {Array<{dest: string, content: string}>} writes */
function writeBuildOutputs(writes) {
if (writes.length === 0) return;
@@ -2859,9 +2944,13 @@ async function themeBuildInternal(
const writeRoot = options.__writeRoot ?? cwd;
let outPath;
if (options.out) {
- // Relative or absolute, the explicit output stays inside the write root.
outPath = path.resolve(cwd, options.out);
- confineOutput(outPath, writeRoot, OUT_REMEDY, options.out);
+ // A build keeps the explicit output inside the write root, relative or
+ // absolute. Check mode writes nothing, so it refuses only a relative path
+ // that escapes cwd.
+ if (!options.check || !path.isAbsolute(options.out)) {
+ confineOutput(outPath, writeRoot, OUT_REMEDY, options.out);
+ }
} else {
outPath = path.join(path.dirname(filePath), `${baseName}.css`);
}
@@ -2957,10 +3046,12 @@ async function themeBuildInternal(
writes.push({dest: variantDtsPath, content: variantContent});
}
- // Every output stays inside cwd, including the defaults beside the theme
- // file. Check mode refuses the same paths, so it never passes outputs that a
- // build would refuse to write.
- confineOutputs(writes, writeRoot, options.out ? OUT_REMEDY : SOURCE_REMEDY);
+ // Every output a build writes stays inside cwd, including the defaults
+ // beside the theme file. Check mode writes nothing, so it compares outputs
+ // outside cwd read-only.
+ if (!options.check) {
+ confineOutputs(writes, writeRoot, options.out ? OUT_REMEDY : SOURCE_REMEDY);
+ }
// Check mode: compare generated content against what's on disk instead of
// writing. A file is "stale" if it's missing or its content differs once the
@@ -2980,7 +3071,10 @@ async function themeBuildInternal(
` ${s.reason === 'missing' ? 'missing' : 'stale'}: ${s.path}`,
);
}
- logger.error(`\n Rebuild with: ${buildCommand}`);
+ // prettier-ignore
+ const remedy = outsideCheckRemedy(writes, [filePath], writeRoot, relative => [relative(filePath), ...(options.out ? ['--out', relative(outPath)] : []), ...(options.iconsSpecifier ? ['--icons-specifier', options.iconsSpecifier] : [])]);
+ if (remedy) logger.error(`\n ${remedy.join('\n ')}`);
+ else logger.error(`\n Rebuild with: ${buildCommand}`);
}
return {
type: 'theme.build.check',
@@ -3506,8 +3600,8 @@ export async function themeBuildFamily(
js: path.relative(cwd, jsPath),
dts: path.relative(cwd, dtsPath),
};
- // The family's outputs stay inside cwd too, in check mode as well.
- confineOutputs(writes, cwd, FAMILY_REMEDY);
+ // A family build's outputs stay inside cwd too; check mode only reads them.
+ if (!options.check) confineOutputs(writes, cwd, FAMILY_REMEDY);
if (options.check) {
const stale = staleBuildOutputs(writes, cwd);
const upToDate = stale.length === 0;
@@ -3524,7 +3618,10 @@ export async function themeBuildFamily(
` ${entry.reason === 'missing' ? 'missing' : 'stale'}: ${entry.path}`,
);
}
- logger.error(`\n Rebuild with: ${buildCommand}`);
+ // prettier-ignore
+ const remedy = outsideCheckRemedy(writes, members.map(member => member.filePath), cwd, relative => ['--family', ...members.map(member => relative(member.filePath)), '--family-key', baseName, ...(options.iconsSpecifier ? ['--icons-specifier', options.iconsSpecifier] : [])]);
+ if (remedy) logger.error(`\n ${remedy.join('\n ')}`);
+ else logger.error(`\n Rebuild with: ${buildCommand}`);
}
return {
type: 'theme.build.check',
diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjs
index efe5c39884..273bbd6ae1 100644
--- a/packages/cli/api/theme/themeBuild.doc.mjs
+++ b/packages/cli/api/theme/themeBuild.doc.mjs
@@ -58,13 +58,13 @@ export const doc = {
name: 'options.out',
type: 'string',
description:
- 'Override the output CSS path, relative or absolute; it must resolve inside cwd. The .js, .d.ts and any .variants.d.ts are written in the same directory, named after the theme (<name>.js), not after the CSS file.',
+ 'Override the output CSS path, relative or absolute; a build refuses a path outside cwd, and check mode refuses only a relative path that escapes cwd. The .js, .d.ts and any .variants.d.ts are written in the same directory, named after the theme (<name>.js), not after the CSS file.',
},
{
name: 'options.check',
type: 'boolean',
description:
- 'Compile in memory and compare each output against what is on disk instead of writing: the CI drift guard.',
+ 'Compile in memory and compare each output against what is on disk instead of writing: the CI drift guard. Because it writes nothing, it also compares outputs outside cwd; when those are stale, the report names the directory that contains them and the build and check commands to run from there, since a build refuses them and each output records the directory it was built from.',
default: 'false',
},
{
@@ -77,7 +77,7 @@ export const doc = {
name: 'ctx.cwd',
type: 'string',
description:
- 'Directory the theme file, a relative out path, and the returned output paths resolve against. Every output is written inside it, including the default outputs beside the theme file.',
+ 'Directory the theme file, a relative out path, and the returned output paths resolve against. Every output a build writes is inside it, including the default outputs beside the theme file.',
default: 'process.cwd()',
},
],
@@ -105,7 +105,7 @@ export const doc = {
},
{
code: 'ERR_PATH_TRAVERSAL',
- when: 'the theme name contains a path separator or traversal marker, or an output resolves outside cwd (including through a symlink): an `out` path, relative or absolute, or the default outputs beside a theme file outside cwd (also rejected in check mode)',
+ when: 'the theme name contains a path separator or traversal marker, or a written output resolves outside cwd (including through a symlink): an `out` path, relative or absolute, or the default outputs beside a theme file outside cwd. Check mode writes nothing, so it refuses only a relative `out` path that escapes cwd',
},
{
code: 'ERR_CORE_NOT_FOUND',
diff --git a/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs b/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs
index 14181c1b45..24d7794bcd 100644
--- a/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.path-safety.test.mjs
@@ -9,9 +9,12 @@
* - Multi-file write is atomic: if one file fails, none are left behind.
* - An `--out` escape, or an output directory that cannot be created, fails
* with a registered error code.
- * - Every output stays inside the working directory: an absolute `--out`
- * path or a theme file outside it fails before anything is written, while
- * absolute paths inside it build, also through a symlinked spelling.
+ * - Every output a build writes stays inside the working directory: an
+ * absolute `--out` path or a theme file outside it fails before anything
+ * is written, while absolute paths inside it build, also through a
+ * symlinked spelling. `--check` writes nothing, so it compares those
+ * outside outputs read-only, and a stale report for them ends with a
+ * remedy that works: the directory to build and check from.
*
* Runs the CLI in-process (shared runCli harness) against a tiny synthetic theme file.
*/
@@ -25,6 +28,7 @@ import {runCli} from '../../../test-utils/run-cli.mjs';
import {themeBuild} from '../../../api/theme/build/build.mjs';
import {AstryxError} from '../../../api/error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
+import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
function writeTheme(dir, name) {
fs.mkdirSync(dir, {recursive: true});
@@ -62,7 +66,9 @@ describe('theme build path safety', () => {
);
expect(result.code).not.toBe(0);
- expect(result.stderr + result.stdout).toMatch(/path separator|invalid theme name/i);
+ expect(result.stderr + result.stdout).toMatch(
+ /path separator|invalid theme name/i,
+ );
// The traversal target must not exist.
expect(fs.existsSync(path.join(tmpDir, 'escaped.js'))).toBe(false);
@@ -95,7 +101,10 @@ describe('theme build path safety', () => {
const themeFile = writeTheme(themesDir, '../leak');
- await runCli(['theme', 'build', path.relative(project, themeFile)], project);
+ await runCli(
+ ['theme', 'build', path.relative(project, themeFile)],
+ project,
+ );
// Neither the CSS nor any sibling JS should have been written.
const entries = fs.readdirSync(themesDir).sort();
@@ -117,41 +126,88 @@ describe('theme build output-path failures carry registered codes', () => {
return {result, envelope: JSON.parse(result.stdout)};
}
- it('reports an --out path outside the project as ERR_PATH_TRAVERSAL', async () => {
+ it('reports a relative --out path outside the project as ERR_PATH_TRAVERSAL, with --check too', async () => {
const project = path.join(tmpDir, 'project');
const themeFile = writeTheme(path.join(project, 'themes'), 'ocean');
+ for (const extra of [[], ['--check']]) {
+ const {result, envelope} = await buildJson(
+ [
+ path.relative(project, themeFile),
+ '--out',
+ '../escaped.css',
+ ...extra,
+ ],
+ project,
+ );
+
+ expect(result.code).toBe(1);
+ expect(envelope.code).toBe(ERROR_CODES.ERR_PATH_TRAVERSAL);
+ expect(registered.has(envelope.code)).toBe(true);
+ }
+ expect(fs.existsSync(path.join(tmpDir, 'escaped.css'))).toBe(false);
+ });
+
+ it('reports an absolute --out path outside the project as ERR_PATH_TRAVERSAL', async () => {
+ const project = path.join(tmpDir, 'project');
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(outside, {recursive: true});
+ const themeFile = writeTheme(path.join(project, 'themes'), 'ocean');
+ const out = path.join(outside, 'ocean.css');
+
const {result, envelope} = await buildJson(
- [path.relative(project, themeFile), '--out', '../escaped.css'],
+ [path.relative(project, themeFile), '--out', out],
project,
);
expect(result.code).toBe(1);
expect(envelope.code).toBe(ERROR_CODES.ERR_PATH_TRAVERSAL);
- expect(registered.has(envelope.code)).toBe(true);
- expect(fs.existsSync(path.join(tmpDir, 'escaped.css'))).toBe(false);
+ expect(fs.readdirSync(outside)).toEqual([]);
});
- it('reports an absolute --out path outside the project as ERR_PATH_TRAVERSAL, with --check too', async () => {
+ it('checks an absolute --out path outside the project read-only', async () => {
const project = path.join(tmpDir, 'project');
const outside = path.join(tmpDir, 'outside');
fs.mkdirSync(outside, {recursive: true});
- const themeFile = writeTheme(path.join(project, 'themes'), 'ocean');
+ const themeFile = path.relative(
+ project,
+ writeTheme(path.join(project, 'themes'), 'ocean'),
+ );
const out = path.join(outside, 'ocean.css');
- for (const extra of [[], ['--check']]) {
- const {result, envelope} = await buildJson(
- [path.relative(project, themeFile), '--out', out, ...extra],
- project,
- );
+ const missing = await buildJson(
+ [themeFile, '--out', out, '--check'],
+ project,
+ );
+ expect(missing.result.code).toBe(1);
+ expect(missing.envelope.type).toBe('theme.build.check');
+ expect(missing.envelope.data.upToDate).toBe(false);
+ expect(fs.readdirSync(outside)).toEqual([]);
- expect(result.code).toBe(1);
- expect(envelope.code).toBe(ERROR_CODES.ERR_PATH_TRAVERSAL);
+ // Outputs built inside the project compare equal once copied outside:
+ // only the volatile Command line, which --check ignores, names --out.
+ const dist = path.join(project, 'dist');
+ const built = await buildJson(
+ [themeFile, '--out', path.join(dist, 'ocean.css')],
+ project,
+ );
+ expect(built.result.code).toBe(0);
+ for (const file of fs.readdirSync(dist)) {
+ fs.copyFileSync(path.join(dist, file), path.join(outside, file));
}
- expect(fs.readdirSync(outside)).toEqual([]);
+ const copied = fs.readdirSync(outside).sort();
+
+ const current = await buildJson(
+ [themeFile, '--out', out, '--check'],
+ project,
+ );
+ expect(current.result.code).toBe(0);
+ expect(current.envelope.type).toBe('theme.build.check');
+ expect(current.envelope.data.upToDate).toBe(true);
+ expect(fs.readdirSync(outside).sort()).toEqual(copied);
});
- it('reports a theme file outside the project as ERR_PATH_TRAVERSAL, because its outputs go beside it', async () => {
+ it('reports a theme file outside the project as ERR_PATH_TRAVERSAL, because its outputs go beside it; --check only compares them', async () => {
const project = path.join(tmpDir, 'project');
fs.mkdirSync(project, {recursive: true});
const shared = path.join(tmpDir, 'shared');
@@ -162,10 +218,82 @@ describe('theme build output-path failures carry registered codes', () => {
expect(result.code).toBe(1);
expect(envelope.code).toBe(ERROR_CODES.ERR_PATH_TRAVERSAL);
+
+ const checked = await buildJson([file, '--check'], project);
+ expect(checked.result.code).toBe(1);
+ expect(checked.envelope.type).toBe('theme.build.check');
+ expect(checked.envelope.data.upToDate).toBe(false);
}
expect(fs.readdirSync(shared)).toEqual(['theme.mjs']);
});
+ /**
+ * Read the remedy that ends a stale report for outputs outside cwd: the
+ * directory to run from, then the build and check arguments after `theme
+ * build`. Each command starts with the install-aware invocation for it.
+ * @param {string} stderr
+ */
+ function readRemedy(stderr) {
+ const lines = stderr.split('\n').map(line => line.trim());
+ const cd = lines.find(line => line.startsWith('cd '));
+ expect(cd).toBeDefined();
+ const dir = /** @type {string} */ (cd).slice('cd '.length);
+ const stem = `${getCliInvocation(dir)} theme build `;
+ const commands = lines.filter(line => line.startsWith(stem));
+ expect(commands).toHaveLength(2);
+ const [build, check] = commands.map(line =>
+ line.slice(stem.length).split(' '),
+ );
+ expect(check).toEqual([...build, '--check']);
+ return {dir, build, check};
+ }
+
+ it('ends a stale report for outputs outside cwd with a remedy that works, and keeps the report for outputs inside it', async () => {
+ const project = path.join(tmpDir, 'project');
+ const inside = path.relative(
+ project,
+ writeTheme(path.join(project, 'themes'), 'ocean'),
+ );
+ const shared = writeTheme(path.join(tmpDir, 'shared'), 'ocean');
+ const outside = path.join(tmpDir, 'outside');
+
+ for (const args of [
+ [path.relative(project, shared)],
+ [inside, '--out', path.join(outside, 'ocean.css')],
+ ]) {
+ const stale = await runCli(
+ ['theme', 'build', ...args, '--check'],
+ project,
+ );
+ expect(stale.code).toBe(1);
+ // The old remedy ran the build from cwd, which refuses these outputs.
+ expect(stale.stderr).not.toContain('Rebuild with:');
+ expect(stale.stderr).not.toContain(`theme build ${args.join(' ')}`);
+
+ // Following the remedy builds, and the check from there passes.
+ const remedy = readRemedy(stale.stderr);
+ const built = await runCli(
+ ['theme', 'build', ...remedy.build],
+ remedy.dir,
+ );
+ expect(built.code).toBe(0);
+ const checked = await runCli(
+ ['--json', 'theme', 'build', ...remedy.check],
+ remedy.dir,
+ );
+ expect(checked.code).toBe(0);
+ expect(JSON.parse(checked.stdout).data.upToDate).toBe(true);
+ }
+
+ // Outputs inside cwd keep the plain rebuild line.
+ const local = await runCli(['theme', 'build', inside, '--check'], project);
+ expect(local.code).toBe(1);
+ expect(local.stderr).toContain(
+ `Rebuild with: astryx theme build ${inside}`,
+ );
+ expect(local.stderr).not.toMatch(/^\s*cd /m);
+ });
+
it('builds absolute paths inside the project, also when they reach it through a symlink', async () => {
const project = path.join(tmpDir, 'project');
const themeFile = writeTheme(path.join(project, 'themes'), 'ocean');
@@ -243,7 +371,7 @@ describe('theme build output-path failures carry registered codes', () => {
});
});
- it('themeBuild() rejects an output outside cwd: an absolute out path, or the default beside a theme file outside cwd', async () => {
+ it('themeBuild() rejects an output outside cwd, an absolute out path or the default beside a theme file outside cwd, and checks it read-only', async () => {
const project = path.join(tmpDir, 'project');
const inside = writeTheme(path.join(project, 'themes'), 'ocean');
const shared = path.join(tmpDir, 'shared');
@@ -257,6 +385,12 @@ describe('theme build output-path failures carry registered codes', () => {
await expect(
themeBuild(file, options, {cwd: project}),
).rejects.toMatchObject({code: ERROR_CODES.ERR_PATH_TRAVERSAL});
+ await expect(
+ themeBuild(file, {...options, check: true}, {cwd: project}),
+ ).resolves.toMatchObject({
+ type: 'theme.build.check',
+ data: {upToDate: false},
+ });
}
expect(fs.existsSync(outDir)).toBe(false);
expect(fs.readdirSync(shared)).toEqual(['theme.mjs']);
diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjs
index a601a15989..303ba86c5b 100644
--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs
+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs
@@ -30,7 +30,7 @@ export const doc = {
{
flag: '--family',
description:
- 'Build the selected extension family into one keyed CSS, JS, and declaration set, written beside the family root theme file, which must be inside the working directory (ERR_PATH_TRAVERSAL). Requires --family-key; refused with --out or --watch (ERR_THEME_INVALID)',
+ 'Build the selected extension family into one keyed CSS, JS, and declaration set, written beside the family root theme file, which must be inside the working directory to build (ERR_PATH_TRAVERSAL); --check only reads, so it compares outputs anywhere. Requires --family-key; refused with --out or --watch (ERR_THEME_INVALID)',
},
{
flag: '--family-key <key>',
@@ -41,7 +41,7 @@ export const doc = {
flag: '-o, --out <path>',
param: 'options.out',
description:
- 'Output CSS file path, relative or absolute; the .js and .d.ts are written beside it (default: <theme name>.css next to the source). Every output must resolve inside the working directory, the defaults beside the source too (ERR_PATH_TRAVERSAL). Single theme only: refused with more than one file or with --family (ERR_THEME_INVALID)',
+ 'Output CSS file path, relative or absolute; the .js and .d.ts are written beside it (default: <theme name>.css next to the source). A build writes only inside the working directory, the defaults beside the source too (ERR_PATH_TRAVERSAL); --check writes nothing, so it compares outputs anywhere and refuses only a relative path that escapes the working directory. Single theme only: refused with more than one file or with --family (ERR_THEME_INVALID)',
},
{
flag: '--icons-specifier <specifier>',