An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): layout.components codemod reads a const-bound default-exported config (#8250)
EJ Hammond4f9bdd782383
diff --git a/.changeset/layout-codemod-const-config.md b/.changeset/layout-codemod-const-config.mdnew file mode 100644index 0000000000..10593fa458--- /dev/null+++ b/.changeset/layout-codemod-const-config.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx upgrade` no longer reports an error on an `astryx.config` written as `const config = {...}; export default config;`, the shape generated configs use. The `migrate-layout-components-to-experimental` codemod now follows a default-exported identifier to its top-level `const` binding when the binding is not exported any other way and nothing else references it, so a config without `layout` is left unchanged and one with `layout.components` is migrated.++@ejhammonddiff --git a/packages/cli/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs b/packages/cli/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjsindex 5d10e7570d..efc4de0a72 100644--- a/packages/cli/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs+++ b/packages/cli/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs@@ -162,6 +162,52 @@ export default createConfig({});});+describe('migrate-layout-components-to-experimental — default export by const reference', () => {+ it('returns null for a generated config with no layout key', async () => {+ const input = `// Generated Astryx config.+const config = {+ integrations: ["@acme/ui"],+ issuesUrl: "https://example.com/issues",+};++export default config;+`;+ const output = await applyTransform(input);+ expect(output).toBeNull();+ });++ it('migrates layout.components in a const-bound object literal', async () => {+ const input = `const config = {+ layout: { components: { KpiCard: '@/components/KpiCard' } },+};++export default config;+`;+ const output = await applyTransform(input);+ expect(output).not.toBeNull();+ expect(output).toMatch(/const config = \{/);+ expect(output).toContain('export default config;');+ expect(output).toMatch(/experimental:\s*\{\s*xle:\s*\{\s*components:\s*\{\s*KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);+ expect(output).not.toMatch(/layout\s*:/);+ });++ it('migrates layout.components in a const-bound createConfig({ ... }) call', async () => {+ const input = `import { createConfig } from '@astryxdesign/cli';++const config = createConfig({+ layout: { components: { KpiCard: '@/components/KpiCard' } },+});++export default config;+`;+ const output = await applyTransform(input);+ expect(output).not.toBeNull();+ expect(output).toContain('createConfig(');+ expect(output).toMatch(/KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);+ expect(output).not.toMatch(/layout\s*:/);+ });+});+describe('migrate-layout-components-to-experimental — placement', () => {it('adds xle to a pre-existing experimental (no xle)', async () => {const input = `export default {@@ -239,8 +285,69 @@ export default {await expect(applyTransform(input)).rejects.toThrow(/cannot be safely migrated/);});- it('throws on a non-object default export (variable reference)', async () => {- const input = `const config = { layout: { components: {} } };+ it('throws when the default export is an identifier with no top-level const binding', async () => {+ const input = `import config from './base-config.mjs';+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when a const-bound config is mutated after its declaration', async () => {+ const input = `const config = {};+config.layout = { components: { KpiCard: '@/components/KpiCard' } };+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when a const-bound config is passed to another call', async () => {+ const input = `const config = {};+Object.assign(config, { layout: { components: { KpiCard: '@/components/KpiCard' } } });+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when a const-bound config is aliased', async () => {+ const input = `const config = {};+const alias = config;+alias.layout = { components: { KpiCard: '@/components/KpiCard' } };+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when the const-bound config is also exported with export const', async () => {+ const input = `export const config = {+ layout: { components: { KpiCard: '@/components/KpiCard' } },+};+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when the const-bound config is also exported by name', async () => {+ const input = `const config = {+ layout: { components: { KpiCard: '@/components/KpiCard' } },+};+export { config };+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when the const-bound config is also exported under another name', async () => {+ const input = `const config = {+ layout: { components: { KpiCard: '@/components/KpiCard' } },+};+export { config as baseConfig };+export default config;+`;+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);+ });++ it('throws when the default export is bound by a reassignable let', async () => {+ const input = `let config = { layout: { components: { KpiCard: '@/components/KpiCard' } } };export default config;`;await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);@@ -306,6 +413,113 @@ describe('migrate-layout-components-to-experimental — end-to-end via runConfig}});+ it('leaves a generated const-bound config with no layout untouched and reports no error', async () => {+ const {runConfigCodemod} = await import('../../../run-codemod.mjs');+ const {default: transform, meta} = await import(+ '../migrate-layout-components-to-experimental.mjs'+ );+ const jscodeshift = (await import('jscodeshift')).default;++ const originalCwd = process.cwd();+ const tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-v013-codemod-test-'),+ );+ const configSource = `// Generated Astryx config.+const config = {+ integrations: ["@acme/ui"],+ issuesUrl: "https://example.com/issues",+};++export default config;+`;+ try {+ process.chdir(tmpDir);+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer'}),+ );+ fs.writeFileSync(path.join(tmpDir, 'astryx.config.mjs'), configSource);++ const entry = {+ id: 'migrate-layout-components-to-experimental',+ type: 'config',+ codemod: {title: meta.title, transform},+ package: 'core',+ version: '0.1.3',+ };+ const log = {+ step() {},+ info() {},+ success() {},+ warn() {},+ error() {},+ message() {},+ };+ const result = runConfigCodemod(entry, {apply: true, log, jscodeshift});++ expect(result.errors).toHaveLength(0);+ expect(result.filesChanged).toBe(0);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),+ ).toBe(configSource);+ } finally {+ process.chdir(originalCwd);+ fs.rmSync(tmpDir, {recursive: true, force: true});+ }+ });++ it('reports an error, not success, for a mutated const-bound config', async () => {+ const {runConfigCodemod} = await import('../../../run-codemod.mjs');+ const {default: transform, meta} = await import(+ '../migrate-layout-components-to-experimental.mjs'+ );+ const jscodeshift = (await import('jscodeshift')).default;++ const originalCwd = process.cwd();+ const tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-v013-codemod-test-'),+ );+ const configSource = `const config = {};+config.layout = { components: { KpiCard: '@/components/KpiCard' } };+export default config;+`;+ try {+ process.chdir(tmpDir);+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'consumer'}),+ );+ fs.writeFileSync(path.join(tmpDir, 'astryx.config.mjs'), configSource);++ const entry = {+ id: 'migrate-layout-components-to-experimental',+ type: 'config',+ codemod: {title: meta.title, transform},+ package: 'core',+ version: '0.1.3',+ };+ const log = {+ step() {},+ info() {},+ success() {},+ warn() {},+ error() {},+ message() {},+ };+ const result = runConfigCodemod(entry, {apply: true, log, jscodeshift});++ expect(result.filesChanged).toBe(0);+ expect(result.errors).toHaveLength(1);+ expect(result.errors[0].error).toMatch(/statically analyze/);+ expect(+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),+ ).toBe(configSource);+ } finally {+ process.chdir(originalCwd);+ fs.rmSync(tmpDir, {recursive: true, force: true});+ }+ });+it('surfaces a thrown bail as a structured error through runConfigCodemod', async () => {const {runConfigCodemod} = await import('../../../run-codemod.mjs');const {default: transform, meta} = await import(diff --git a/packages/cli/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs b/packages/cli/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjsindex f538a7da6f..b26697aff4 100644--- a/packages/cli/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs+++ b/packages/cli/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs@@ -28,10 +28,14 @@* - object `{ from, description?, default? }` → carried over UNCHANGED* (from/description/default preserved, key order preserved).*- * The transform recognizes the config default export as EITHER a bare object- * literal (`export default { ... }`) or a `createConfig({ ... })` call wrapping- * an object literal (`export default createConfig({ ... })`). Anything else is- * not statically analyzable and the transform THROWS with a clear+ * The transform recognizes the config default export as a bare object literal+ * (`export default { ... }`), a `createConfig({ ... })` call wrapping an object+ * literal (`export default createConfig({ ... })`), or an identifier bound by a+ * top-level `const` to either form (`const config = { ... }; export default+ * config;`, the shape generated configs use) when the binding is not+ * exported any other way and the default export is its only reference, so+ * nothing can mutate the object after its declaration. Anything else is not statically analyzable and the transform+ * THROWS with a clear* migrate-manually message (the unified config-codemod contract has no* structured-error return — `runConfigCodemod` surfaces a thrown `err.message`* as `{file, codemod, error}`).@@ -76,10 +80,16 @@ export default function transformer(file, api) {const declaration = defaultExports.paths()[0].node.declaration;- // Resolve the config object literal from either form:+ // Resolve the config object literal from any supported form:// export default { ... }// export default createConfig({ ... })- const configObject = resolveConfigObject(j, declaration);+ // const config = { ... } | createConfig({ ... }); export default config;+ const configObject = resolveConfigObject(+ j,+ j.Identifier.check(declaration)+ ? findTopLevelConstInit(j, root, declaration)+ : declaration,+ );if (!configObject) {throw new Error(`could not statically analyze astryx config; ${MANUAL}`,@@ -179,6 +189,78 @@ function resolveConfigObject(/** @type {any} */ j, /** @type {any} */ declaratioreturn null;}+/**+ * Find the initializer of the top-level, non-exported `const <name> = <init>`+ * declaration that the default-exported identifier refers to. `let`/`var`+ * bindings can be reassigned, so they are not treated as statically+ * analyzable. Neither is a binding exported any other way (`export const`,+ * `export { name }`, `export { name as other }`), since another module could+ * import and mutate it, nor one referenced anywhere besides its declaration+ * and the default export: a member write, an alias or a call argument could+ * change the object after its initializer. A named export specifier is such a+ * reference, so `hasOtherReference` rejects it.+ * @returns {any} the initializer node, or null if there is no such binding+ */+function findTopLevelConstInit(/** @type {any} */ j, /** @type {any} */ root, /** @type {any} */ exported) {+ const name = exported.name;+ for (const statement of root.get().node.program.body) {+ // `export const` is skipped on purpose: another module can import the+ // binding and mutate the object.+ if (+ !j.VariableDeclaration.check(statement) ||+ statement.kind !== 'const'+ ) {+ continue;+ }+ for (const declarator of statement.declarations) {+ if (+ j.VariableDeclarator.check(declarator) &&+ j.Identifier.check(declarator.id) &&+ declarator.id.name === name+ ) {+ return hasOtherReference(j, root, name, [declarator.id, exported])+ ? null+ : declarator.init ?? null;+ }+ }+ }+ return null;+}++/**+ * Whether any identifier named `name`, other than the `allowed` nodes, could+ * refer to the binding. Non-computed member properties (`x.name`) and object+ * keys (`{ name: 1 }`) name a property, not the binding, so they don't count;+ * every other occurrence (including a shadowing one) does.+ * @returns {boolean}+ */+function hasOtherReference(/** @type {any} */ j, /** @type {any} */ root, /** @type {string} */ name, /** @type {any[]} */ allowed) {+ return root+ .find(j.Identifier, {name})+ .some((/** @type {any} */ path) => {+ const node = path.node;+ if (allowed.includes(node)) return false;+ const parent = path.parent?.node;+ if (+ (j.MemberExpression.check(parent) ||+ j.OptionalMemberExpression.check(parent)) &&+ parent.property === node &&+ !parent.computed+ ) {+ return false;+ }+ if (+ (j.ObjectProperty.check(parent) || j.Property.check(parent)) &&+ parent.key === node &&+ !parent.computed &&+ !parent.shorthand+ ) {+ return false;+ }+ return true;+ });+}+/*** Find a (non-computed, non-spread) property on an object literal by key name.* Supports Identifier and string-literal keys.