An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): use detected package manager everywhere instead of hardcoded npx (#972) (#975)
Cindy Zhang9446b1595294
diff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjsindex 8d45f4b537..a55d7b7619 100644--- a/packages/cli/src/codemods/runner.mjs+++ b/packages/cli/src/codemods/runner.mjs@@ -9,6 +9,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import * as p from '@clack/prompts';+import {getRunPrefix} from '../utils/package-manager.mjs';// Known corruption patterns that indicate a broken transform.// Each entry: [regex, human-readable description]@@ -59,10 +60,11 @@ async function formatChangedFiles(files) {const {execSync} = await import('node:child_process');const fileArgs = files.map((f) => `"${f}"`).join(' ');+ const prefix = getRunPrefix();const formatters = [- {name: 'prettier', cmd: `npx prettier --write ${fileArgs}`},- {name: 'biome', cmd: `npx biome format --write ${fileArgs}`},+ {name: 'prettier', cmd: `${prefix} prettier --write ${fileArgs}`},+ {name: 'biome', cmd: `${prefix} biome format --write ${fileArgs}`},];for (const {name, cmd} of formatters) {diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjsindex 96c079bf31..114e4119b5 100644--- a/packages/cli/src/commands/agent-docs.mjs+++ b/packages/cli/src/commands/agent-docs.mjs@@ -90,7 +90,7 @@ export function resolveAgentPaths(targetDir, agent) {* Format C (one-liner per command) chosen after testing three formats* against Claude Opus for AI agent usability (scored 5/5).*/-export function generateCompressedIndex(version, {coreDir, zh = false, lang, runPrefix = 'npx'} = {}) {+export function generateCompressedIndex(version, {coreDir, zh = false, lang, runPrefix = getRunPrefix()} = {}) {const run = `${runPrefix} xds`;const lines = [XDS_MARKER_START];diff --git a/packages/cli/src/commands/agent-docs.test.mjs b/packages/cli/src/commands/agent-docs.test.mjsindex 1ce6b2589d..a5b49c131f 100644--- a/packages/cli/src/commands/agent-docs.test.mjs+++ b/packages/cli/src/commands/agent-docs.test.mjs@@ -36,14 +36,14 @@ describe('generateCompressedIndex', () => {it('does not include theme command references', () => {const result = generateCompressedIndex('1.0.0');- expect(result).not.toContain('npx xds theme');+ expect(result).not.toMatch(/\bxds theme\b/);});it('includes upgrade command and migration rule', () => {const result = generateCompressedIndex('1.0.0');- expect(result).toContain('npx xds upgrade');- expect(result).toContain('npx xds upgrade --apply');- expect(result).toContain('after @xds/core bump, always run npx xds upgrade --apply');+ expect(result).toContain('xds upgrade');+ expect(result).toContain('xds upgrade --apply');+ expect(result).toMatch(/always run .+ xds upgrade --apply/);});it('uses custom runPrefix when provided', () => {diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjsindex d81f868848..d0bdefb6bc 100644--- a/packages/cli/src/commands/build-theme.mjs+++ b/packages/cli/src/commands/build-theme.mjs@@ -14,6 +14,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {createRequire} from 'node:module';import {pathToFileURL, fileURLToPath} from 'node:url';+import {getRunPrefix} from '../utils/package-manager.mjs';// Import shared theme processing from core — ensures build and runtime// use the same logic for typography.scale expansion, prose, and component rules.@@ -577,7 +578,7 @@ function generateBuiltModule(themeDef, iconImportPath) {.join('\n');return `${iconImport}/**- * ${themeDef.name} theme — built by \`npx xds theme build\`+ * ${themeDef.name} theme — built by \`${getRunPrefix()} xds theme build\`* Import the CSS file alongside this module:** import { ${toIdentifier(themeDef.name)}Theme } from './${themeDef.name}';diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjsindex 88c08ccf72..89b2d7d6f7 100644--- a/packages/cli/src/commands/component/index.mjs+++ b/packages/cli/src/commands/component/index.mjs@@ -32,6 +32,7 @@ import {} from '../../lib/component-legacy.mjs';import {findClosestComponents} from '../../lib/string-utils.mjs';import {resolveTheme} from '../../lib/resolve-theme.mjs';+import {getRunPrefix} from '../../utils/package-manager.mjs';export function registerComponent(program) {program@@ -42,6 +43,7 @@ export function registerComponent(program) {.option('--props', 'Print only the props table').option('--source', 'Print component source code').action(async (name, options) => {+ const run = getRunPrefix();const coreDir = findCoreDir(process.cwd());const zh = program.opts().zh || false;const dense = program.opts().dense || false;@@ -134,7 +136,7 @@ export function registerComponent(program) {}}- console.log('Usage: npx xds component <name>');+ console.log(`Usage: ${run} xds component <name>`);console.log('');}return;@@ -193,7 +195,7 @@ export function registerComponent(program) {if (!readmePath) {console.error(`Error: Component "${name}" not found.`);- console.error('Run `npx xds component --list` to see available components.');+ console.error(`Run \`${run} xds component --list\` to see available components.`);process.exit(1);}}diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjsindex ec80a14801..aaf0ff737b 100644--- a/packages/cli/src/commands/docs.mjs+++ b/packages/cli/src/commands/docs.mjs@@ -14,6 +14,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {pathToFileURL} from 'node:url';import {CLI_ROOT} from '../utils/paths.mjs';+import {getRunPrefix} from '../utils/package-manager.mjs';const DOCS_DIR = path.join(CLI_ROOT, 'docs');@@ -185,6 +186,7 @@ export function registerDocs(program) {.command('docs [topic] [section]').description('Print XDS reference docs').action(async (topic, section) => {+ const run = getRunPrefix();const topics = discoverTopics();const lang = program.opts().lang || null;const zh = program.opts().zh || false;@@ -202,8 +204,8 @@ export function registerDocs(program) {console.log(` ${name}`);}}- console.log('\nUsage: npx xds docs <topic>');- console.log(' npx xds docs <topic> <section>\n');+ console.log(`\nUsage: ${run} xds docs <topic>`);+ console.log(` ${run} xds docs <topic> <section>\n`);return;}diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjsindex 7db7e1157a..51df7774b7 100644--- a/packages/cli/src/commands/gap-report.mjs+++ b/packages/cli/src/commands/gap-report.mjs@@ -16,6 +16,7 @@ import {loadGapReportConfig,GAP_CATEGORIES,} from '../utils/github.mjs';+import {getRunPrefix} from '../utils/package-manager.mjs';function isCancel(value) {if (p.isCancel(value)) {@@ -173,7 +174,7 @@ export function registerGapReport(program) {const config = loadGapReportConfig();if (!config.enabled) {console.log(- 'Gap reporting is disabled. Run `npx xds gap-report setup` to configure.',+ `Gap reporting is disabled. Run \`${getRunPrefix()} xds gap-report setup\` to configure.`,);return;}@@ -182,7 +183,7 @@ export function registerGapReport(program) {console.error('Error: GitHub CLI (gh) is not installed or not authenticated.\n' +'Install it from https://cli.github.com and run `gh auth login`.\n\n' +- 'Or run `npx xds gap-report setup` to configure a custom command.',+ `Or run \`${getRunPrefix()} xds gap-report setup\` to configure a custom command.`,);process.exit(1);}diff --git a/packages/cli/src/commands/init.mjs b/packages/cli/src/commands/init.mjsindex 2597f87563..2ab19e450e 100644--- a/packages/cli/src/commands/init.mjs+++ b/packages/cli/src/commands/init.mjs@@ -15,10 +15,12 @@ import * as p from '@clack/prompts';import * as path from 'node:path';import * as fs from 'node:fs';import {CLI_ROOT} from '../utils/paths.mjs';+import {getRunPrefix} from '../utils/package-manager.mjs';import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';import {listTemplates} from './template.mjs';const VALID_FEATURES = ['agents', 'theme', 'template'];+const run = getRunPrefix();function isCancel(value) {if (p.isCancel(value)) {@@ -45,7 +47,7 @@ function runAgents(targetDir, {interactive = true, agent, agentDocsPath} = {}) {console.log(`✓ AI agent docs installed → ${summary}`);}} catch {- const msg = 'Could not install agent docs. Try again with `npx xds init --features agents`.';+ const msg = `Could not install agent docs. Try again with \`${run} xds init --features agents\`.`;if (interactive) {p.log.warning(msg);} else {@@ -58,14 +60,14 @@ function runAgents(targetDir, {interactive = true, agent, agentDocsPath} = {}) {async function runTheme({interactive = true} = {}) {if (!interactive) {- console.log('✓ Theme scaffolding requires interactive mode. Run `npx xds theme` instead.');+ console.log(`✓ Theme scaffolding requires interactive mode. Run \`${run} xds theme\` instead.`);return;}p.note('Create a custom theme with your brand colors.\n' +- 'Run `npx xds theme` for the full theme wizard.\n' +- 'Run `npx xds theme --list` to see existing themes.',+ `Run \`${run} xds theme\` for the full theme wizard.\n` ++ `Run \`${run} xds theme --list\` to see existing themes.`,'Themes',);}@@ -78,7 +80,7 @@ async function runTemplate(targetDir, {interactive = true, templateName} = {}) {if (!interactive) {if (!templateName) {- console.log(`✓ Available templates: ${templates.join(', ')}. Use npx xds template <name> [path].`);+ console.log(`✓ Available templates: ${templates.join(', ')}. Use ${run} xds template <name> [path].`);return;}@@ -213,7 +215,7 @@ export function registerInit(program) {// Feature: swizzle awarenessp.note(- 'You can customize any component with:\n npx xds swizzle XDSButton\n npx xds swizzle --list',+ `You can customize any component with:\n ${run} xds swizzle XDSButton\n ${run} xds swizzle --list`,'Component Customization',);@@ -232,7 +234,7 @@ export function registerInit(program) {console.log(' 2. Optionally add a theme:');console.log(" import { defaultTheme } from '@xds/theme/default'");console.log(' <XDSTheme theme={defaultTheme}>...</XDSTheme>');- console.log(' 3. npx xds --help for all commands');+ console.log(` 3. ${run} xds --help for all commands`);console.log('');});}diff --git a/packages/cli/src/commands/theme.mjs b/packages/cli/src/commands/theme.mjsindex 2a6ab531f3..b67e0a05fa 100644--- a/packages/cli/src/commands/theme.mjs+++ b/packages/cli/src/commands/theme.mjs@@ -12,6 +12,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import * as p from '@clack/prompts';import {findCoreDir} from '../utils/paths.mjs';+import {getRunPrefix} from '../utils/package-manager.mjs';function isCancel(value) {if (p.isCancel(value)) {@@ -216,7 +217,7 @@ function generateThemeFile({name, exportName, colors, includeComponentOverrides,// Each component reads its overrides from theme.components.<name>.//// To discover what's themeable for a component, run:-// npx xds --detail compact component <Name>+// ${getRunPrefix()} xds --detail compact component <Name>// and look for the "Theme Overrides" section.// --- Button ---@@ -286,7 +287,7 @@ function generateThemeFile({name, exportName, colors, includeComponentOverrides,** ${modeComment}*- * Generated by \`npx xds theme\`.+ * Generated by \`${getRunPrefix()} xds theme\`.* Customize the values below, then import in your app.** Only override token groups you want to change — omitted groups@@ -451,7 +452,7 @@ export function registerTheme(program) {const themes = discoverThemes(coreDir);if (themes.length === 0) {- console.log('\nNo themes found. Run `npx xds theme` to create one.\n');+ console.log(`\nNo themes found. Run \`${getRunPrefix()} xds theme\` to create one.\n`);} else {console.log('\nExisting themes:\n');for (const theme of themes) {@@ -673,8 +674,8 @@ export function registerTheme(program) {'Omitted groups use the defineVars defaults automatically.\n' +(includeComponentOverrides? 'Uncomment sections in "Component Style Overrides" to customize components.\n'- : 'Run `npx xds theme` again with component overrides to customize components.\n') +- '\nRun `npx xds docs tokens` to see all available tokens.',+ : `Run \`${getRunPrefix()} xds theme\` again with component overrides to customize components.\n`) ++ `\nRun \`${getRunPrefix()} xds docs tokens\` to see all available tokens.`,'Next steps',);diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjsindex 778ab62e01..c7ff790ed6 100644--- a/packages/cli/src/commands/upgrade.mjs+++ b/packages/cli/src/commands/upgrade.mjs@@ -34,7 +34,7 @@ import {} from '../codemods/registry.mjs';import {runCodemods} from '../codemods/runner.mjs';import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';-import {detectPackageManager} from '../utils/package-manager.mjs';+import {detectPackageManager, getRunPrefix} from '../utils/package-manager.mjs';/*** Detect the installed @xds/core version from the consumer's package.json.@@ -257,7 +257,7 @@ export function registerUpgrade(program) {p.log.success(`Agent docs updated: ${written.join(', ')}`);} catch {p.log.warn(- 'Could not update agent docs. Run `npx xds agent-docs` to update manually.',+ `Could not update agent docs. Run \`${getRunPrefix()} xds agent-docs\` to update manually.`,);}}diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjsindex 913350c37c..b419965f81 100644--- a/packages/cli/src/index.mjs+++ b/packages/cli/src/index.mjs@@ -10,6 +10,7 @@ import {fileURLToPath} from 'node:url';import * as fs from 'node:fs';import * as path from 'node:path';import {checkForUpdate} from './utils/update-check.mjs';+import {getRunPrefix} from './utils/package-manager.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -87,22 +88,27 @@ for (const cmd of commands) {program.command('postinstall', {hidden: true}).action(() => {+ const run = getRunPrefix();+ const r = `${run} xds`;+ const pad = (s, len) => s + ' '.repeat(Math.max(0, len - s.length));+ const W = 49; // inner width of the box+ const line = (s) => ` │ ${pad(s, W)}│`;console.log(`- ╭───────────────────────────────────────────────────╮- │ │- │ XDS design system installed! │- │ │- │ Get started: │- │ npx xds init Interactive setup │- │ npx xds --help See all commands │- │ │- │ Or run directly: │- │ npx xds init Setup + AI agent docs │- │ npx xds component Browse component docs │- │ npx xds docs Design system reference │- │ npx xds swizzle Customize a component │- │ npx xds template Add a page template │- │ │- ╰───────────────────────────────────────────────────╯+ ╭${'─'.repeat(W + 2)}╮+${line('')}+${line(' XDS design system installed!')}+${line('')}+${line(' Get started:')}+${line(` ${r} init Interactive setup`)}+${line(` ${r} --help See all commands`)}+${line('')}+${line(' Or run directly:')}+${line(` ${r} init Setup + AI agent docs`)}+${line(` ${r} component Browse component docs`)}+${line(` ${r} docs Design system reference`)}+${line(` ${r} swizzle Customize a component`)}+${line(` ${r} template Add a page template`)}+${line('')}+ ╰${'─'.repeat(W + 2)}╯`);});diff --git a/packages/cli/src/lib/component-legacy.mjs b/packages/cli/src/lib/component-legacy.mjsindex 38480d5952..447cfb483c 100644--- a/packages/cli/src/lib/component-legacy.mjs+++ b/packages/cli/src/lib/component-legacy.mjs@@ -10,6 +10,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {discoverComponents, findComponentReadme, resolveImportPath} from './component-discovery.mjs';+import {getRunPrefix} from '../utils/package-manager.mjs';export function cleanReadme(content, componentName) {const displayName = componentName.startsWith('XDS')@@ -386,7 +387,7 @@ export function extractBriefAll(coreDir) {`> **Style overrides:** Most components accept an \`xstyle\` prop.`,`> Use inline objects for simple overrides: \`xstyle={{ maxWidth: 300 }}\``,`> Use \`stylex.create()\` for pseudo-classes/media queries or 3+ properties.`,- `> See \`npx xds docs principles\` for details.\n`,+ `> See \`${getRunPrefix()} xds docs principles\` for details.\n`,);for (const [category, comps] of Object.entries(components)) {diff --git a/packages/cli/src/utils/package-manager.mjs b/packages/cli/src/utils/package-manager.mjsindex 0974a3622e..8407302842 100644--- a/packages/cli/src/utils/package-manager.mjs+++ b/packages/cli/src/utils/package-manager.mjs@@ -16,17 +16,39 @@ import * as path from 'node:path';* @returns {'yarn'|'pnpm'|'bun'|'npm'}*/export function detectPackageManager(targetDir = process.cwd()) {+ const KNOWN_PMS = new Set(['yarn', 'pnpm', 'bun', 'npm']);let dir = path.resolve(targetDir);const root = path.parse(dir).root;while (dir !== root) {+ // 1. Lockfiles (highest priority)if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';if (fs.existsSync(path.join(dir, 'bun.lockb')) || fs.existsSync(path.join(dir, 'bun.lock'))) return 'bun';if (fs.existsSync(path.join(dir, 'package-lock.json'))) return 'npm';++ // 2. packageManager field in package.json+ const pkgPath = path.join(dir, 'package.json');+ if (fs.existsSync(pkgPath)) {+ try {+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ if (pkg.packageManager) {+ const name = pkg.packageManager.split('@')[0];+ if (KNOWN_PMS.has(name)) return name;+ }+ } catch {}+ }+dir = path.dirname(dir);}+ // 3. npm_config_user_agent env var (set by all PMs when running scripts)+ const ua = process.env.npm_config_user_agent;+ if (ua) {+ const name = ua.split('/')[0];+ if (KNOWN_PMS.has(name)) return name;+ }+return 'npx';}diff --git a/packages/cli/src/utils/package-manager.test.mjs b/packages/cli/src/utils/package-manager.test.mjsnew file mode 100644index 0000000000..5461fd71b3--- /dev/null+++ b/packages/cli/src/utils/package-manager.test.mjs@@ -0,0 +1,111 @@+import {describe, it, expect, afterEach, vi} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {detectPackageManager} from './package-manager.mjs';++let tmpDir;++afterEach(() => {+ if (tmpDir) {+ fs.rmSync(tmpDir, {recursive: true, force: true});+ tmpDir = null;+ }+ vi.restoreAllMocks();+ delete process.env.npm_config_user_agent;+});++function makeTmpDir() {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-pm-test-'));+ return tmpDir;+}++describe('detectPackageManager', () => {+ it('detects yarn from yarn.lock', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ expect(detectPackageManager(dir)).toBe('yarn');+ });++ it('detects pnpm from pnpm-lock.yaml', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');+ expect(detectPackageManager(dir)).toBe('pnpm');+ });++ it('detects npm from package-lock.json', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');+ expect(detectPackageManager(dir)).toBe('npm');+ });++ it('detects bun from bun.lockb', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'bun.lockb'), '');+ expect(detectPackageManager(dir)).toBe('bun');+ });++ it('detects from packageManager field in package.json (no lockfile)', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(detectPackageManager(dir)).toBe('yarn');+ });++ it('detects pnpm from packageManager field', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(detectPackageManager(dir)).toBe('pnpm');+ });++ it('ignores unknown packageManager values', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(detectPackageManager(dir)).toBe('npx');+ });++ it('lockfile takes priority over packageManager field', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ expect(detectPackageManager(dir)).toBe('yarn');+ });++ it('detects from npm_config_user_agent env var', () => {+ const dir = makeTmpDir();+ process.env.npm_config_user_agent = 'yarn/1.22.22 node/v20.0.0';+ expect(detectPackageManager(dir)).toBe('yarn');+ });++ it('detects pnpm from npm_config_user_agent env var', () => {+ const dir = makeTmpDir();+ process.env.npm_config_user_agent = 'pnpm/8.15.0 node/v20.0.0';+ expect(detectPackageManager(dir)).toBe('pnpm');+ });++ it('falls back to npx when no signals present', () => {+ const dir = makeTmpDir();+ expect(detectPackageManager(dir)).toBe('npx');+ });++ it('packageManager field takes priority over npm_config_user_agent', () => {+ const dir = makeTmpDir();+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({packageManager: '[email protected]'}),+ );+ process.env.npm_config_user_agent = 'npm/10.0.0 node/v20.0.0';+ expect(detectPackageManager(dir)).toBe('bun');+ });+});