Skip to content

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

TypeScript

fix(cli): scope migration literals to resolved sinks (#6445)

EJ Hammond8dd6f73f2f73
diff --git a/.changeset/scope-codemods-to-jsx-props.md b/.changeset/scope-codemods-to-jsx-props.md
new file mode 100644
index 0000000000..1382175fab
--- /dev/null
+++ b/.changeset/scope-codemods-to-jsx-props.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Restrict the status-variant and Avatar-size upgrade codemods to static props on verified imported JSX components, avoiding unrelated literal rewrites.
+
+@ejhammond
diff --git a/packages/cli/assets/codemods/transform-prop.mjs b/packages/cli/assets/codemods/transform-prop.mjs
new file mode 100644
index 0000000000..2da71b9aaa
--- /dev/null
+++ b/packages/cli/assets/codemods/transform-prop.mjs
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Find imported components, resolve their local JSX names (including aliases),
+ * and yield matching JSX prop paths to a visitor.
+ *
+ * This helper intentionally stops at the JSX boundary. It does not follow
+ * variables, helper calls, object spreads, wrapper components, or types.
+ *
+ * @param {any} root jscodeshift collection for one source file
+ * @param {any} j configured jscodeshift instance
+ * @param {{
+ * matchesImport: (source: string) => boolean,
+ * components: ReadonlyMap<string, ReadonlySet<string>>,
+ * normalizeComponentName?: (name: string) => string,
+ * }} options
+ * @param {(propPath: any, context: {component: string, localName: string}) => void} visit
+ */
+export function transformProp(root, j, options, visit) {
+ const normalize = options.normalizeComponentName ?? (name => name);
+ /** @type {Map<string, {component: string, props: ReadonlySet<string>}>} */
+ const directBindings = new Map();
+ /** @type {Set<string>} */
+ const namespaceBindings = new Set();
+
+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {
+ const source = importPath.node.source.value;
+ if (
+ importPath.node.importKind === 'type' ||
+ typeof source !== 'string' ||
+ !options.matchesImport(source)
+ ) {
+ return;
+ }
+
+ const subpathName = normalize(source.split('/').at(-1) ?? '');
+ const subpathProps = options.components.get(subpathName);
+
+ for (const specifier of importPath.node.specifiers ?? []) {
+ if (specifier.importKind === 'type') continue;
+
+ if (specifier.type === 'ImportSpecifier') {
+ const importedName =
+ specifier.imported?.name ?? specifier.imported?.value;
+ if (typeof importedName !== 'string') continue;
+ const component = normalize(importedName);
+ const props = options.components.get(component);
+ if (!props) continue;
+ directBindings.set(specifier.local?.name ?? importedName, {
+ component,
+ props,
+ });
+ } else if (specifier.type === 'ImportDefaultSpecifier' && subpathProps) {
+ directBindings.set(specifier.local.name, {
+ component: subpathName,
+ props: subpathProps,
+ });
+ } else if (specifier.type === 'ImportNamespaceSpecifier') {
+ namespaceBindings.add(specifier.local.name);
+ }
+ }
+ });
+
+ if (directBindings.size === 0 && namespaceBindings.size === 0) return;
+
+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ jsxPath) => {
+ const name = jsxPath.node.name;
+ let localName;
+ let component;
+ let props;
+
+ if (name.type === 'JSXIdentifier') {
+ localName = name.name;
+ const binding = directBindings.get(localName);
+ if (!binding) return;
+ ({component, props} = binding);
+ } else if (
+ name.type === 'JSXMemberExpression' &&
+ name.object?.type === 'JSXIdentifier' &&
+ name.property?.type === 'JSXIdentifier' &&
+ namespaceBindings.has(name.object.name)
+ ) {
+ localName = name.object.name;
+ component = normalize(name.property.name);
+ props = options.components.get(component);
+ if (!props) return;
+ } else {
+ return;
+ }
+
+ // A parameter or local declaration with the imported name shadows the
+ // module binding. Only JSX tags whose root binding resolves to Program are
+ // considered usages of the import discovered above.
+ const bindingScope = jsxPath.scope.lookup(localName);
+ if (!bindingScope || bindingScope.path.node.type !== 'Program') return;
+
+ for (let index = 0; index < jsxPath.node.attributes.length; index++) {
+ const attribute = jsxPath.node.attributes[index];
+ if (
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name?.type !== 'JSXIdentifier' ||
+ !props.has(attribute.name.name)
+ ) {
+ continue;
+ }
+ visit(jsxPath.get('attributes', index), {component, localName});
+ }
+ });
+}
diff --git a/packages/cli/assets/codemods/transform-prop.test.mjs b/packages/cli/assets/codemods/transform-prop.test.mjs
new file mode 100644
index 0000000000..95a0e21e6d
--- /dev/null
+++ b/packages/cli/assets/codemods/transform-prop.test.mjs
@@ -0,0 +1,95 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import jscodeshift from 'jscodeshift';
+import {transformProp} from './transform-prop.mjs';
+
+const j = jscodeshift.withParser('tsx');
+const components = new Map([
+ ['Widget', new Set(['tone'])],
+ ['Group', new Set(['size'])],
+]);
+
+function apply(source) {
+ const root = j(source);
+ transformProp(
+ root,
+ j,
+ {
+ matchesImport: value => /^@example\/core(?:\/|$)/.test(value),
+ components,
+ normalizeComponentName: name =>
+ name.startsWith('XDS') ? name.slice(3) : name,
+ },
+ propPath => {
+ propPath.node.name.name = `migrated${propPath.node.name.name}`;
+ },
+ );
+ return root.toSource({quote: 'single'});
+}
+
+describe('transformProp', () => {
+ it('maps named import aliases to their JSX usages', () => {
+ const output = apply(`import {Widget as Card} from '@example/core';
+const view = <Card tone="old" other="old" />;`);
+
+ expect(output).toContain('<Card migratedtone="old" other="old"');
+ });
+
+ it('maps default subpath imports', () => {
+ const output = apply(`import Card from '@example/core/Widget';
+const view = <Card tone="old" />;`);
+
+ expect(output).toContain('<Card migratedtone="old"');
+ });
+
+ it('ignores declaration-level type imports', () => {
+ const output = apply(`import type {Widget} from '@example/core';
+const Widget = props => <div {...props} />;
+const view = <Widget tone="old" />;`);
+
+ expect(output).toContain('<Widget tone="old"');
+ expect(output).not.toContain('migratedtone');
+ });
+
+ it('ignores type specifiers in mixed imports', () => {
+ const output = apply(`import {type Widget, Group} from '@example/core';
+const Widget = props => <div {...props} />;
+const view = <><Widget tone="old" /><Group size="old" /></>;`);
+
+ expect(output).toContain('<Widget tone="old"');
+ expect(output).toContain('<Group migratedsize="old"');
+ expect(output).not.toContain('<Widget migratedtone');
+ });
+
+ it('maps namespace imports', () => {
+ const output = apply(`import * as Core from '@example/core';
+const view = <Core.Group size="old" />;`);
+
+ expect(output).toContain('<Core.Group migratedsize="old"');
+ });
+
+ it('ignores same-named imports from other packages', () => {
+ const source = `import {Widget} from '@other/core';
+const view = <Widget tone="old" />;`;
+ expect(apply(source)).toBe(source);
+ });
+
+ it('ignores a local binding that shadows an imported alias', () => {
+ const output = apply(`import {Widget as Card} from '@example/core';
+const migrated = <Card tone="old" />;
+function Local(Card) { return <Card tone="local" />; }`);
+
+ expect(output).toContain('<Card migratedtone="old"');
+ expect(output).toContain('<Card tone="local"');
+ });
+
+ it('yields only configured props on configured components', () => {
+ const output = apply(`import {Widget, Group} from '@example/core';
+const a = <Widget size="old" tone="old" />;
+const b = <Group tone="old" size="old" />;`);
+
+ expect(output).toContain('<Widget size="old" migratedtone="old"');
+ expect(output).toContain('<Group tone="old" migratedsize="old"');
+ });
+});
diff --git a/packages/cli/assets/codemods/transforms/v0.0.14/__tests__/rename-status-variants.test.mjs b/packages/cli/assets/codemods/transforms/v0.0.14/__tests__/rename-status-variants.test.mjs
index b0a58173f5..9a719a07b0 100644
--- a/packages/cli/assets/codemods/transforms/v0.0.14/__tests__/rename-status-variants.test.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.0.14/__tests__/rename-status-variants.test.mjs
@@ -1,205 +1,126 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {describe, expect, it} from 'vitest';
+import transform from '../rename-status-variants.mjs';
async function applyTransform(source) {
- const {default: transform} = await import(
- '../rename-status-variants.mjs'
- );
const jscodeshift = (await import('jscodeshift')).default;
const j = jscodeshift.withParser('tsx');
const api = {jscodeshift: j, stats: () => {}, report: () => {}};
- const file = {source, path: 'test.tsx'};
- const result = transform(file, api);
- return result ?? source;
+ return transform({source, path: 'test.tsx'}, api) ?? source;
}
describe('rename-status-variants', () => {
- it('renames StatusDot variant="positive" to "success"', async () => {
- const input = `<XDSStatusDot variant="positive" label="Online" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).not.toContain("'positive'");
- });
+ it('renames direct StatusDot literals and ternary branches', async () => {
+ const output = await applyTransform(`import {StatusDot} from '@astryxdesign/core';
+const a = <StatusDot variant="positive" />;
+const b = <StatusDot variant={'negative'} />;
+const c = <StatusDot variant={ready ? 'info' : 'positive'} />;`);
- it('renames StatusDot variant="negative" to "error"', async () => {
- const input = `<XDSStatusDot variant="negative" label="Offline" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'error'");
- expect(output).not.toContain("'negative'");
+ expect(output).toContain("variant='success'");
+ expect(output).toContain("variant={'error'}");
+ expect(output).toContain("ready ? 'accent' : 'success'");
});
- it('renames StatusDot variant="info" to "accent"', async () => {
- const input = `<XDSStatusDot variant="info" label="Info" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'accent'");
- expect(output).not.toContain("'info'");
- });
+ it('renames literals inside satisfies expressions while preserving the type', async () => {
+ const output =
+ await applyTransform(`import {StatusDot} from '@astryxdesign/core';
+const view = <StatusDot variant={'positive' satisfies StatusDotVariant} />;`);
- it('renames AvatarStatusDot variant="positive" to "success"', async () => {
- const input = `<XDSAvatarStatusDot variant="positive" label="Online" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).not.toContain("'positive'");
+ expect(output).toContain("{'success' satisfies StatusDotVariant}");
});
- it('renames Icon color="positive" to "success"', async () => {
- const input = `<XDSIcon color="positive" icon={CheckIcon} />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).not.toContain("'positive'");
- });
+ it('renames Icon, SVGIcon, AvatarStatusDot, and ProgressBar props', async () => {
+ const output = await applyTransform(`import {
+ Icon,
+ SVGIcon,
+ AvatarStatusDot,
+ ProgressBar,
+} from '@astryxdesign/core';
+const view = <>
+ <Icon color="negative" />
+ <SVGIcon color="positive" />
+ <AvatarStatusDot variant="negative" />
+ <ProgressBar variant="positive" />
+</>;`);
- it('renames Icon color="negative" to "error"', async () => {
- const input = `<XDSIcon color="negative" icon={XIcon} />`;
- const output = await applyTransform(input);
- expect(output).toContain("'error'");
- expect(output).not.toContain("'negative'");
+ expect(output.match(/'error'/g)).toHaveLength(2);
+ expect(output.match(/'success'/g)).toHaveLength(2);
});
- it('renames ProgressBar variant="positive" to "success"', async () => {
- const input = `<XDSProgressBar variant="positive" value={50} />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).not.toContain("'positive'");
- });
+ it('maps import aliases and default subpath imports', async () => {
+ const output = await applyTransform(`import {StatusDot as Dot} from '@xds/core';
+import IconGlyph from '@astryxdesign/core/Icon';
+const view = <><Dot variant="positive" /><IconGlyph color="negative" /></>;`);
- it('renames ProgressBar variant="negative" to "error"', async () => {
- const input = `<XDSProgressBar variant="negative" value={50} />`;
- const output = await applyTransform(input);
- expect(output).toContain("'error'");
- expect(output).not.toContain("'negative'");
+ expect(output).toContain("<Dot variant='success'");
+ expect(output).toContain("<IconGlyph color='error'");
});
- it('handles expression container: variant={"positive"}', async () => {
- const input = `<XDSStatusDot variant={'positive'} label="Online" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).not.toContain("'positive'");
- });
+ it('maps namespace imports', async () => {
+ const output = await applyTransform(`import * as Core from '@astryxdesign/core';
+const view = <Core.StatusDot variant="info" />;`);
- it('handles ternary: variant={x ? "positive" : "negative"}', async () => {
- const input = `<XDSStatusDot variant={isOnline ? 'positive' : 'negative'} label="Status" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).toContain("'error'");
- expect(output).not.toContain("'positive'");
- expect(output).not.toContain("'negative'");
+ expect(output).toContain("variant='accent'");
});
- it('renames object property values in files importing target components', async () => {
- const input = `import { XDSStatusDot } from '@xds/core/StatusDot';
-const args = { variant: 'positive' };`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).not.toContain("'positive'");
- });
+ it('keeps Badge info distinct while renaming its removed variants', async () => {
+ const output = await applyTransform(`import {Badge} from '@astryxdesign/core';
+const view = <>
+ <Badge variant="info" />
+ <Badge variant="positive" />
+ <Badge variant="negative" />
+</>;`);
- it('renames unambiguous values in Storybook argType options arrays but leaves ambiguous "info"', async () => {
- const input = `import { XDSStatusDot } from '@xds/core/StatusDot';
-const meta = { argTypes: { variant: { options: ['positive', 'negative', 'warning', 'info', 'neutral'] } } };`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).toContain("'error'");
- expect(output).not.toContain("'positive'");
- expect(output).not.toContain("'negative'");
- // 'info' is ambiguous (valid on Badge etc.) and this is a context-blind
- // path — the codemod cannot tell which component the options describe, so
- // it is left for human review rather than risk rewriting a valid value.
- expect(output).toContain("'info'");
- expect(output).not.toContain("'accent'");
- // warning and neutral are unchanged
- expect(output).toContain("'warning'");
- expect(output).toContain("'neutral'");
+ expect(output).toContain('variant="info"');
+ expect(output).toContain("variant='success'");
+ expect(output).toContain("variant='error'");
});
- it('does not touch unrelated components', async () => {
- const input = `<XDSBadge variant="info" label="New" />`;
- const output = await applyTransform(input);
- // XDSBadge is not in the target list
- expect(output).toContain('info');
+ it('leaves variables, helpers, objects, types, and Storybook metadata untouched', async () => {
+ const input = `import {StatusDot} from '@astryxdesign/core';
+type CellTone = 'positive' | 'negative' | 'info';
+const args = {variant: 'positive'};
+const options = ['positive', 'negative', 'info'];
+function tone() { return 'negative' as const; }
+const view = <StatusDot variant={tone()} />;`;
+
+ expect(await applyTransform(input)).toBe(input);
});
- it('does not rewrite Badge config "info" in a file that also imports a target (Icon)', async () => {
- // Regression: a file may import a target component (e.g. XDSIcon) AND
- // declare a typed config object for a NON-target component (Badge, whose
- // BadgeVariantMap still has `info`). The context-blind object-property path
- // must NOT rewrite that `info` to `accent` just because the file imports a
- // target — `accent` is not a valid Badge variant. positive/negative stay
- // renamed (no component keeps them), but info is preserved.
- const input = `import { XDSIcon } from '@xds/core/Icon';
-import { XDSBadge, type XDSBadgeVariant } from '@xds/core/Badge';
-const PROGRESS_CONFIG: Record<string, {label: string; variant: XDSBadgeVariant}> = {
- OPEN: {label: 'Open', variant: 'info'},
- DONE: {label: 'Done', variant: 'positive'},
- BLOCKED: {label: 'Blocked', variant: 'negative'},
-};`;
- const output = await applyTransform(input);
- // Ambiguous 'info' on a Badge config is left intact.
- expect(output).toContain("variant: 'info'");
- expect(output).not.toContain("'accent'");
- // Unambiguous values are still migrated (no component retains them).
- expect(output).toContain("variant: 'success'");
- expect(output).toContain("variant: 'error'");
- expect(output).not.toContain("'positive'");
- expect(output).not.toContain("'negative'");
+ it('leaves unrelated props untouched', async () => {
+ const output = await applyTransform(`import {StatusDot} from '@astryxdesign/core';
+const view = <StatusDot variant="positive" label="positive" />;`);
+
+ expect(output).toContain("variant='success'");
+ expect(output).toContain('label="positive"');
});
- it('still renames "info" to "accent" on a direct target JSX attribute', async () => {
- // The precise path (component is known) keeps the full mapping, including
- // the ambiguous info -> accent, even when other components are imported.
- const input = `import { XDSStatusDot } from '@xds/core/StatusDot';
-import { XDSBadge } from '@xds/core/Badge';
-const a = <XDSStatusDot variant="info" label="Status" />;
-const b = <XDSBadge variant="info" label="New" />;`;
- const output = await applyTransform(input);
- // StatusDot's info -> accent (precise), Badge's info stays.
- expect(output).toContain("<XDSStatusDot variant='accent'");
- expect(output).toContain('<XDSBadge variant="info"');
+ it('ignores same-named components imported from other packages', async () => {
+ const input = `import {StatusDot} from '@other/core';
+const view = <StatusDot variant="positive" />;`;
+ expect(await applyTransform(input)).toBe(input);
});
- it('does not touch unrelated props on target components', async () => {
- const input = `<XDSStatusDot variant="positive" label="positive result" />`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- // The label "positive result" should NOT be renamed
- expect(output).toContain('positive result');
+ it('ignores a local component that shadows an imported alias', async () => {
+ const output = await applyTransform(`import {StatusDot as Dot} from '@xds/core';
+const migrated = <Dot variant="positive" />;
+function Local(Dot) { return <Dot variant="negative" />; }`);
+
+ expect(output).toContain("variant='success'");
+ expect(output).toContain('variant="negative"');
});
- it('returns undefined when no changes needed', async () => {
- const {default: transform} = await import(
- '../rename-status-variants.mjs'
- );
+ it('returns undefined when no direct prop needs a change', async () => {
const jscodeshift = (await import('jscodeshift')).default;
const j = jscodeshift.withParser('tsx');
- const api = {jscodeshift: j, stats: () => {}, report: () => {}};
- const source = `<XDSStatusDot variant='success' label='Online' />`;
- const result = transform({source, path: 'test.tsx'}, api);
- expect(result).toBeUndefined();
- });
-
- it('handles a full component file', async () => {
- const input = `import { XDSStatusDot } from '@xds/core/StatusDot';
-import { XDSIcon } from '@xds/core/Icon';
-
-function StatusIndicator({ isOnline }: { isOnline: boolean }) {
- return (
- <div>
- <XDSStatusDot
- variant={isOnline ? 'positive' : 'negative'}
- label={isOnline ? 'Online' : 'Offline'}
- />
- <XDSIcon
- icon={isOnline ? CheckIcon : XIcon}
- color={isOnline ? 'positive' : 'negative'}
- />
- </div>
- );
-}`;
- const output = await applyTransform(input);
- expect(output).toContain("'success'");
- expect(output).toContain("'error'");
- expect(output).not.toContain("'positive'");
- expect(output).not.toContain("'negative'");
+ const source = `import {StatusDot} from '@astryxdesign/core';
+const view = <StatusDot variant="success" />;`;
+ expect(
+ transform(
+ {source, path: 'test.tsx'},
+ {jscodeshift: j, stats: () => {}, report: () => {}},
+ ),
+ ).toBeUndefined();
});
});
diff --git a/packages/cli/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs b/packages/cli/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs
index c40eb506c8..6aa6e866df 100644
--- a/packages/cli/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs
@@ -4,86 +4,81 @@
* @file Codemod: Rename status variants positive/negative → success/error
* @see https://github.com/facebookexperimental/xds/issues/996
*
- * Converges component APIs to match the token layer naming:
- * - `positive` → `success` (maps to --color-success)
- * - `negative` → `error` (maps to --color-error)
- * - `info` → `accent` (maps to --color-accent)
- *
- * Affected components:
- * - XDSStatusDot: variant="positive|negative|info" → variant="success|error|accent"
- * - XDSAvatarStatusDot: variant="positive|negative" → variant="success|error"
- * - XDSIcon: color="positive|negative" → color="success|error"
- * - XDSProgressBar: variant="positive|negative" → variant="success|error"
- *
- * Transforms JSX attributes, object properties (in files importing affected
- * components), TypeScript type annotations, and Storybook argType options.
+ * This transform is deliberately limited to static literals written directly
+ * in affected props on imported JSX components. It does not infer through
+ * variables, helpers, objects, types, or wrappers: missing an indirect
+ * migration is safer than rewriting an unrelated domain using the same words.
*/
+import {transformProp} from '../../transform-prop.mjs';
+
export const meta = {
title: 'Rename status variants positive/negative → success/error',
description:
- 'Renames `positive` to `success`, `negative` to `error`, and `info` to `accent` ' +
- 'on StatusDot, AvatarStatusDot, Icon, SVGIcon, and ProgressBar to align with token naming. ' +
- 'The `info` -> `accent` rename is only applied to direct JSX attributes on these ' +
- 'components (where the component is known); in context-blind locations (object ' +
- 'properties, type unions) `info` is left untouched because it is a valid variant on ' +
- 'other components such as Badge.',
+ 'Renames static status values written directly on imported StatusDot, ' +
+ 'AvatarStatusDot, Icon, SVGIcon, ProgressBar, and Badge JSX elements. ' +
+ 'Indirect values are left unchanged for manual migration.',
pr: '#996',
};
-/** Rename mappings. */
-const RENAMES = new Map([
+const CORE_IMPORT_RE = /^@(astryxdesign|xds)\/core(?:\/|$)/;
+
+const COMPONENT_PROPS = new Map([
+ ['StatusDot', new Set(['variant'])],
+ ['AvatarStatusDot', new Set(['variant'])],
+ ['Icon', new Set(['color'])],
+ ['SVGIcon', new Set(['color'])],
+ ['ProgressBar', new Set(['variant'])],
+ ['Badge', new Set(['variant'])],
+]);
+
+const STATUS_RENAMES = new Map([
['positive', 'success'],
['negative', 'error'],
['info', 'accent'],
]);
-/**
- * Ambiguous renames that are only safe when the target component is known.
- *
- * `info` is a VALID variant on non-target components (notably XDSBadge, whose
- * BadgeVariantMap still has `info`). `positive`/`negative` are not retained by
- * any component post-migration, so renaming them is always safe. Therefore the
- * context-blind heuristic paths (object properties, type unions, and suffixed
- * props on wrapper components) must NOT rewrite `info` — only the precise path,
- * a direct JSX attribute on a known target component, may. Otherwise a
- * `variant: 'info'` on an unrelated Badge config in a file that merely also
- * imports e.g. XDSIcon gets wrongly rewritten to the invalid `accent`.
- */
-const AMBIGUOUS_VALUES = new Set(['info']);
-
-
-/**
- * Components and which props are affected.
- * Key: component name. Value: set of prop names to check.
- */
-const COMPONENT_PROPS = new Map([
- ['XDSStatusDot', new Set(['variant'])],
- ['XDSAvatarStatusDot', new Set(['variant'])],
- ['XDSIcon', new Set(['color'])],
- ['XDSProgressBar', new Set(['variant'])],
+const BADGE_RENAMES = new Map([
+ ['positive', 'success'],
+ ['negative', 'error'],
]);
-/** All affected component names for quick lookup. */
-const TARGET_COMPONENTS = new Set(COMPONENT_PROPS.keys());
-
-/** All affected prop names (variant, color). */
-const TARGET_PROP_NAMES = new Set();
-for (const props of COMPONENT_PROPS.values()) {
- for (const p of props) TARGET_PROP_NAMES.add(p);
+/** @param {string} name */
+function canonicalComponentName(name) {
+ return name.startsWith('XDS') ? name.slice(3) : name;
}
/**
- * Check if a key matches a target prop — exact or case-insensitive suffix.
- * e.g. "dotVariant" matches because it ends with "variant".
+ * @param {any} node
+ * @param {ReadonlyMap<string, string>} renames
+ * @returns {boolean}
*/
-function matchesPropName(/** @type {any} */ keyName) {
- if (TARGET_PROP_NAMES.has(keyName)) return true;
- const lower = keyName.toLowerCase();
- for (const prop of TARGET_PROP_NAMES) {
- if (lower.endsWith(prop.toLowerCase()) && lower !== prop.toLowerCase()) return true;
+function renameStaticValue(node, renames) {
+ if (!node) return false;
+ if (
+ node.type === 'TSAsExpression' ||
+ node.type === 'TSSatisfiesExpression' ||
+ node.type === 'TypeCastExpression' ||
+ node.type === 'ParenthesizedExpression'
+ ) {
+ return renameStaticValue(node.expression, renames);
}
- return false;
+ if (node.type === 'ConditionalExpression') {
+ const consequentChanged = renameStaticValue(node.consequent, renames);
+ const alternateChanged = renameStaticValue(node.alternate, renames);
+ return consequentChanged || alternateChanged;
+ }
+ if (
+ (node.type !== 'StringLiteral' && node.type !== 'Literal') ||
+ typeof node.value !== 'string'
+ ) {
+ return false;
+ }
+ const replacement = renames.get(node.value);
+ if (!replacement) return false;
+ node.value = replacement;
+ if (node.raw) node.raw = undefined;
+ return true;
}
/**
@@ -96,158 +91,25 @@ export default function transformer(file, api) {
const root = j(file.source);
let hasChanges = false;
- /**
- * Rename a string literal value if it matches our renames.
- * Unwraps TSAsExpression (e.g. 'positive' as const) to reach the literal.
- * @returns {boolean} whether a rename occurred
- */
- function renameValue(/** @type {any} */ node, {precise = false} = {}) {
- if (!node) return false;
-
- // Unwrap TSAsExpression (e.g. 'positive' as const → StringLiteral)
- const target = node.type === 'TSAsExpression' ? node.expression : node;
-
- const isString =
- target.type === 'StringLiteral' || target.type === 'Literal';
- if (!isString || typeof target.value !== 'string') return false;
-
- const replacement = RENAMES.get(target.value);
- if (!replacement) return false;
-
- // Ambiguous values (e.g. `info`) are only renamed in a precise context
- // where the target component is known (a direct JSX attribute on a target).
- // In context-blind paths they may belong to a component that legitimately
- // keeps the value (e.g. Badge's `info`), so leave them untouched.
- if (!precise && AMBIGUOUS_VALUES.has(target.value)) return false;
-
- target.value = replacement;
- if (target.raw) target.raw = undefined;
- return true;
- }
-
- /**
- * Rename elements in an array (handles TSAsExpression wrapping).
- */
- function renameArrayElements(/** @type {any} */ node, {precise = false} = {}) {
- let arrayNode = node;
- if (arrayNode.type === 'TSAsExpression') arrayNode = arrayNode.expression;
- if (arrayNode.type !== 'ArrayExpression') return;
- arrayNode.elements.forEach((/** @type {any} */ el) => {
- if (renameValue(el, {precise})) hasChanges = true;
- });
- }
-
- // Determine early: does this file import any target component?
- const importsTarget = [...TARGET_COMPONENTS].some(
- (name) =>
- root.find(j.ImportSpecifier, {imported: {name}}).length > 0,
+ transformProp(
+ root,
+ j,
+ {
+ matchesImport: source => CORE_IMPORT_RE.test(source),
+ components: COMPONENT_PROPS,
+ normalizeComponentName: canonicalComponentName,
+ },
+ (propPath, {component}) => {
+ const prop = propPath.node;
+ const value =
+ prop.value?.type === 'JSXExpressionContainer'
+ ? prop.value.expression
+ : prop.value;
+ const renames = component === 'Badge' ? BADGE_RENAMES : STATUS_RENAMES;
+ if (renameStaticValue(value, renames)) hasChanges = true;
+ },
);
- // 1. JSX attributes on target components
- root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {
- const name = path.node.name;
- const componentName = name.type === 'JSXIdentifier' ? name.name : null;
- if (!componentName) return;
-
- const isDirectTarget = TARGET_COMPONENTS.has(componentName);
- // For non-target components, only check suffixed props if file imports targets
- if (!isDirectTarget && !importsTarget) return;
-
- path.node.attributes.forEach((/** @type {any} */ attr) => {
- if (attr.type !== 'JSXAttribute') return;
- const attrName = attr.name.name;
-
- if (isDirectTarget) {
- // Direct targets: only their specific props
- const targetProps = COMPONENT_PROPS.get(componentName);
- if (!targetProps || !targetProps.has(attrName)) return;
- } else {
- // Non-target components: suffixed prop names only
- // (e.g. dotVariant on ChangelogSection wrapping XDSStatusDot)
- if (!matchesPropName(attrName) || TARGET_PROP_NAMES.has(attrName)) return;
- }
-
- // Only a direct JSX attribute on a target component is a precise context
- // where the component (and thus the validity of `info`) is known. The
- // wrapper/suffixed-prop case is a heuristic and must not touch ambiguous
- // values.
- const precise = isDirectTarget;
- const value = attr.value;
-
- // variant="positive" (string literal)
- if (renameValue(value, {precise})) {
- hasChanges = true;
- return;
- }
-
- // variant={'positive'} (expression container)
- if (
- value &&
- value.type === 'JSXExpressionContainer' &&
- value.expression
- ) {
- if (renameValue(value.expression, {precise})) {
- hasChanges = true;
- return;
- }
-
- // variant={condition ? 'positive' : 'negative'} (ternary)
- if (value.expression.type === 'ConditionalExpression') {
- if (renameValue(value.expression.consequent, {precise}))
- hasChanges = true;
- if (renameValue(value.expression.alternate, {precise}))
- hasChanges = true;
- }
- }
- });
- });
-
- // 2. Object properties in files importing target components.
- // Handles args objects, config objects, Storybook argTypes, etc.
- if (importsTarget) {
- const PropertyType = j.ObjectProperty ?? j.Property;
- root.find(PropertyType).forEach((/** @type {any} */ path) => {
- const key = path.node.key;
- const keyName =
- key.type === 'Identifier'
- ? key.name
- : key.type === 'StringLiteral' || key.type === 'Literal'
- ? key.value
- : null;
-
- if (!keyName || !matchesPropName(keyName)) return;
-
- const value = path.node.value;
-
- // variant: 'positive' → variant: 'success'
- if (renameValue(value)) {
- hasChanges = true;
- return;
- }
-
- // variant: { options: ['positive', 'negative', ...] }
- if (value.type === 'ObjectExpression') {
- const optionsProp = value.properties.find(
- (/** @type {any} */ p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),
- );
- if (optionsProp) {
- renameArrayElements(optionsProp.value);
- }
- }
-
- // variant: ['positive', 'negative'] or [...] as Type[]
- renameArrayElements(value);
- });
- }
-
- // 3. TypeScript type references: 'positive' | 'negative' in union types
- if (importsTarget) {
- root.find(j.TSLiteralType).forEach((/** @type {any} */ path) => {
- const lit = path.node.literal;
- if (renameValue(lit)) hasChanges = true;
- });
- }
-
if (!hasChanges) return undefined;
return root.toSource({quote: 'single'});
}
diff --git a/packages/cli/assets/codemods/transforms/v0.1.8/__tests__/rename-avatar-size-scale.test.mjs b/packages/cli/assets/codemods/transforms/v0.1.8/__tests__/rename-avatar-size-scale.test.mjs
index fd21774650..c6e1c94c71 100644
--- a/packages/cli/assets/codemods/transforms/v0.1.8/__tests__/rename-avatar-size-scale.test.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.1.8/__tests__/rename-avatar-size-scale.test.mjs
@@ -1,161 +1,129 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
+import {describe, expect, it} from 'vitest';
+import transform from '../rename-avatar-size-scale.mjs';
async function applyTransform(source) {
- const {default: transform} = await import('../rename-avatar-size-scale.mjs');
const jscodeshift = (await import('jscodeshift')).default;
const j = jscodeshift.withParser('tsx');
const api = {jscodeshift: j, stats: () => {}, report: () => {}};
- const file = {source, path: 'test.tsx'};
- const result = transform(file, api);
- return result ?? source;
+ return transform({source, path: 'test.tsx'}, api) ?? source;
}
describe('rename-avatar-size-scale', () => {
- it('renames every named size on an Avatar JSX size attribute', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
+ it('renames every direct Avatar size literal', async () => {
+ const output =
+ await applyTransform(`import {Avatar} from '@astryxdesign/core';
const a = <Avatar name="A" size="tiny" />;
const b = <Avatar name="B" size="xsmall" />;
const c = <Avatar name="C" size="small" />;
const d = <Avatar name="D" size="medium" />;
-const e = <Avatar name="E" size="large" />;`;
- const output = await applyTransform(input);
- expect(output).toContain(`size='xsm'`);
- expect(output).toContain(`size='sm'`);
- expect(output).toContain(`size='md'`);
- expect(output).toContain(`size='lg'`);
- expect(output).toContain(`size='xl'`);
- for (const old of ['tiny', 'xsmall', 'small', 'medium', 'large']) {
- expect(output).not.toContain(`size="${old}"`);
+const e = <Avatar name="E" size="large" />;`);
+
+ for (const size of ['xsm', 'sm', 'md', 'lg', 'xl']) {
+ expect(output).toContain(`size='${size}'`);
}
});
- it('renames size on AvatarGroup', async () => {
- const input = `import {AvatarGroup} from '@astryxdesign/core';
-const x = <AvatarGroup size="medium">{kids}</AvatarGroup>;`;
- const output = await applyTransform(input);
- expect(output).toContain(`size='lg'`);
- });
+ it('renames literals inside satisfies expressions while preserving the type', async () => {
+ const output =
+ await applyTransform(`import {Avatar} from '@astryxdesign/core';
+const view = <Avatar size={'small' satisfies AvatarSize} />;`);
- it('leaves numeric sizes untouched', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
-const x = <Avatar name="A" size={48} />;`;
- const output = await applyTransform(input);
- expect(output).toContain('size={48}');
+ expect(output).toContain("{'md' satisfies AvatarSize}");
});
- it('is alias-aware', async () => {
- const input = `import {Avatar as Face} from '@astryxdesign/core';
-const x = <Face name="A" size="small" />;`;
- const output = await applyTransform(input);
- expect(output).toContain(`size='md'`);
- });
+ it('renames AvatarGroup and conditional literals', async () => {
+ const output =
+ await applyTransform(`import {AvatarGroup} from '@astryxdesign/core';
+const view = <AvatarGroup size={large ? 'large' : 'small'}>{kids}</AvatarGroup>;`);
- it('renames the subpath and legacy import sources', async () => {
- const sub = `import {Avatar} from '@astryxdesign/core/Avatar';
-const x = <Avatar name="A" size="large" />;`;
- expect(await applyTransform(sub)).toContain(`size='xl'`);
- const legacy = `import {Avatar} from '@xds/core';
-const x = <Avatar name="A" size="tiny" />;`;
- expect(await applyTransform(legacy)).toContain(`size='xsm'`);
+ expect(output).toContain("large ? 'xl' : 'md'");
});
- it('renames a size inside a ternary on an Avatar element', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
-const x = <Avatar name="A" size={big ? 'large' : 'small'} />;`;
- const output = await applyTransform(input);
- expect(output).toContain(`big ? 'xl' : 'md'`);
- });
+ it('maps import aliases and default subpath imports', async () => {
+ const output =
+ await applyTransform(`import {Avatar as Face} from '@xds/core';
+import Faces from '@astryxdesign/core/AvatarGroup';
+const view = <><Face size="medium" /><Faces size="large" /></>;`);
- it('renames the UNIQUE names tiny/xsmall in Storybook options and size args', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
-const meta = {
- argTypes: {size: {control: 'select', options: ['tiny', 'xsmall']}},
- args: {size: 'tiny'},
-};`;
- const output = await applyTransform(input);
- expect(output).toContain(`['xsm', 'sm']`);
- expect(output).toContain(`size: 'xsm'`);
+ expect(output).toContain("<Face size='lg'");
+ expect(output).toContain("<Faces size='xl'");
});
- it('renames a FULL Storybook options array (unique name unlocks ambiguous members)', async () => {
- // The presence of a unique name (tiny/xsmall) proves the whole array is the
- // Avatar size enum, so small/medium/large in it are safe to rename too.
- const input = `import {Avatar} from '@astryxdesign/core';
-const meta = {
- argTypes: {size: {control: 'select', options: ['tiny', 'xsmall', 'small', 'medium', 'large']}},
-};`;
- const output = await applyTransform(input);
- expect(output).toContain(`['xsm', 'sm', 'md', 'lg', 'xl']`);
- });
+ it('ignores declaration-level type imports paired with a local Avatar', async () => {
+ const input = `import type {Avatar} from '@astryxdesign/core';
+const Avatar = props => <div {...props} />;
+const view = <Avatar size="small" />;`;
- it('renames a standalone Avatar-size array literal used with .map()', async () => {
- const input = `import {AvatarGroup} from '@astryxdesign/core';
-const sizes = (['tiny', 'xsmall', 'small', 'medium', 'large'] as const).map(s => s);`;
- const output = await applyTransform(input);
- expect(output).toContain(`['xsm', 'sm', 'md', 'lg', 'xl']`);
+ expect(await applyTransform(input)).toBe(input);
});
- it('does NOT rename an array of ambiguous words with no unique Avatar name', async () => {
- // Without tiny/xsmall, the array could be anything (priorities, densities),
- // so ambiguous members are left untouched.
- const input = `import {Avatar} from '@astryxdesign/core';
-const densities = ['small', 'medium', 'large'] as const;`;
- const output = await applyTransform(input);
- expect(output).toContain(`['small', 'medium', 'large']`);
- });
+ it('ignores mixed type specifiers while migrating runtime imports', async () => {
+ const output =
+ await applyTransform(`import {type Avatar, AvatarGroup} from '@astryxdesign/core';
+const Avatar = props => <div {...props} />;
+const view = <><Avatar size="small" /><AvatarGroup size="large" /></>;`);
- it('renames a UNIQUE name in a size-typed union literal', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
-type Props = {size: 'tiny' | 'xsmall'};`;
- const output = await applyTransform(input);
- expect(output).toContain(`'xsm' | 'sm'`);
+ expect(output).toContain('<Avatar size="small"');
+ expect(output).toContain("<AvatarGroup size='xl'");
});
- // --- Precision guards: ambiguous common words must NOT be corrupted in
- // --- context-blind positions, even in files that import Avatar. ---
+ it('maps namespace imports', async () => {
+ const output =
+ await applyTransform(`import * as Core from '@astryxdesign/core';
+const view = <Core.Avatar size="small" />;`);
- it('does NOT rename ambiguous names in an unrelated union type', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
-type TaskPriority = 'urgent' | 'high' | 'medium' | 'low' | 'none';`;
- const output = await applyTransform(input);
- expect(output).toContain(`'medium'`);
- expect(output).not.toContain(`'lg'`);
+ expect(output).toContain("size='md'");
});
- it('does NOT rename an ambiguous name in a non-size object property', async () => {
+ it('leaves numeric and dynamic sizes untouched', async () => {
const input = `import {Avatar} from '@astryxdesign/core';
-const cfg = {priority: 'medium', density: 'large'};`;
- const output = await applyTransform(input);
- expect(output).toContain(`priority: 'medium'`);
- expect(output).toContain(`density: 'large'`);
+const named = 'small';
+const a = <Avatar size={48} />;
+const b = <Avatar size={named} />;`;
+ expect(await applyTransform(input)).toBe(input);
});
- it('does NOT rename an ambiguous name in a size-keyed object property (component unknown)', async () => {
- // A `size: 'small'` object entry could belong to any component; renaming it
- // blind would be unsafe, so it is left for manual migration.
+ it('leaves objects, types, arrays, and Storybook metadata untouched', async () => {
const input = `import {Avatar} from '@astryxdesign/core';
-const args = {size: 'small'};`;
- const output = await applyTransform(input);
- expect(output).toContain(`size: 'small'`);
+type Density = 'tiny' | 'xsmall' | 'small' | 'medium' | 'large';
+const card = {size: 'small'};
+const sizes = ['tiny', 'xsmall', 'small', 'medium', 'large'];
+const meta = {argTypes: {size: {options: sizes}}};
+const view = <Avatar size={card.size} />;`;
+
+ expect(await applyTransform(input)).toBe(input);
});
- it('does not touch files that never import Avatar/AvatarGroup', async () => {
+ it('does not touch files without an Avatar import', async () => {
const input = `import {Badge} from '@astryxdesign/core';
-const x = <Badge size="small" />;
-type P = 'tiny' | 'xsmall';`;
- const output = await applyTransform(input);
- expect(output).toContain(`size="small"`);
- expect(output).toContain(`'tiny' | 'xsmall'`);
+const view = <Badge size="small" />;`;
+ expect(await applyTransform(input)).toBe(input);
});
- it('does not rename an unrelated non-size string in an Avatar file', async () => {
- const input = `import {Avatar} from '@astryxdesign/core';
-const label = 'small';
-const x = <Avatar name="A" size="small" />;`;
- const output = await applyTransform(input);
- expect(output).toContain(`const label = 'small'`);
- expect(output).toContain(`size='md'`);
+ it('ignores same-named components imported from other packages', async () => {
+ const input = `import {Avatar} from '@other/core';
+const view = <Avatar size="small" />;`;
+ expect(await applyTransform(input)).toBe(input);
+ });
+
+ it('ignores a local component that shadows an imported alias', async () => {
+ const output =
+ await applyTransform(`import {Avatar as Face} from '@xds/core';
+const migrated = <Face size="medium" />;
+function Local(Face) { return <Face size="large" />; }`);
+
+ expect(output).toContain("size='lg'");
+ expect(output).toContain('size="large"');
+ });
+
+ it('leaves unrelated props on Avatar untouched', async () => {
+ const output =
+ await applyTransform(`import {Avatar} from '@astryxdesign/core';
+const view = <Avatar size="small" label="small" />;`);
+
+ expect(output).toContain("size='md'");
+ expect(output).toContain('label="small"');
});
});
diff --git a/packages/cli/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs b/packages/cli/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs
index b36b4ee38e..a4f755ff34 100644
--- a/packages/cli/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs
@@ -4,46 +4,23 @@
* @file Codemod: Rename Avatar named sizes to Icon's abbreviated scale
* @see https://github.com/facebook/astryx/issues/2672
*
- * As of v0.1.8, Avatar and AvatarGroup use the same abbreviated size scale as
- * Icon (`xsm`/`sm`/`md`/`lg`/`xl`) instead of full words. Pixel values are
- * unchanged — only the names move:
- *
- * tiny (20px) → xsm
- * xsmall (24px) → sm
- * small (36px) → md ← also the new default (was `small`)
- * medium (48px) → lg
- * large (128px) → xl
- *
- * The default size shifts from `small` to `md`, but that is the SAME 36px, so
- * call sites that relied on the default need no change.
- *
- * ## Precision
- *
- * `small`, `medium`, and `large` are common English words that appear as
- * unrelated string/type literals (priorities, statuses, breakpoints, …). To
- * avoid corrupting those, the three AMBIGUOUS names are renamed ONLY in a
- * precise context: a `size` JSX attribute on a component that resolves to an
- * Avatar/AvatarGroup import (alias-aware).
- *
- * `tiny` and `xsmall` are unique to Avatar's scale, so they are additionally
- * renamed in context-blind positions (object properties keyed `size`/`*Size`,
- * Storybook `options` arrays, and size-typed union literals) within files that
- * import Avatar/AvatarGroup.
+ * This transform is deliberately limited to static literals written directly
+ * in the `size` prop of an imported Avatar or AvatarGroup JSX element. It does
+ * not infer through variables, helpers, objects, types, Storybook metadata, or
+ * wrappers: missing an indirect migration is safer than rewriting another
+ * component's size vocabulary.
*/
+import {transformProp} from '../../transform-prop.mjs';
+
export const meta = {
title: 'Rename Avatar named sizes tiny/xsmall/small/medium/large → xsm/sm/md/lg/xl',
description:
- 'Avatar and AvatarGroup adopt Icon\'s abbreviated size scale ' +
- '(xsm/sm/md/lg/xl). Pixel values are unchanged; the default moves from ' +
- '`small` to `md` (both 36px). The ambiguous names small/medium/large are ' +
- 'only renamed on Avatar/AvatarGroup `size` JSX attributes; the unique ' +
- 'names tiny/xsmall are also renamed in size-keyed props, Storybook ' +
- 'options, and union types in files importing Avatar/AvatarGroup.',
+ 'Renames static sizes written directly on imported Avatar and AvatarGroup ' +
+ 'JSX elements. Indirect values are left unchanged for manual migration.',
pr: '#2672',
};
-/** Import sources that provide the Astryx Avatar/AvatarGroup components. */
const IMPORT_SOURCES = new Set([
'@astryxdesign/core',
'@astryxdesign/core/Avatar',
@@ -53,10 +30,11 @@ const IMPORT_SOURCES = new Set([
'@xds/core/AvatarGroup',
]);
-/** Component names whose `size` prop is renamed. */
-const TARGET_IMPORTED_NAMES = new Set(['Avatar', 'AvatarGroup']);
+const COMPONENT_PROPS = new Map([
+ ['Avatar', new Set(['size'])],
+ ['AvatarGroup', new Set(['size'])],
+]);
-/** Old → new size-name mapping. */
const RENAMES = new Map([
['tiny', 'xsm'],
['xsmall', 'sm'],
@@ -65,46 +43,38 @@ const RENAMES = new Map([
['large', 'xl'],
]);
-/**
- * Ambiguous names — common words that must ONLY be renamed in a precise
- * context. `tiny`/`xsmall` are omitted because they are unique to Avatar's
- * scale; their presence in a collection proves it is an Avatar size enum.
- */
-const AMBIGUOUS = new Set(['small', 'medium', 'large']);
-
-/** Names that appear only in Avatar's scale — safe signals of Avatar sizing. */
-const UNIQUE = new Set(['tiny', 'xsmall']);
-
-/**
- * Rename a string-literal node if its value is an old size name.
- * Unwraps `'small' as const`. In non-precise contexts, ambiguous names are
- * skipped. Returns true when a rename occurred.
- */
-function renameValue(/** @type {any} */ node, {precise = false} = {}) {
- if (!node) return false;
- const target = node.type === 'TSAsExpression' ? node.expression : node;
- const isString =
- target.type === 'StringLiteral' || target.type === 'Literal';
- if (!isString || typeof target.value !== 'string') return false;
- const replacement = RENAMES.get(target.value);
- if (!replacement) return false;
- if (!precise && AMBIGUOUS.has(target.value)) return false;
- target.value = replacement;
- if (target.raw) target.raw = undefined;
- return true;
+/** @param {string} name */
+function canonicalComponentName(name) {
+ return name.startsWith('XDS') ? name.slice(3) : name;
}
-/** Extract a plain string value from a literal-ish node, or null. */
-function literalString(/** @type {any} */ node) {
- const target = node?.type === 'TSAsExpression' ? node.expression : node;
+/** @param {any} node @returns {boolean} */
+function renameStaticValue(node) {
+ if (!node) return false;
if (
- target &&
- (target.type === 'StringLiteral' || target.type === 'Literal') &&
- typeof target.value === 'string'
+ node.type === 'TSAsExpression' ||
+ node.type === 'TSSatisfiesExpression' ||
+ node.type === 'TypeCastExpression' ||
+ node.type === 'ParenthesizedExpression'
) {
- return target.value;
+ return renameStaticValue(node.expression);
}
- return null;
+ if (node.type === 'ConditionalExpression') {
+ const consequentChanged = renameStaticValue(node.consequent);
+ const alternateChanged = renameStaticValue(node.alternate);
+ return consequentChanged || alternateChanged;
+ }
+ if (
+ (node.type !== 'StringLiteral' && node.type !== 'Literal') ||
+ typeof node.value !== 'string'
+ ) {
+ return false;
+ }
+ const replacement = RENAMES.get(node.value);
+ if (!replacement) return false;
+ node.value = replacement;
+ if (node.raw) node.raw = undefined;
+ return true;
}
/**
@@ -117,122 +87,23 @@ export default function transformer(file, api) {
const root = j(file.source);
let hasChanges = false;
- // Track alias-aware local names for the target components.
- const targetLocals = new Set();
- root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {
- if (!IMPORT_SOURCES.has(path.node.source.value)) return;
- for (const spec of path.node.specifiers ?? []) {
- if (
- spec.type === 'ImportSpecifier' &&
- TARGET_IMPORTED_NAMES.has(spec.imported.name)
- ) {
- targetLocals.add(spec.local.name);
- }
- }
- });
-
- if (targetLocals.size === 0) return undefined;
-
- function renameArrayElements(/** @type {any} */ node) {
- let arr = node;
- if (arr.type === 'TSAsExpression') arr = arr.expression;
- if (arr.type !== 'ArrayExpression') return;
- // If the array contains a name unique to Avatar's scale (tiny/xsmall), the
- // whole collection is unambiguously the Avatar size enum, so it is safe to
- // rename the ambiguous members too. Otherwise stay conservative.
- const precise = arr.elements.some((/** @type {any} */ el) => UNIQUE.has(literalString(el)));
- for (const el of arr.elements) {
- if (renameValue(el, {precise})) hasChanges = true;
- }
- }
-
- // 1. `size` JSX attributes on target components — PRECISE (component known),
- // so all five names, including the ambiguous ones, are renamed here.
- root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {
- const name = path.node.name;
- const componentName = name.type === 'JSXIdentifier' ? name.name : null;
- if (!componentName || !targetLocals.has(componentName)) return;
-
- for (const attr of path.node.attributes) {
- if (attr.type !== 'JSXAttribute' || attr.name?.name !== 'size') continue;
- const value = attr.value;
-
- // size="small"
- if (renameValue(value, {precise: true})) {
- hasChanges = true;
- continue;
- }
- if (
- value &&
- value.type === 'JSXExpressionContainer' &&
- value.expression
- ) {
- // size={'small'}
- if (renameValue(value.expression, {precise: true})) {
- hasChanges = true;
- continue;
- }
- // size={cond ? 'small' : 'large'}
- if (value.expression.type === 'ConditionalExpression') {
- if (renameValue(value.expression.consequent, {precise: true}))
- hasChanges = true;
- if (renameValue(value.expression.alternate, {precise: true}))
- hasChanges = true;
- }
- }
- }
- });
-
- // 2. Object properties keyed `size` (or `*Size`) + Storybook `options`
- // arrays — NON-PRECISE (the component isn't known here), so only the
- // unique names tiny/xsmall are renamed.
- const PropertyType = j.ObjectProperty ?? j.Property;
- root.find(PropertyType).forEach((/** @type {any} */ path) => {
- const key = path.node.key;
- const keyName =
- key.type === 'Identifier'
- ? key.name
- : key.type === 'StringLiteral' || key.type === 'Literal'
- ? key.value
- : null;
- if (typeof keyName !== 'string') return;
-
- const lower = keyName.toLowerCase();
- if (lower !== 'size' && !lower.endsWith('size')) return;
-
- const value = path.node.value;
- // size: 'tiny'
- if (renameValue(value)) {
- hasChanges = true;
- return;
- }
- // size: { control: 'select', options: ['tiny', ...] }
- if (value.type === 'ObjectExpression') {
- const optionsProp = value.properties.find(
- (/** @type {any} */ p) => p.key && (p.key.name === 'options' || p.key.value === 'options'),
- );
- if (optionsProp) renameArrayElements(optionsProp.value);
- }
- // size: ['tiny', 'xsmall', ...]
- renameArrayElements(value);
- });
-
- // 3. Union-type literals — NON-PRECISE, so only the unique names tiny/xsmall
- // are renamed. This avoids corrupting unrelated unions that happen to use
- // common words like 'medium' (e.g. a priority or breakpoint type) in a
- // file that also imports Avatar.
- root.find(j.TSLiteralType).forEach((/** @type {any} */ path) => {
- if (renameValue(path.node.literal)) hasChanges = true;
- });
-
- // 4. Standalone array literals whose members are exactly the Avatar size
- // scale (identified by the presence of a unique name like tiny/xsmall) —
- // e.g. `(['tiny', 'xsmall', 'small', 'medium', 'large'] as const).map(...)`
- // used to render every size. The unique name proves the whole array is the
- // Avatar enum, so its ambiguous members can be renamed safely.
- root.find(j.ArrayExpression).forEach((/** @type {any} */ path) => {
- renameArrayElements(path.node);
- });
+ transformProp(
+ root,
+ j,
+ {
+ matchesImport: source => IMPORT_SOURCES.has(source),
+ components: COMPONENT_PROPS,
+ normalizeComponentName: canonicalComponentName,
+ },
+ propPath => {
+ const prop = propPath.node;
+ const value =
+ prop.value?.type === 'JSXExpressionContainer'
+ ? prop.value.expression
+ : prop.value;
+ if (renameStaticValue(value)) hasChanges = true;
+ },
+ );
if (!hasChanges) return undefined;
return root.toSource({quote: 'single'});