Skip to content

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

TypeScript

fix(cli): use semver comparison in upgrade gate, update-check, --list dedup (#2460)

Joeyb7158c205b4b
diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjs
index 6e511daf98..01e0284789 100644
--- a/packages/cli/src/codemods/registry.mjs
+++ b/packages/cli/src/codemods/registry.mjs
@@ -19,24 +19,9 @@ const registry = new Map([
['0.0.15', () => import('./transforms/v0.0.15/index.mjs')],
]);
-/**
- * Compare two semver strings numerically.
- * Returns negative if a < b, positive if a > b, 0 if equal.
- *
- * @param {string} a
- * @param {string} b
- * @returns {number}
- */
-function semverCompare(a, b) {
- const pa = a.split('-')[0].split('.').map(Number);
- const pb = b.split('-')[0].split('.').map(Number);
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
- const na = pa[i] ?? 0;
- const nb = pb[i] ?? 0;
- if (na !== nb) return na - nb;
- }
- return 0;
-}
+// Re-export from the shared utility so registry callers and other consumers
+// (upgrade gate, update-check) all use the same comparator.
+import {semverCompare} from '../utils/semver.mjs';
/**
* All registered versions, sorted ascending.
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 964131870e..142b42e3a0 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -33,11 +33,11 @@ import {ensureJscodeshift} from '../codemods/ensure-jscodeshift.mjs';
import {
getTransformsBetween,
latestVersion,
- versions,
} from '../codemods/registry.mjs';
import {runCodemods} from '../codemods/runner.mjs';
import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';
import {detectPackageManager, getRunPrefix} from '../utils/package-manager.mjs';
+import {isValidSemver, semverGte} from '../utils/semver.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
/**
@@ -125,12 +125,13 @@ function getInstallCommand(force = false) {
* List all available codemods across all versions.
*/
async function listCodemods() {
- for (const version of versions) {
- const manifests = await getTransformsBetween('0.0.0', version);
- for (const {transforms} of manifests) {
- for (const {name, meta} of transforms) {
- p.log.info(` ${name} — ${meta.title} (${meta.pr})`);
- }
+ // Walk the full registry once. The previous implementation called
+ // getTransformsBetween('0.0.0', v) for every v in versions, so a codemod
+ // introduced at 0.0.2 was reprinted for every version >= 0.0.2.
+ const manifests = await getTransformsBetween('0.0.0', latestVersion);
+ for (const {transforms} of manifests) {
+ for (const {name, meta} of transforms) {
+ p.log.info(` ${name} — ${meta.title} (${meta.pr})`);
}
}
}
@@ -154,14 +155,35 @@ export function registerUpgrade(program) {
const json = program.opts().json || false;
if (!json) p.intro('XDS Upgrade');
+ // Validate --to / --from upfront so callers don't silently accept
+ // typos like `--to bogus` (which used to flow through getTransformsBetween
+ // and just emit "no codemods available").
+ if (options.to !== undefined && !isValidSemver(options.to)) {
+ const msg = `Invalid --to value: "${options.to}". Expected a semver string like 0.0.10.`;
+ if (json) return jsonError(msg);
+ p.log.error(msg);
+ p.outro('Aborted');
+ process.exitCode = 1;
+ return;
+ }
+ if (options.from !== undefined && !isValidSemver(options.from)) {
+ const msg = `Invalid --from value: "${options.from}". Expected a semver string like 0.0.5.`;
+ if (json) return jsonError(msg);
+ p.log.error(msg);
+ p.outro('Aborted');
+ process.exitCode = 1;
+ return;
+ }
if (options.list) {
const codemods = [];
- for (const version of versions) {
- const manifests = await getTransformsBetween('0.0.0', version);
- for (const {transforms} of manifests) {
- for (const {name, meta, optional} of transforms) {
- codemods.push({name, title: meta.title, version, pr: meta.pr, optional: !!optional});
- }
+ // Walk the registry once from 0.0.0 → latest. Earlier this looped
+ // over every version and re-walked getTransformsBetween('0.0.0', v),
+ // so each codemod was printed once per release that included it
+ // (31 unique × 9 ≈ 201 lines on the current registry).
+ const manifests = await getTransformsBetween('0.0.0', latestVersion);
+ for (const {version, transforms} of manifests) {
+ for (const {name, meta, optional} of transforms) {
+ codemods.push({name, title: meta.title, version, pr: meta.pr, optional: !!optional});
}
}
if (json) return jsonOut('upgrade.list', codemods.map(({name, title, version, optional}) => ({name, title, version, optional})));
@@ -201,7 +223,7 @@ export function registerUpgrade(program) {
p.log.info(`Target version: ${targetVersion}`);
}
- if (!options.force && currentVersion >= targetVersion) {
+ if (!options.force && semverGte(currentVersion, targetVersion)) {
if (!json) {
p.log.success('Already up to date — no codemods to run.');
p.log.info('Use --force to run codemods anyway, or --from <version> to specify the previous version.');
diff --git a/packages/cli/src/commands/upgrade.test.mjs b/packages/cli/src/commands/upgrade.test.mjs
new file mode 100644
index 0000000000..f0d9b864ee
--- /dev/null
+++ b/packages/cli/src/commands/upgrade.test.mjs
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {Command} from 'commander';
+import {registerUpgrade} from './upgrade.mjs';
+import {latestVersion} from '../codemods/registry.mjs';
+
+let tmpDir;
+let originalCwd;
+let logCalls;
+let stdoutCalls;
+let exitCode;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-upgrade-test-'));
+ originalCwd = process.cwd();
+ process.chdir(tmpDir);
+ logCalls = [];
+ stdoutCalls = [];
+ exitCode = undefined;
+ vi.spyOn(console, 'log').mockImplementation((...args) => {
+ logCalls.push(args.join(' '));
+ });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ // @clack/prompts writes directly to process.stdout — capture that too.
+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
+ stdoutCalls.push(typeof chunk === 'string' ? chunk : chunk.toString());
+ return true;
+ });
+ // jsonError() calls process.exit(1) directly. Trap it so tests can assert.
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
+ exitCode = code;
+ throw new Error(`__exit ${code}`);
+ });
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+});
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ // Mirror the global --json flag from src/index.mjs so program.opts().json
+ // resolves the same way in tests.
+ program.option('--json', 'Output as typed JSON');
+ registerUpgrade(program);
+ return program;
+}
+
+function writePkg(deps) {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'fixture', dependencies: deps}, null, 2),
+ );
+}
+
+/** Run a command and capture the parsed JSON response (last printed JSON line). */
+async function runJson(args) {
+ const program = createProgram();
+ try {
+ await program.parseAsync(['node', 'xds', ...args]);
+ } catch (err) {
+ if (!String(err?.message || '').startsWith('__exit')) throw err;
+ }
+ // Find the most recent stringified JSON envelope in console.log output.
+ for (let i = logCalls.length - 1; i >= 0; i--) {
+ const line = logCalls[i];
+ if (line.startsWith('{')) {
+ try {
+ return JSON.parse(line);
+ } catch {
+ // not JSON, keep looking
+ }
+ }
+ }
+ return null;
+}
+
+describe('upgrade gate (semver comparison)', () => {
+ it('does NOT block an upgrade from 0.0.9 to 0.0.10 (regression)', async () => {
+ // The original bug: string compare said '0.0.9' >= '0.0.10', so the
+ // gate told users "Already up to date" without --force.
+ writePkg({'@xds/core': '^0.0.9'});
+
+ const result = await runJson(['--json', 'upgrade', '--to', '0.0.10', '--codemod-only']);
+ // Either a real run or "no codemods available" — but never the
+ // up-to-date short-circuit (which has no `type` field).
+ expect(result).not.toBeNull();
+ // The receipt or "no codemods" path should not look like the
+ // up-to-date short-circuit (which would return without printing JSON).
+ expect(result.type === 'upgrade.run' || result.error || logCalls.some(l => l.includes('No codemods'))).toBeTruthy();
+ });
+
+ it('blocks when current >= target by semver (e.g. 0.0.10 → 0.0.9)', async () => {
+ writePkg({'@xds/core': '^0.0.10'});
+ const program = createProgram();
+ await program.parseAsync(['node', 'xds', 'upgrade', '--to', '0.0.9']);
+ const output = stdoutCalls.join('') + logCalls.join('\n');
+ expect(output).toMatch(/up to date|Already/i);
+ });
+});
+
+describe('upgrade --to validation', () => {
+ it('rejects bogus --to values with a structured error', async () => {
+ writePkg({'@xds/core': '^0.0.5'});
+ const result = await runJson(['--json', 'upgrade', '--to', 'bogus']);
+ expect(result).not.toBeNull();
+ expect(result.error).toMatch(/Invalid --to/);
+ expect(exitCode).toBe(1);
+ });
+
+ it('rejects bogus --from values', async () => {
+ writePkg({'@xds/core': '^0.0.5'});
+ const result = await runJson(['--json', 'upgrade', '--from', 'not-a-version', '--to', '0.0.5']);
+ expect(result).not.toBeNull();
+ expect(result.error).toMatch(/Invalid --from/);
+ expect(exitCode).toBe(1);
+ });
+
+ it('accepts a valid semver --to', async () => {
+ writePkg({'@xds/core': '^0.0.5'});
+ // Don't actually run codemods — codemod-only + a target with no
+ // matching transforms is enough to confirm validation passed.
+ const result = await runJson(['--json', 'upgrade', '--to', latestVersion, '--codemod-only']);
+ // No "Invalid --to" error means validation passed.
+ expect(result?.error || '').not.toMatch(/Invalid --to/);
+ });
+});
+
+describe('upgrade --list dedup', () => {
+ it('lists each codemod exactly once', async () => {
+ const result = await runJson(['--json', 'upgrade', '--list']);
+ expect(result).not.toBeNull();
+ expect(result.type).toBe('upgrade.list');
+ const names = result.data.map((c) => c.name);
+ const unique = new Set(names);
+ // The bug: 31 unique codemods printed 9× → 201 entries.
+ expect(names.length).toBe(unique.size);
+ });
+});
diff --git a/packages/cli/src/utils/semver.mjs b/packages/cli/src/utils/semver.mjs
new file mode 100644
index 0000000000..a315f83414
--- /dev/null
+++ b/packages/cli/src/utils/semver.mjs
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Minimal semver utilities for the CLI.
+ *
+ * We deliberately avoid pulling in `semver` from npm — XDS releases follow a
+ * strict `MAJOR.MINOR.PATCH[-prerelease]` shape and the CLI runs in consumer
+ * sandboxes where a smaller dependency surface is preferred.
+ */
+
+const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+/**
+ * True if `value` looks like a valid semver string (MAJOR.MINOR.PATCH with
+ * optional prerelease/build metadata).
+ *
+ * @param {unknown} value
+ * @returns {boolean}
+ */
+export function isValidSemver(value) {
+ return typeof value === 'string' && SEMVER_RE.test(value);
+}
+
+/**
+ * Compare two semver strings numerically.
+ *
+ * Returns a negative number if `a < b`, positive if `a > b`, 0 if equal.
+ * Prerelease tags are stripped — `0.0.5-beta.1` compares equal to `0.0.5`.
+ * That's adequate for the upgrade gate, which only cares about ordering of
+ * released versions.
+ *
+ * @param {string} a
+ * @param {string} b
+ * @returns {number}
+ */
+export function semverCompare(a, b) {
+ const pa = String(a).split('-')[0].split('.').map(Number);
+ const pb = String(b).split('-')[0].split('.').map(Number);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const na = pa[i] ?? 0;
+ const nb = pb[i] ?? 0;
+ if (Number.isNaN(na) || Number.isNaN(nb)) {
+ // Fall back to lexicographic compare on garbage input rather than
+ // returning NaN, which would silently break sort/filter callers.
+ return String(a).localeCompare(String(b));
+ }
+ if (na !== nb) return na - nb;
+ }
+ return 0;
+}
+
+/**
+ * `true` if `a` is greater than or equal to `b` in semver order.
+ *
+ * @param {string} a
+ * @param {string} b
+ * @returns {boolean}
+ */
+export function semverGte(a, b) {
+ return semverCompare(a, b) >= 0;
+}
+
+/**
+ * `true` if `a` is strictly greater than `b` in semver order.
+ *
+ * @param {string} a
+ * @param {string} b
+ * @returns {boolean}
+ */
+export function semverGt(a, b) {
+ return semverCompare(a, b) > 0;
+}
diff --git a/packages/cli/src/utils/semver.test.mjs b/packages/cli/src/utils/semver.test.mjs
new file mode 100644
index 0000000000..fa7f00a263
--- /dev/null
+++ b/packages/cli/src/utils/semver.test.mjs
@@ -0,0 +1,67 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {isValidSemver, semverCompare, semverGt, semverGte} from './semver.mjs';
+
+describe('semverCompare', () => {
+ it('orders patch versions numerically (not lexicographically)', () => {
+ // The bug fix that motivated this util: '0.0.10' < '0.0.9' under
+ // string comparison, but '0.0.10' > '0.0.9' under semver.
+ expect(semverCompare('0.0.10', '0.0.9')).toBeGreaterThan(0);
+ expect(semverCompare('0.0.9', '0.0.10')).toBeLessThan(0);
+ expect(semverCompare('0.0.20', '0.0.5')).toBeGreaterThan(0);
+ });
+
+ it('returns 0 for equal versions', () => {
+ expect(semverCompare('1.2.3', '1.2.3')).toBe(0);
+ });
+
+ it('orders by major, then minor, then patch', () => {
+ expect(semverCompare('2.0.0', '1.99.99')).toBeGreaterThan(0);
+ expect(semverCompare('1.2.0', '1.1.99')).toBeGreaterThan(0);
+ });
+
+ it('strips prerelease tags before comparing', () => {
+ expect(semverCompare('0.0.5-beta.1', '0.0.5')).toBe(0);
+ });
+
+ it('treats missing components as zero', () => {
+ expect(semverCompare('1.0', '1.0.0')).toBe(0);
+ });
+});
+
+describe('semverGt / semverGte', () => {
+ it('semverGte is true for equal versions', () => {
+ expect(semverGte('0.0.5', '0.0.5')).toBe(true);
+ expect(semverGt('0.0.5', '0.0.5')).toBe(false);
+ });
+
+ it('semverGte handles double-digit patches correctly', () => {
+ // The original upgrade-gate bug: string compare said 0.0.9 >= 0.0.10.
+ expect(semverGte('0.0.9', '0.0.10')).toBe(false);
+ expect(semverGte('0.0.10', '0.0.9')).toBe(true);
+ });
+});
+
+describe('isValidSemver', () => {
+ it('accepts MAJOR.MINOR.PATCH', () => {
+ expect(isValidSemver('0.0.5')).toBe(true);
+ expect(isValidSemver('1.2.3')).toBe(true);
+ expect(isValidSemver('10.20.30')).toBe(true);
+ });
+
+ it('accepts prerelease and build metadata', () => {
+ expect(isValidSemver('1.0.0-beta.1')).toBe(true);
+ expect(isValidSemver('1.0.0+build.5')).toBe(true);
+ });
+
+ it('rejects bogus values', () => {
+ expect(isValidSemver('bogus')).toBe(false);
+ expect(isValidSemver('1.0')).toBe(false);
+ expect(isValidSemver('v1.0.0')).toBe(false);
+ expect(isValidSemver('')).toBe(false);
+ expect(isValidSemver(null)).toBe(false);
+ expect(isValidSemver(undefined)).toBe(false);
+ expect(isValidSemver(123)).toBe(false);
+ });
+});
diff --git a/packages/cli/src/utils/update-check.mjs b/packages/cli/src/utils/update-check.mjs
index 6c4c062cb3..3cadc78f61 100644
--- a/packages/cli/src/utils/update-check.mjs
+++ b/packages/cli/src/utils/update-check.mjs
@@ -14,6 +14,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import {semverGt} from './semver.mjs';
/**
* Read the latest available version from local signals.
@@ -93,8 +94,9 @@ export function checkForUpdate(cwd = process.cwd()) {
const installed = getInstalledVersion(cwd);
if (!installed) return null;
- // Simple string comparison works for our semver scheme (0.0.x)
- if (latest > installed) {
+ // Use semver-aware comparison so '0.0.20' is correctly treated as greater
+ // than '0.0.5' (lexicographic compare gets that backwards).
+ if (semverGt(latest, installed)) {
return `FYI: A newer version of @xds/core (${latest}) is available. You can upgrade with: xds upgrade --apply --to ${latest}`;
}
diff --git a/packages/cli/src/utils/update-check.test.mjs b/packages/cli/src/utils/update-check.test.mjs
index e8844643ae..a7a3d0a70f 100644
--- a/packages/cli/src/utils/update-check.test.mjs
+++ b/packages/cli/src/utils/update-check.test.mjs
@@ -170,4 +170,30 @@ describe('checkForUpdate', () => {
expect(hint).toContain('0.0.9');
expect(hint).toContain('FYI');
});
+
+ it('uses semver (not lexicographic) comparison for double-digit patches', () => {
+ // Regression: with string compare, '0.0.20' > '0.0.5' is false because
+ // '2' < '5' lexicographically. Users on 0.0.5 would never be told that
+ // 0.0.20 is available.
+ process.env.XDS_LATEST_VERSION = '0.0.20';
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({dependencies: {'@xds/core': '^0.0.5'}}),
+ );
+
+ const hint = checkForUpdate(tmpDir);
+ expect(hint).toContain('0.0.20');
+ });
+
+ it('does not suggest an upgrade when latest < installed (semver)', () => {
+ // The mirror-image bug: '0.0.9' > '0.0.10' is true under string compare,
+ // so a stale env hint of 0.0.9 would falsely claim it's "newer" than 0.0.10.
+ process.env.XDS_LATEST_VERSION = '0.0.9';
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({dependencies: {'@xds/core': '^0.0.10'}}),
+ );
+
+ expect(checkForUpdate(tmpDir)).toBeNull();
+ });
});