Skip to content

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

TypeScript

fix(cli): only migrate theme-shaped objects proven to be Astryx themes (#7980)

EJ Hammond3dd95a046047
diff --git a/.changeset/theme-surface-codemod-look-alikes.md b/.changeset/theme-surface-codemod-look-alikes.md
new file mode 100644
index 0000000000..256438fe56
--- /dev/null
+++ b/.changeset/theme-surface-codemod-look-alikes.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx upgrade` to 0.7 no longer renames component keys in a look-alike theme object that is not an Astryx theme, such as another library's `{name, components: {checkbox, radio, textarea}}` theme. A theme object with no `defineTheme()` call or Astryx theme type is migrated only when it is the binding a same-stem theme descriptor declares (`brandTheme` exported from `brandTheme.ts` beside `brandTheme.doc.mjs`). (#7980)
+
+@ejhammond
diff --git a/packages/cli/assets/codemods/transform-prop.mjs b/packages/cli/assets/codemods/transform-prop.mjs
index 2da71b9aaa..d75b475a02 100644
--- a/packages/cli/assets/codemods/transform-prop.mjs
+++ b/packages/cli/assets/codemods/transform-prop.mjs
@@ -1,27 +1,47 @@
// 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.
+ * Find imported components, resolve their local names (including aliases and
+ * namespace members) at a use site, 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 {{
+ * `transformProp` intentionally stops at the JSX boundary. It does not follow
+ * variables, helper calls, object spreads, wrapper components, or types. The
+ * resolver it is built on (`importedComponents`, `resolveImportedComponent`,
+ * `isModuleBinding`) is exported for transforms that prove other use sites.
+ */
+
+/**
+ * @typedef {{
* matchesImport: (source: string) => boolean,
* components: ReadonlyMap<string, ReadonlySet<string>>,
* normalizeComponentName?: (name: string) => string,
- * }} options
- * @param {(propPath: any, context: {component: string, localName: string}) => void} visit
+ * }} ImportOptions
*/
-export function transformProp(root, j, options, visit) {
+
+/**
+ * @typedef {{
+ * direct: Map<string, {component: string, props: ReadonlySet<string>}>,
+ * namespaces: Set<string>,
+ * normalize: (name: string) => string,
+ * components: ReadonlyMap<string, ReadonlySet<string>>,
+ * }} ImportedComponents
+ */
+
+/**
+ * Local names bound by accepted runtime imports: named, aliased and default
+ * component imports, and namespace imports.
+ * @param {any} root jscodeshift collection for one source file
+ * @param {any} j configured jscodeshift instance
+ * @param {ImportOptions} options
+ * @returns {ImportedComponents}
+ */
+export function importedComponents(root, j, options) {
const normalize = options.normalizeComponentName ?? (name => name);
- /** @type {Map<string, {component: string, props: ReadonlySet<string>}>} */
- const directBindings = new Map();
+ /** @type {ImportedComponents['direct']} */
+ const direct = new Map();
/** @type {Set<string>} */
- const namespaceBindings = new Set();
+ const namespaces = new Set();
root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {
const source = importPath.node.source.value;
@@ -46,53 +66,83 @@ export function transformProp(root, j, options, visit) {
const component = normalize(importedName);
const props = options.components.get(component);
if (!props) continue;
- directBindings.set(specifier.local?.name ?? importedName, {
- component,
- props,
- });
+ direct.set(specifier.local?.name ?? importedName, {component, props});
} else if (specifier.type === 'ImportDefaultSpecifier' && subpathProps) {
- directBindings.set(specifier.local.name, {
+ direct.set(specifier.local.name, {
component: subpathName,
props: subpathProps,
});
} else if (specifier.type === 'ImportNamespaceSpecifier') {
- namespaceBindings.add(specifier.local.name);
+ namespaces.add(specifier.local.name);
}
}
});
- if (directBindings.size === 0 && namespaceBindings.size === 0) return;
+ return {direct, namespaces, normalize, components: options.components};
+}
- root.find(j.JSXOpeningElement).forEach((/** @type {any} */ jsxPath) => {
- const name = jsxPath.node.name;
- let localName;
- let component;
- let props;
+/**
+ * True when `localName` at `path` resolves to a module-scope binding. A
+ * parameter or local declaration with the same name shadows the import.
+ * @param {any} path any node path inside the file
+ * @param {string} localName
+ */
+export function isModuleBinding(path, localName) {
+ return path.scope?.lookup(localName)?.path.node.type === 'Program';
+}
- 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;
- }
+/**
+ * Resolve a component reference (`Card`, `Lib.Card`, or their JSX forms) to
+ * the imported component it names at `scopePath`, or null.
+ * @param {any} nameNode Identifier, JSXIdentifier, MemberExpression, or JSXMemberExpression
+ * @param {any} scopePath the path whose scope the reference is evaluated in
+ * @param {ImportedComponents} imports
+ * @returns {{component: string, props: ReadonlySet<string>, localName: string} | null}
+ */
+export function resolveImportedComponent(nameNode, scopePath, imports) {
+ let localName;
+ let binding;
+ if (nameNode?.type === 'JSXIdentifier' || nameNode?.type === 'Identifier') {
+ localName = nameNode.name;
+ binding = imports.direct.get(localName);
+ } else if (
+ (nameNode?.type === 'JSXMemberExpression' ||
+ (nameNode?.type === 'MemberExpression' && !nameNode.computed)) &&
+ (nameNode.object?.type === 'JSXIdentifier' ||
+ nameNode.object?.type === 'Identifier') &&
+ (nameNode.property?.type === 'JSXIdentifier' ||
+ nameNode.property?.type === 'Identifier') &&
+ imports.namespaces.has(nameNode.object.name)
+ ) {
+ localName = nameNode.object.name;
+ const component = imports.normalize(nameNode.property.name);
+ const props = imports.components.get(component);
+ if (props) binding = {component, props};
+ }
+ if (!binding || !isModuleBinding(scopePath, localName)) return null;
+ return {...binding, localName};
+}
- // 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;
+/**
+ * @param {any} root jscodeshift collection for one source file
+ * @param {any} j configured jscodeshift instance
+ * @param {ImportOptions} options
+ * @param {(propPath: any, context: {component: string, localName: string}) => void} visit
+ */
+export function transformProp(root, j, options, visit) {
+ const imports = importedComponents(root, j, options);
+ if (imports.direct.size === 0 && imports.namespaces.size === 0) return;
+
+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ jsxPath) => {
+ // Only JSX tags whose root binding resolves to Program are usages of the
+ // import discovered above.
+ const resolved = resolveImportedComponent(
+ jsxPath.node.name,
+ jsxPath,
+ imports,
+ );
+ if (!resolved) return;
+ const {component, props, localName} = resolved;
for (let index = 0; index < jsxPath.node.attributes.length; index++) {
const attribute = jsxPath.node.attributes[index];
diff --git a/packages/cli/assets/codemods/transform-prop.test.mjs b/packages/cli/assets/codemods/transform-prop.test.mjs
index 95a0e21e6d..1e096e2753 100644
--- a/packages/cli/assets/codemods/transform-prop.test.mjs
+++ b/packages/cli/assets/codemods/transform-prop.test.mjs
@@ -2,7 +2,11 @@
import {describe, expect, it} from 'vitest';
import jscodeshift from 'jscodeshift';
-import {transformProp} from './transform-prop.mjs';
+import {
+ importedComponents,
+ resolveImportedComponent,
+ transformProp,
+} from './transform-prop.mjs';
const j = jscodeshift.withParser('tsx');
const components = new Map([
@@ -92,4 +96,35 @@ const b = <Group tone="old" size="old" />;`);
expect(output).toContain('<Widget size="old" migratedtone="old"');
expect(output).toContain('<Group tone="old" migratedsize="old"');
});
+
+ it('resolves non-JSX references through the same import and shadow rules', () => {
+ const root = j(`import {Widget as Card} from '@example/core';
+import * as Lib from '@example/core';
+const a = Card;
+const b = Lib.Group;
+function shadow(Card, Lib) {
+ return [Card, Lib.Group];
+}`);
+ const imports = importedComponents(root, j, {
+ matchesImport: value => /^@example\/core(?:\/|$)/.test(value),
+ components,
+ });
+ const resolved = root
+ .find(j.VariableDeclarator)
+ .paths()
+ .map(
+ path =>
+ resolveImportedComponent(path.node.init, path, imports)?.component,
+ );
+ expect(resolved).toEqual(['Widget', 'Group']);
+ const shadowed = root
+ .find(j.ArrayExpression)
+ .paths()
+ .flatMap(path =>
+ path.node.elements.map(element =>
+ resolveImportedComponent(element, path, imports),
+ ),
+ );
+ expect(shadowed).toEqual([null, null]);
+ });
});
diff --git a/packages/cli/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs b/packages/cli/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs
index 8df169d86f..9a8ca0a647 100644
--- a/packages/cli/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs
@@ -1,6 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {afterEach, describe, expect, it} from 'vitest';
import jscodeshift from 'jscodeshift';
import manifest from '../index.mjs';
import transform, {
@@ -16,6 +19,38 @@ function apply(source, filePath = 'theme.ts') {
return transform({source, path: filePath}, api) ?? source;
}
+/** A proven theme: an object passed to Astryx's imported defineTheme(). */
+function defined(components) {
+ return `${IMPORT}export default defineTheme({name: 'brand', components: ${components}});`;
+}
+
+const THEME_DOC = `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */
+export default {
+ type: 'theme',
+ name: 'brand',
+ displayName: 'Brand',
+ description: 'A brand theme.',
+ maintained: false,
+};
+`;
+
+const tempDirs = [];
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+});
+
+/** Write `files` into a fresh directory and return its path. */
+function folder(files) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-surface-'));
+ tempDirs.push(dir);
+ for (const [name, content] of Object.entries(files)) {
+ fs.writeFileSync(path.join(dir, name), content);
+ }
+ return dir;
+}
+
const EXPECTED_TARGETS = {
'base-table': 'table',
checkbox: 'checkbox-indicator',
@@ -60,7 +95,7 @@ describe('migrate-deprecated-theme-surface', () => {
'renames static target key %s to %s inside a components map',
(oldKey, newKey) => {
const output = apply(
- `export default {name: 'brand', components: {${JSON.stringify(oldKey)}: {base: {color: 'red'}}}};`,
+ defined(`{${JSON.stringify(oldKey)}: {base: {color: 'red'}}}`),
);
expect(output).not.toContain(`${JSON.stringify(oldKey)}:`);
@@ -103,12 +138,114 @@ export const theme = defineTheme({name: 'brand', components});`);
}
});
+ it('does not rewrite a look-alike theme object from another library', () => {
+ const input = `export const muiTheme = {
+ name: 'brand',
+ components: {checkbox: {root: {color: 'red'}}, radio: {root: {}}, textarea: {root: {}}},
+};`;
+ expect(apply(input, 'src/muiTheme.ts')).toBe(input);
+ });
+
+ it('does not take a file-level Astryx import as proof for a look-alike object', () => {
+ const input = `import {Button} from '@astryxdesign/core';
+export const editorTheme = {name: 'editor', components: {textarea: {root: {}}}};`;
+ expect(apply(input, 'src/editorTheme.ts')).toBe(input);
+ });
+
+ it('renames a direct theme object in a source its theme descriptor declares', () => {
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
+ const output = apply(
+ `export const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};`,
+ path.join(dir, 'brandTheme.ts'),
+ );
+ expect(output).toContain("'nav-icon':");
+ expect(output).not.toMatch(/navicon\s*:/);
+ });
+
+ it('renames only the declared theme binding in a described theme source', () => {
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
+ const output = apply(
+ `export const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};
+export const otherLibraryTheme = {
+ name: 'other',
+ components: {checkbox: {root: {}}, textarea: {root: {}}},
+};`,
+ path.join(dir, 'brandTheme.ts'),
+ );
+ expect(output).toContain("'nav-icon':");
+ expect(output).toContain(
+ 'components: {checkbox: {root: {}}, textarea: {root: {}}}',
+ );
+ expect(output).not.toContain('checkbox-indicator');
+ expect(output).not.toContain('text-area');
+ });
+
+ it('follows a local binding exported under the descriptor name', () => {
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
+ const output = apply(
+ `const theme = {name: 'brand', components: {navicon: {base: {}}}} as const;
+export {theme as brandTheme};`,
+ path.join(dir, 'brandTheme.ts'),
+ );
+ expect(output).toContain("'nav-icon':");
+ });
+
+ it('does not treat an unexported or nested same-named object as the declared theme', () => {
+ const dir = folder({'brandTheme.doc.mjs': THEME_DOC});
+ for (const input of [
+ `const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};`,
+ `export function make() {
+ const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};
+ return brandTheme;
+}`,
+ ]) {
+ expect(apply(input, path.join(dir, 'brandTheme.ts'))).toBe(input);
+ }
+ });
+
+ it('does not treat a descriptor for another stem or kind as theme proof', () => {
+ const input = `export const brandTheme = {name: 'brand', components: {navicon: {base: {}}}};`;
+ const otherStem = folder({'otherTheme.doc.mjs': THEME_DOC});
+ expect(apply(input, path.join(otherStem, 'brandTheme.ts'))).toBe(input);
+ const otherKind = folder({
+ 'brandTheme.doc.mjs': 'export default {name: "brand", props: []};\n',
+ });
+ expect(apply(input, path.join(otherKind, 'brandTheme.ts'))).toBe(input);
+ });
+
it('does not treat a defineTheme from another library as an Astryx theme', () => {
const input = `import {defineTheme} from 'other-ui';
export default defineTheme({components: {checkbox: {base: {color: 'red'}}}});`;
expect(apply(input)).toBe(input);
});
+ it.each([
+ [
+ 'named defineTheme',
+ `import {defineTheme} from '@astryxdesign/core';
+function unrelated(defineTheme) {
+ return defineTheme({name: 'fake', components: {checkbox: {root: {}}}});
+}`,
+ ],
+ [
+ 'aliased defineTheme',
+ `import {defineTheme as makeTheme} from '@astryxdesign/core';
+function unrelated() {
+ const makeTheme = otherLibrary.createTheme;
+ return makeTheme({name: 'fake', components: {checkbox: {root: {}}}});
+}`,
+ ],
+ [
+ 'namespace defineTheme',
+ `import * as Astryx from '@astryxdesign/core';
+function unrelated(Astryx) {
+ return Astryx.defineTheme({name: 'fake', components: {checkbox: {root: {}}}});
+}`,
+ ],
+ ])('does not treat a shadowed %s as an Astryx call', (_name, input) => {
+ expect(apply(input)).toBe(input);
+ });
+
it.each([
[
'an aliased defineTheme import',
@@ -141,9 +278,54 @@ const brand: DefineThemeInput = {name: 'brand', components: {navicon: {base: {}}
expect(output).not.toMatch(/navicon\s*:/);
});
+ it.each([
+ [
+ 'a locally redeclared named type',
+ `import type {DefineThemeInput} from '@astryxdesign/core';
+function unrelated() {
+ type DefineThemeInput = OtherTheme;
+ return {name: 'fake', components: {checkbox: {root: {}}}} satisfies DefineThemeInput;
+}`,
+ ],
+ [
+ 'an aliased type shadowed by a type parameter',
+ `import type {DefineThemeInput as Theme} from '@astryxdesign/core';
+function unrelated<Theme>(value: unknown) {
+ const theme: Theme = {name: 'fake', components: {checkbox: {root: {}}}};
+ return theme;
+}`,
+ ],
+ [
+ 'a namespace shadowed by a type parameter',
+ `import type * as Astryx from '@astryxdesign/core';
+function unrelated<Astryx>() {
+ return {name: 'fake', components: {checkbox: {root: {}}}} satisfies Astryx.DefineThemeInput;
+}`,
+ ],
+ [
+ 'a namespace shadowed by a local namespace',
+ `import * as Astryx from '@astryxdesign/core';
+function unrelated() {
+ namespace Astryx { export type DefineThemeInput = OtherTheme; }
+ return ({name: 'fake', components: {checkbox: {root: {}}}}) as Astryx.DefineThemeInput;
+}`,
+ ],
+ ])('does not treat %s as an Astryx theme type', (_name, input) => {
+ expect(apply(input)).toBe(input);
+ });
+
+ it('still recognizes an unshadowed theme type inside a function', () => {
+ const output =
+ apply(`import type {DefineThemeInput} from '@astryxdesign/core';
+function makeTheme<T>() {
+ return {components: {navicon: {base: {}}}} satisfies DefineThemeInput;
+}`);
+ expect(output).toContain("'nav-icon':");
+ });
+
it('renames a clear-icon alias with a TODO naming the owner scope it loses', () => {
const output = apply(
- `export default {name: 'brand', components: {'selector-clear-icon': {base: {color: 'red'}}}};`,
+ defined(`{'selector-clear-icon': {base: {color: 'red'}}}`),
);
expect(output).toContain("'input-clear-icon':");
expect(output).toContain(
@@ -155,10 +337,12 @@ const brand: DefineThemeInput = {name: 'brand', components: {navicon: {base: {}}
});
it('flags two clear-icon aliases that collapse onto the shared target', () => {
- const output = apply(`export default {name: 'brand', components: {
+ const output = apply(
+ defined(`{
'selector-clear-icon': {base: {color: 'red'}},
'date-input-clear-icon': {base: {color: 'blue'}},
-}};`);
+}`),
+ );
expect(output).toContain("'input-clear-icon':");
expect(output).toContain(
'merge deprecated theme target `date-input-clear-icon` into `input-clear-icon`',
@@ -312,7 +496,9 @@ const theme = {name: 'brand', components: {[oldTarget]: {base: {color: 'red'}}}}
});
it('is byte-idempotent after JavaScript and CSS migration', () => {
- const js = `export default {name: 'brand', components: {statusdot: {base: {color: 'red'}}, 'selector-clear-icon': {base: {color: 'red'}}}};`;
+ const js = defined(
+ `{statusdot: {base: {color: 'red'}}, 'selector-clear-icon': {base: {color: 'red'}}}`,
+ );
const css = '.astryx-textarea.sm {}';
const jsOnce = apply(js);
const cssOnce = apply(css, 'theme.css');
diff --git a/packages/cli/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs b/packages/cli/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs
index 096505bb55..d3f1db35f2 100644
--- a/packages/cli/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs
@@ -5,19 +5,28 @@
*
* Static keys directly inside a theme's `components` object move to their
* canonical target. A theme is a `defineTheme()` call imported from Astryx, an
- * object typed as an Astryx theme (annotation, `as`, or `satisfies`), or a
- * direct theme object with a static `name` whose component entries are style
- * objects. CSS selectors move the same target classes, keep the owner scope of
- * the per-component clear-icon aliases, and replace target-qualified bare
- * prop/state classes with reflected `data-*` selectors using the final 0.6
- * runtime contract. A known bare class that cannot be classified for its target
- * gets a TODO. Dynamic theme keys, unqualified classes, declarations, comments,
+ * object typed as an Astryx theme (annotation, `as`, or `satisfies`), or the
+ * direct theme object a same-stem theme descriptor (`<stem>.doc.mjs`) declares:
+ * the top-level binding exported as `<stem>`, with a static `name` and
+ * component entries that are style objects. Shape alone is not proof: a
+ * look-alike object anywhere else, including another object in the same theme
+ * source, is left unchanged. CSS selectors move the same target classes, keep
+ * the owner scope of the per-component clear-icon aliases, and replace
+ * target-qualified bare prop/state classes with reflected `data-*` selectors
+ * using the final 0.6 runtime contract. A known bare class that cannot be
+ * classified for its target gets a TODO. Dynamic theme keys, unqualified classes, declarations, comments,
* and strings containing CSS are left for manual review.
*/
+import * as fs from 'node:fs';
import path from 'node:path';
import postcss from 'postcss';
import selectorParser from 'postcss-selector-parser';
+import {readThemeDescriptorValue} from '../../../../foundation/discovery/theme-discovery.mjs';
+import {
+ importedComponents,
+ resolveImportedComponent,
+} from '../../transform-prop.mjs';
import {migrateAstryxThemeSelectors} from '../v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs';
import {
V06_THEME_SELECTOR_DYNAMIC_AXES,
@@ -338,15 +347,88 @@ const TS_WRAPPERS = new Set([
]);
/**
- * Local names that refer to Astryx's `defineTheme`, its theme types, or an
- * Astryx namespace import.
- * @param {any} root @param {any} j
+ * The export name a same-stem theme descriptor beside this file declares
+ * (`brandTheme` for `brandTheme.ts` beside `brandTheme.doc.mjs`), or null. The
+ * descriptor is read statically, never executed; an unreadable or non-theme
+ * descriptor is not proof.
+ * @param {string} filePath
+ * @returns {string | null}
+ */
+function describedThemeExportName(filePath) {
+ const stem = path.basename(filePath, path.extname(filePath));
+ const docPath = path.join(path.dirname(filePath), `${stem}.doc.mjs`);
+ if (!fs.existsSync(docPath)) return null;
+ try {
+ return readThemeDescriptorValue(docPath, `Theme descriptor ${docPath}`)
+ .type === 'theme'
+ ? stem
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Top-level local names this module exports under `exportName`: an exported
+ * declaration of that name, or a source-less `export {local as exportName}`.
+ * @param {any} root @param {any} j @param {string} exportName
+ */
+function localNamesExportedAs(root, j, exportName) {
+ /** @type {Set<string>} */
+ const locals = new Set();
+ root
+ .find(j.ExportNamedDeclaration)
+ .forEach((/** @type {any} */ exportPath) => {
+ const node = exportPath.node;
+ if (node.exportKind === 'type' || node.source) return;
+ for (const declarator of node.declaration?.declarations ?? []) {
+ if (declarator.id?.name === exportName) locals.add(exportName);
+ }
+ for (const specifier of node.specifiers ?? []) {
+ const exported = specifier.exported?.name ?? specifier.exported?.value;
+ const local = specifier.local?.name ?? specifier.local?.value;
+ if (
+ specifier.exportKind !== 'type' &&
+ exported === exportName &&
+ typeof local === 'string'
+ ) {
+ locals.add(local);
+ }
+ }
+ });
+ return locals;
+}
+
+/**
+ * Astryx's `defineTheme` imports (resolved at each call site, so a shadowing
+ * parameter or local never counts), its theme types, an Astryx namespace
+ * import, and the binding a theme descriptor declares.
+ * @param {any} root @param {any} j @param {string} filePath
*/
-function astryxThemeBindings(root, j) {
+function astryxThemeBindings(root, j, filePath) {
+ /** @type {Set<string> | undefined} */
+ let describedLocals;
const bindings = {
- defineTheme: new Set(),
+ defineTheme: importedComponents(root, j, {
+ matchesImport: source => ASTRYX_MODULE.test(source),
+ components: new Map([['defineTheme', new Set()]]),
+ }),
themeTypes: new Set(),
namespaces: new Set(),
+ /**
+ * Top-level locals exported under the descriptor's name. Read lazily:
+ * only a direct theme-shaped object needs the descriptor.
+ * @returns {Set<string>}
+ */
+ describedThemeLocals() {
+ if (describedLocals == null) {
+ const exportName = describedThemeExportName(filePath);
+ describedLocals = exportName
+ ? localNamesExportedAs(root, j, exportName)
+ : new Set();
+ }
+ return describedLocals;
+ },
};
root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {
const source = importPath.node.source?.value;
@@ -358,7 +440,6 @@ function astryxThemeBindings(root, j) {
bindings.namespaces.add(local);
} else if (specifier.type === 'ImportSpecifier') {
const imported = specifier.imported?.name ?? specifier.imported?.value;
- if (imported === 'defineTheme') bindings.defineTheme.add(local);
if (THEME_TYPE_NAMES.has(imported)) bindings.themeTypes.add(local);
}
}
@@ -379,20 +460,80 @@ function namesBinding(name, locals, namespaces, members) {
);
}
-/** @param {any} typeNode @param {ReturnType<typeof astryxThemeBindings>} bindings */
-function isAstryxThemeType(typeNode, bindings) {
+/** @param {any} typeNode @param {any} usePath @param {ReturnType<typeof astryxThemeBindings>} bindings */
+function isAstryxThemeType(typeNode, usePath, bindings) {
const node = typeNode?.typeAnnotation ?? typeNode;
- return (
- node?.type === 'TSTypeReference' &&
- namesBinding(
+ if (
+ node?.type !== 'TSTypeReference' ||
+ !namesBinding(
node.typeName,
bindings.themeTypes,
bindings.namespaces,
THEME_TYPE_NAMES,
)
+ ) {
+ return false;
+ }
+ const root =
+ node.typeName.type === 'Identifier' ? node.typeName : node.typeName.left;
+ return isModuleTypeBinding(usePath, root.name);
+}
+
+/** @param {any} statement @param {string} name */
+function statementDeclares(statement, name) {
+ const node =
+ statement?.type === 'ExportNamedDeclaration' ||
+ statement?.type === 'ExportDefaultDeclaration'
+ ? statement.declaration
+ : statement;
+ if (node?.id?.type === 'Identifier' && node.id.name === name) return true;
+ return (node?.declarations ?? []).some(
+ (/** @type {any} */ declarator) =>
+ declarator.id?.type === 'Identifier' && declarator.id.name === name,
);
}
+/**
+ * True when a type-position `name` at `path` can only mean the module-scope
+ * import: no enclosing type parameter, parameter, or block-level declaration
+ * (type alias, interface, enum, class, namespace, function, or variable)
+ * reuses the name. Anything this cannot rule out counts as shadowed.
+ * @param {any} path @param {string} name
+ */
+function isModuleTypeBinding(path, name) {
+ const valueScope = path.scope?.lookup(name);
+ if (valueScope != null && valueScope.path.node.type !== 'Program') {
+ return false;
+ }
+ for (let current = path; current != null; current = current.parent) {
+ const node = current.node;
+ if (node.type === 'Program') return true;
+ const typeParameters = node.typeParameters?.params ?? [];
+ if (
+ typeParameters.some(
+ (/** @type {any} */ parameter) =>
+ (parameter.name?.name ?? parameter.name) === name,
+ )
+ ) {
+ return false;
+ }
+ const statements =
+ node.type === 'SwitchCase'
+ ? node.consequent
+ : node.type !== 'ClassBody' && Array.isArray(node.body)
+ ? node.body
+ : [];
+ if (
+ statements.some((/** @type {any} */ statement) =>
+ statementDeclares(statement, name),
+ )
+ ) {
+ return false;
+ }
+ }
+ return false;
+}
+
/**
* True for a theme object whose shape alone identifies it: a static string
* `name` beside a `components` map whose entries are all style objects.
@@ -426,16 +567,45 @@ function isDirectThemeObject(node) {
);
}
+/**
+ * True when this object literal initializes the top-level binding that the
+ * file's theme descriptor declares, directly or through TypeScript wrappers.
+ * @param {any} objectPath @param {ReturnType<typeof astryxThemeBindings>} bindings
+ */
+function isDescribedThemeBinding(objectPath, bindings) {
+ let parent = objectPath.parent;
+ while (parent != null && TS_WRAPPERS.has(parent.node.type)) {
+ parent = parent.parent;
+ }
+ const declarator = parent?.node;
+ if (
+ declarator?.type !== 'VariableDeclarator' ||
+ declarator.id?.type !== 'Identifier'
+ ) {
+ return false;
+ }
+ const declaration = parent.parent;
+ const container = declaration?.parent?.node;
+ const topLevel =
+ container?.type === 'Program' ||
+ (container?.type === 'ExportNamedDeclaration' &&
+ declaration.parent.parent?.node.type === 'Program');
+ return topLevel && bindings.describedThemeLocals().has(declarator.id.name);
+}
+
/**
* True when this object literal is an Astryx theme: the argument of an
- * imported `defineTheme()`, typed as an Astryx theme, or a direct theme object.
+ * imported `defineTheme()`, typed as an Astryx theme, or the direct theme
+ * object a theme descriptor declares.
* @param {any} objectPath @param {ReturnType<typeof astryxThemeBindings>} bindings
*/
function isThemeRoot(objectPath, bindings) {
let child = objectPath;
let parent = objectPath.parent;
while (parent != null && TS_WRAPPERS.has(parent.node.type)) {
- if (isAstryxThemeType(parent.node.typeAnnotation, bindings)) return true;
+ if (isAstryxThemeType(parent.node.typeAnnotation, parent, bindings)) {
+ return true;
+ }
child = parent;
parent = parent.parent;
}
@@ -443,22 +613,20 @@ function isThemeRoot(objectPath, bindings) {
if (
node?.type === 'CallExpression' &&
node.arguments?.[0] === child.node &&
- namesBinding(
- node.callee,
- bindings.defineTheme,
- bindings.namespaces,
- new Set(['defineTheme']),
- )
+ resolveImportedComponent(node.callee, parent, bindings.defineTheme)
) {
return true;
}
if (
node?.type === 'VariableDeclarator' &&
- isAstryxThemeType(node.id?.typeAnnotation, bindings)
+ isAstryxThemeType(node.id?.typeAnnotation, parent, bindings)
) {
return true;
}
- return isDirectThemeObject(objectPath.node);
+ return (
+ isDirectThemeObject(objectPath.node) &&
+ isDescribedThemeBinding(objectPath, bindings)
+ );
}
/**
@@ -567,10 +735,10 @@ function addScopeTodo(property, oldKey, owner, j) {
];
}
-/** @param {string} source @param {any} j */
-function migrateStaticThemeKeys(source, j) {
+/** @param {string} source @param {string} filePath @param {any} j */
+function migrateStaticThemeKeys(source, filePath, j) {
const root = j(source);
- const bindings = astryxThemeBindings(root, j);
+ const bindings = astryxThemeBindings(root, j, filePath);
let changed = false;
root.find(j.ObjectExpression).forEach((/** @type {any} */ objectPath) => {
@@ -620,5 +788,5 @@ export default function migrateDeprecatedThemeSurface(file, api) {
const result = migrateCss(file.source, file.path);
return result === file.source ? undefined : result;
}
- return migrateStaticThemeKeys(file.source, api.jscodeshift);
+ return migrateStaticThemeKeys(file.source, file.path, api.jscodeshift);
}
diff --git a/packages/cli/assets/docs/tree/styling-advanced.doc.mjs b/packages/cli/assets/docs/tree/styling-advanced.doc.mjs
index 3088af3553..82ec41aaf4 100644
--- a/packages/cli/assets/docs/tree/styling-advanced.doc.mjs
+++ b/packages/cli/assets/docs/tree/styling-advanced.doc.mjs
@@ -142,7 +142,7 @@ const overrides = stylex.create({
},
{
type: 'prose',
- text: 'The upgrade treats a `components` map as a theme when it belongs to a `defineTheme()` call imported from Astryx, an object typed as an Astryx theme, or a theme object with a static `name` whose component entries are style objects. It leaves computed theme keys, unqualified classes, unknown consumer classes, declarations, comments, and CSS inside JavaScript or TypeScript strings unchanged. It adds `TODO(astryx upgrade)` when a map has both an old and a canonical key, and when a bare class Astryx once emitted has no known meaning on the target it qualifies. Review each TODO by hand.',
+ text: 'The upgrade treats a `components` map as a theme when it belongs to a `defineTheme()` call imported from Astryx, an object typed as an Astryx theme, or the theme object a same-stem theme descriptor (`<stem>.doc.mjs`) declares: the top-level binding exported as `<stem>`, with a static `name` and component entries that are style objects. A look-alike object anywhere else, such as a theme object from another library in the same file, is not an Astryx theme. It leaves computed theme keys, unqualified classes, unknown consumer classes, declarations, comments, and CSS inside JavaScript or TypeScript strings unchanged. It adds `TODO(astryx upgrade)` when a map has both an old and a canonical key, and when a bare class Astryx once emitted has no known meaning on the target it qualifies. Review each TODO by hand.',
},
],
},