@astryxdesign/cli 0.7.5-canary.04434e7 → 0.7.5-canary.05ead02

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +1 -1
  2. package/api/template/tokenizer-showcase.test.mjs +47 -0
  3. package/api/theme/build/build.mjs +9 -4
  4. package/api/upgrade/_adapter.d.mts +47 -2
  5. package/api/upgrade/_adapter.mjs +58 -2
  6. package/api/upgrade/run/failure-receipt.test.mjs +57 -0
  7. package/api/upgrade/run/outcomes.test.mjs +646 -0
  8. package/api/upgrade/run/run.d.mts +36 -0
  9. package/api/upgrade/run/run.mjs +509 -45
  10. package/api/upgrade/upgrade.doc.mjs +2 -2
  11. package/api/upgrade/upgrade.type.d.mts +24 -0
  12. package/api/upgrade/upgrade.type.mjs +15 -3
  13. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  14. package/assets/codemods/integration-runner.mjs +7 -1
  15. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  16. package/assets/codemods/outcome.mjs +79 -0
  17. package/assets/codemods/outcome.test.mjs +40 -0
  18. package/assets/codemods/parse.mjs +94 -0
  19. package/assets/codemods/run-codemod.mjs +92 -2
  20. package/assets/codemods/runner.mjs +38 -5
  21. package/assets/codemods/transforms/next/__tests__/migrate-codeblock-tokenizer-to-language.test.mjs +130 -0
  22. package/assets/codemods/transforms/next/index.mjs +11 -1
  23. package/assets/codemods/transforms/next/migrate-codeblock-tokenizer-to-language.mjs +315 -0
  24. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  25. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  26. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  27. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +24 -4
  28. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +44 -10
  29. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +6 -3
  30. package/assets/docs/author-a-theme.doc.mjs +2 -1
  31. package/assets/docs/icons.doc.mjs +24 -1
  32. package/assets/docs/tree/template-styles.doc.mjs +1 -1
  33. package/assets/docs/tree/tokens-color.doc.mjs +145 -1
  34. package/assets/docs/tree/tokens.doc.mjs +1 -1
  35. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs +6 -4
  36. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx +61 -55
  37. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.doc.mjs +6 -4
  38. package/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherShowcase.tsx +68 -37
  39. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  40. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  41. package/assets/templates/blocks/components/Thumbnail/ThumbnailDisabled.doc.mjs +1 -1
  42. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +13 -6
  43. package/assets/templates/pages/dashboard-alert-rail/page.tsx +3 -3
  44. package/assets/templates/pages/library/page.tsx +1 -2
  45. package/assets/templates/pages/table-comparison/page.tsx +12 -3
  46. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +3 -2
  47. package/assets/templates/themes/butter/butterTheme.ts +47 -44
  48. package/assets/templates/themes/chocolate/chocolateTheme.ts +15 -2
  49. package/assets/templates/themes/gothic/gothicTheme.ts +21 -16
  50. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +1 -1
  51. package/assets/templates/themes/matcha/matchaTheme.ts +15 -2
  52. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +4 -4
  53. package/assets/templates/themes/neutral/neutralTheme.ts +24 -119
  54. package/assets/templates/themes/stone/stoneTheme.ts +46 -21
  55. package/assets/templates/themes/y2k/y2kTheme.ts +20 -16
  56. package/assets/theme.template.ts +9 -5
  57. package/authoring/codemod/type.ts +10 -0
  58. package/clients/cli/commands/build-theme.adaptations.test.mjs +110 -0
  59. package/clients/cli/commands/upgrade.doc.mjs +30 -2
  60. package/clients/cli/commands/upgrade.file-protection.test.mjs +146 -0
  61. package/clients/cli/commands/upgrade.outcomes.test.mjs +350 -0
  62. package/foundation/agent-docs/agent-docs.mjs +1 -0
  63. package/foundation/agent-docs/agent-docs.test.mjs +5 -0
  64. package/foundation/response/response-types.doc.mjs +1 -1
  65. package/package.json +10 -9
@@ -0,0 +1,315 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Codemod: migrate CodeBlock tokenizer to a custom language value
5
+ *
6
+ * `tokenizer={fn}` beside a static `language="x"` other than `plaintext`
7
+ * becomes `language={createCodeLanguage({name: 'x', identifiers: ['x'],
8
+ * tokenize: fn})}` (`component:CodeBlock` FR13). The custom language paints
9
+ * with the same function, labels `x`, and reflects `data-language="x"`, so the
10
+ * block looks the same. `createCodeLanguage` is imported from
11
+ * `@astryxdesign/core/CodeBlock` when the file does not import it yet, under
12
+ * a free alias when the file already binds the name to something else. A
13
+ * `tokenizer` that is a name or a call-free property may be undefined at run
14
+ * time, so it is guarded: `fn ? createCodeLanguage({...}) : 'x'`.
15
+ *
16
+ * Built on the shared `transformProp` helper, so it does not follow
17
+ * variables, helpers, wrappers, or types. Where a CodeBlock writes
18
+ * `tokenizer` but the codemod cannot prove the result, it keeps the old prop
19
+ * and leaves a TODO instead of guessing: a computed or missing `language`, a
20
+ * `tokenizer` value that is neither a function literal nor a name or property
21
+ * (a name or property is guarded with `fn ? createCodeLanguage(...) : 'x'`,
22
+ * since it may be undefined), a
23
+ * `plaintext` language (which shows no label today, while a language value
24
+ * does), and any CodeBlock that also spreads props. The deprecated prop keeps
25
+ * working there. Comments are the codemod's only report channel, and each is
26
+ * added once, so a second run changes nothing.
27
+ */
28
+
29
+ import {transformProp} from '../../transform-prop.mjs';
30
+
31
+ export const meta = {
32
+ title: 'Migrate CodeBlock tokenizer to a custom language',
33
+ description:
34
+ 'Replaces `tokenizer={fn}` beside a static `language="x"` with ' +
35
+ "`language={createCodeLanguage({name: 'x', identifiers: ['x'], tokenize: fn})}`. " +
36
+ 'Keeps the old prop with a TODO where the language is computed, missing, ' +
37
+ 'or `plaintext`, and where the CodeBlock also spreads props; the ' +
38
+ 'deprecated prop still works there.',
39
+ };
40
+
41
+ const OLD_NAME = 'tokenizer';
42
+ const CORE_IMPORT_RE = /^@(astryxdesign|xds)\/core(?:\/|$)/;
43
+ const CODEBLOCK_SOURCE = '@astryxdesign/core/CodeBlock';
44
+ const COMPONENT_PROPS = new Map([['CodeBlock', new Set([OLD_NAME])]]);
45
+
46
+ const UNPROVEN_COMMENT =
47
+ ' TODO(astryx upgrade): tokenizer is deprecated. Pass ' +
48
+ 'language={createCodeLanguage({name, identifiers, tokenize})} instead, ' +
49
+ 'with this function as tokenize; the language here is computed, missing, ' +
50
+ 'or plaintext, so it was left unchanged. ';
51
+ const VALUE_COMMENT =
52
+ ' TODO(astryx upgrade): tokenizer is deprecated. Pass ' +
53
+ 'language={createCodeLanguage({name, identifiers, tokenize})} instead; ' +
54
+ 'this tokenizer value is computed (not a function, a name, or a ' +
55
+ 'call-free property), so it was left unchanged. ';
56
+ const SPREAD_COMMENT =
57
+ ' TODO(astryx upgrade): tokenizer is deprecated, but this CodeBlock also ' +
58
+ 'spreads props that may set language or tokenizer, so it was left ' +
59
+ 'unchanged. Pass language={createCodeLanguage({name, identifiers, ' +
60
+ 'tokenize})} by hand. ';
61
+
62
+ const TYPE_WRAPPERS = new Set([
63
+ 'TSAsExpression',
64
+ 'TSSatisfiesExpression',
65
+ 'TSTypeAssertion',
66
+ 'TSNonNullExpression',
67
+ 'TypeCastExpression',
68
+ 'ParenthesizedExpression',
69
+ ]);
70
+
71
+ /** @param {any} node */
72
+ function unwrap(node) {
73
+ let current = node;
74
+ while (current && TYPE_WRAPPERS.has(current.type)) {
75
+ current = current.expression;
76
+ }
77
+ return current;
78
+ }
79
+
80
+ /** @param {any} attribute */
81
+ function attributeValue(attribute) {
82
+ return attribute.value?.type === 'JSXExpressionContainer'
83
+ ? attribute.value.expression
84
+ : attribute.value;
85
+ }
86
+
87
+ /** The static string of a node, or null. @param {any} node */
88
+ function staticString(node) {
89
+ const value = unwrap(node);
90
+ if (
91
+ value != null &&
92
+ (value.type === 'StringLiteral' || value.type === 'Literal') &&
93
+ typeof value.value === 'string'
94
+ ) {
95
+ return value.value;
96
+ }
97
+ if (
98
+ value?.type === 'TemplateLiteral' &&
99
+ value.expressions.length === 0 &&
100
+ value.quasis.length === 1
101
+ ) {
102
+ return value.quasis[0].value.cooked;
103
+ }
104
+ return null;
105
+ }
106
+
107
+ /**
108
+ * A name, or a property chain on one with no call and no computed key other
109
+ * than a literal: safe to read twice, and narrowed by a `?:` guard.
110
+ * @param {any} node
111
+ * @returns {boolean}
112
+ */
113
+ function isCallFreeChain(node) {
114
+ const value = unwrap(node);
115
+ if (value == null) {
116
+ return false;
117
+ }
118
+ if (value.type === 'Identifier' || value.type === 'ThisExpression') {
119
+ return true;
120
+ }
121
+ if (value.type === 'MemberExpression') {
122
+ const key = value.property;
123
+ const literalKey =
124
+ !value.computed ||
125
+ key.type === 'StringLiteral' ||
126
+ key.type === 'NumericLiteral' ||
127
+ key.type === 'Literal';
128
+ return (
129
+ literalKey && value.optional !== true && isCallFreeChain(value.object)
130
+ );
131
+ }
132
+ return false;
133
+ }
134
+
135
+ /** @param {any} j @param {any} node @param {string} text */
136
+ function addComment(j, node, text) {
137
+ node.comments ??= [];
138
+ if (node.comments.some((/** @type {any} */ c) => c.value === text)) {
139
+ return false;
140
+ }
141
+ node.comments.push(j.commentBlock(text, true, false));
142
+ return true;
143
+ }
144
+
145
+ /**
146
+ * The local name `createCodeLanguage` is imported under, adding the import
147
+ * when the file has none.
148
+ * @param {any} j @param {any} root
149
+ */
150
+ function ensureCreateImport(j, root) {
151
+ let local = null;
152
+ root
153
+ .find(j.ImportDeclaration)
154
+ .filter((/** @type {any} */ p) => CORE_IMPORT_RE.test(p.node.source.value))
155
+ .forEach((/** @type {any} */ p) => {
156
+ for (const specifier of p.node.specifiers ?? []) {
157
+ if (
158
+ specifier.type === 'ImportSpecifier' &&
159
+ specifier.imported.name === 'createCodeLanguage'
160
+ ) {
161
+ local = specifier.local?.name ?? 'createCodeLanguage';
162
+ }
163
+ }
164
+ });
165
+ if (local != null) {
166
+ return local;
167
+ }
168
+ // Any other binding of the name (a local import or function) would clash,
169
+ // so the import takes the first free alias instead.
170
+ const name = freeName(j, root, 'createCodeLanguage');
171
+ const specifier =
172
+ name === 'createCodeLanguage'
173
+ ? j.importSpecifier(j.identifier('createCodeLanguage'))
174
+ : j.importSpecifier(
175
+ j.identifier('createCodeLanguage'),
176
+ j.identifier(name),
177
+ );
178
+ const existing = root.find(j.ImportDeclaration).filter(
179
+ (/** @type {any} */ p) =>
180
+ p.node.source.value === CODEBLOCK_SOURCE &&
181
+ p.node.importKind !== 'type' &&
182
+ // A namespace import cannot take a named specifier beside it.
183
+ !(p.node.specifiers ?? []).some(
184
+ (/** @type {any} */ s) => s.type === 'ImportNamespaceSpecifier',
185
+ ),
186
+ );
187
+ if (existing.size() > 0) {
188
+ existing.get().node.specifiers.push(specifier);
189
+ } else {
190
+ const declaration = j.importDeclaration(
191
+ [specifier],
192
+ j.stringLiteral(CODEBLOCK_SOURCE),
193
+ );
194
+ const imports = root.find(j.ImportDeclaration);
195
+ if (imports.size() > 0) {
196
+ imports.at(imports.size() - 1).insertAfter(declaration);
197
+ } else {
198
+ root.get().node.program.body.unshift(declaration);
199
+ }
200
+ }
201
+ return name;
202
+ }
203
+
204
+ /**
205
+ * `preferred`, or `preferred` with a numeric suffix, whichever no binding or
206
+ * reference in the file already uses.
207
+ * @param {any} j @param {any} root @param {string} preferred
208
+ */
209
+ function freeName(j, root, preferred) {
210
+ const used = new Set();
211
+ root.find(j.Identifier).forEach((/** @type {any} */ p) => {
212
+ used.add(p.node.name);
213
+ });
214
+ if (!used.has(preferred)) {
215
+ return preferred;
216
+ }
217
+ let n = 2;
218
+ while (used.has(`${preferred}${n}`)) {
219
+ n++;
220
+ }
221
+ return `${preferred}${n}`;
222
+ }
223
+
224
+ /**
225
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
226
+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
227
+ * @returns {string | null | undefined}
228
+ */
229
+ export default function transformer(file, api) {
230
+ const j = api.jscodeshift;
231
+ const root = j(file.source);
232
+ let hasChanges = false;
233
+ /** @type {Array<() => void>} */
234
+ const rewrites = [];
235
+
236
+ transformProp(
237
+ root,
238
+ j,
239
+ {
240
+ matchesImport: source => CORE_IMPORT_RE.test(source),
241
+ components: COMPONENT_PROPS,
242
+ },
243
+ propPath => {
244
+ const opening = propPath.parent?.node;
245
+ const attributes = opening?.attributes ?? [];
246
+ const prop = propPath.node;
247
+ if (
248
+ attributes.some(
249
+ (/** @type {any} */ a) => a.type === 'JSXSpreadAttribute',
250
+ )
251
+ ) {
252
+ hasChanges = addComment(j, prop, SPREAD_COMMENT) || hasChanges;
253
+ return;
254
+ }
255
+ const languageAttribute = attributes.find(
256
+ (/** @type {any} */ a) =>
257
+ a.type === 'JSXAttribute' && a.name?.name === 'language',
258
+ );
259
+ const language =
260
+ languageAttribute == null
261
+ ? null
262
+ : staticString(attributeValue(languageAttribute));
263
+ const tokenize = attributeValue(prop);
264
+ const tokenizeNode = unwrap(tokenize);
265
+ // A function literal is always a function. A name or property may be
266
+ // undefined at run time (a forwarded optional prop), so it is guarded:
267
+ // `fn ? createCodeLanguage({...}) : 'x'` keeps the plain block the
268
+ // released prop drew without one. Anything else is reported.
269
+ const isFunction =
270
+ tokenizeNode?.type === 'ArrowFunctionExpression' ||
271
+ tokenizeNode?.type === 'FunctionExpression';
272
+ const isGuardable = isCallFreeChain(tokenizeNode);
273
+ if (language == null || language === '' || language === 'plaintext') {
274
+ hasChanges = addComment(j, prop, UNPROVEN_COMMENT) || hasChanges;
275
+ return;
276
+ }
277
+ if (!(isFunction || isGuardable)) {
278
+ hasChanges = addComment(j, prop, VALUE_COMMENT) || hasChanges;
279
+ return;
280
+ }
281
+ rewrites.push(() => {
282
+ const create = ensureCreateImport(j, root);
283
+ const value = j.callExpression(j.identifier(create), [
284
+ j.objectExpression([
285
+ j.objectProperty(j.identifier('name'), j.stringLiteral(language)),
286
+ j.objectProperty(
287
+ j.identifier('identifiers'),
288
+ j.arrayExpression([j.stringLiteral(language)]),
289
+ ),
290
+ j.objectProperty(j.identifier('tokenize'), tokenize),
291
+ ]),
292
+ ]);
293
+ languageAttribute.value = j.jsxExpressionContainer(
294
+ isFunction
295
+ ? value
296
+ : j.conditionalExpression(
297
+ tokenize,
298
+ value,
299
+ j.stringLiteral(language),
300
+ ),
301
+ );
302
+ opening.attributes = opening.attributes.filter(
303
+ (/** @type {any} */ a) => a !== prop,
304
+ );
305
+ });
306
+ },
307
+ );
308
+
309
+ for (const rewrite of rewrites) {
310
+ rewrite();
311
+ hasChanges = true;
312
+ }
313
+ if (!hasChanges) return undefined;
314
+ return root.toSource({quote: 'single'});
315
+ }
@@ -162,6 +162,52 @@ export default createConfig({
162
162
  });
163
163
  });
164
164
 
165
+ describe('migrate-layout-components-to-experimental — default export by const reference', () => {
166
+ it('returns null for a generated config with no layout key', async () => {
167
+ const input = `// Generated Astryx config.
168
+ const config = {
169
+ integrations: ["@acme/ui"],
170
+ issuesUrl: "https://example.com/issues",
171
+ };
172
+
173
+ export default config;
174
+ `;
175
+ const output = await applyTransform(input);
176
+ expect(output).toBeNull();
177
+ });
178
+
179
+ it('migrates layout.components in a const-bound object literal', async () => {
180
+ const input = `const config = {
181
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
182
+ };
183
+
184
+ export default config;
185
+ `;
186
+ const output = await applyTransform(input);
187
+ expect(output).not.toBeNull();
188
+ expect(output).toMatch(/const config = \{/);
189
+ expect(output).toContain('export default config;');
190
+ expect(output).toMatch(/experimental:\s*\{\s*xle:\s*\{\s*components:\s*\{\s*KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);
191
+ expect(output).not.toMatch(/layout\s*:/);
192
+ });
193
+
194
+ it('migrates layout.components in a const-bound createConfig({ ... }) call', async () => {
195
+ const input = `import { createConfig } from '@astryxdesign/cli';
196
+
197
+ const config = createConfig({
198
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
199
+ });
200
+
201
+ export default config;
202
+ `;
203
+ const output = await applyTransform(input);
204
+ expect(output).not.toBeNull();
205
+ expect(output).toContain('createConfig(');
206
+ expect(output).toMatch(/KpiCard:\s*\{\s*from:\s*['"]@\/components\/KpiCard['"]/);
207
+ expect(output).not.toMatch(/layout\s*:/);
208
+ });
209
+ });
210
+
165
211
  describe('migrate-layout-components-to-experimental — placement', () => {
166
212
  it('adds xle to a pre-existing experimental (no xle)', async () => {
167
213
  const input = `export default {
@@ -239,8 +285,69 @@ export default {
239
285
  await expect(applyTransform(input)).rejects.toThrow(/cannot be safely migrated/);
240
286
  });
241
287
 
242
- it('throws on a non-object default export (variable reference)', async () => {
243
- const input = `const config = { layout: { components: {} } };
288
+ it('throws when the default export is an identifier with no top-level const binding', async () => {
289
+ const input = `import config from './base-config.mjs';
290
+ export default config;
291
+ `;
292
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
293
+ });
294
+
295
+ it('throws when a const-bound config is mutated after its declaration', async () => {
296
+ const input = `const config = {};
297
+ config.layout = { components: { KpiCard: '@/components/KpiCard' } };
298
+ export default config;
299
+ `;
300
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
301
+ });
302
+
303
+ it('throws when a const-bound config is passed to another call', async () => {
304
+ const input = `const config = {};
305
+ Object.assign(config, { layout: { components: { KpiCard: '@/components/KpiCard' } } });
306
+ export default config;
307
+ `;
308
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
309
+ });
310
+
311
+ it('throws when a const-bound config is aliased', async () => {
312
+ const input = `const config = {};
313
+ const alias = config;
314
+ alias.layout = { components: { KpiCard: '@/components/KpiCard' } };
315
+ export default config;
316
+ `;
317
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
318
+ });
319
+
320
+ it('throws when the const-bound config is also exported with export const', async () => {
321
+ const input = `export const config = {
322
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
323
+ };
324
+ export default config;
325
+ `;
326
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
327
+ });
328
+
329
+ it('throws when the const-bound config is also exported by name', async () => {
330
+ const input = `const config = {
331
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
332
+ };
333
+ export { config };
334
+ export default config;
335
+ `;
336
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
337
+ });
338
+
339
+ it('throws when the const-bound config is also exported under another name', async () => {
340
+ const input = `const config = {
341
+ layout: { components: { KpiCard: '@/components/KpiCard' } },
342
+ };
343
+ export { config as baseConfig };
344
+ export default config;
345
+ `;
346
+ await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
347
+ });
348
+
349
+ it('throws when the default export is bound by a reassignable let', async () => {
350
+ const input = `let config = { layout: { components: { KpiCard: '@/components/KpiCard' } } };
244
351
  export default config;
245
352
  `;
246
353
  await expect(applyTransform(input)).rejects.toThrow(/statically analyze/);
@@ -306,6 +413,113 @@ describe('migrate-layout-components-to-experimental — end-to-end via runConfig
306
413
  }
307
414
  });
308
415
 
416
+ it('leaves a generated const-bound config with no layout untouched and reports no error', async () => {
417
+ const {runConfigCodemod} = await import('../../../run-codemod.mjs');
418
+ const {default: transform, meta} = await import(
419
+ '../migrate-layout-components-to-experimental.mjs'
420
+ );
421
+ const jscodeshift = (await import('jscodeshift')).default;
422
+
423
+ const originalCwd = process.cwd();
424
+ const tmpDir = fs.mkdtempSync(
425
+ path.join(process.cwd(), '.astryx-v013-codemod-test-'),
426
+ );
427
+ const configSource = `// Generated Astryx config.
428
+ const config = {
429
+ integrations: ["@acme/ui"],
430
+ issuesUrl: "https://example.com/issues",
431
+ };
432
+
433
+ export default config;
434
+ `;
435
+ try {
436
+ process.chdir(tmpDir);
437
+ fs.writeFileSync(
438
+ path.join(tmpDir, 'package.json'),
439
+ JSON.stringify({name: 'consumer'}),
440
+ );
441
+ fs.writeFileSync(path.join(tmpDir, 'astryx.config.mjs'), configSource);
442
+
443
+ const entry = {
444
+ id: 'migrate-layout-components-to-experimental',
445
+ type: 'config',
446
+ codemod: {title: meta.title, transform},
447
+ package: 'core',
448
+ version: '0.1.3',
449
+ };
450
+ const log = {
451
+ step() {},
452
+ info() {},
453
+ success() {},
454
+ warn() {},
455
+ error() {},
456
+ message() {},
457
+ };
458
+ const result = runConfigCodemod(entry, {apply: true, log, jscodeshift});
459
+
460
+ expect(result.errors).toHaveLength(0);
461
+ expect(result.filesChanged).toBe(0);
462
+ expect(
463
+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),
464
+ ).toBe(configSource);
465
+ } finally {
466
+ process.chdir(originalCwd);
467
+ fs.rmSync(tmpDir, {recursive: true, force: true});
468
+ }
469
+ });
470
+
471
+ it('reports an error, not success, for a mutated const-bound config', async () => {
472
+ const {runConfigCodemod} = await import('../../../run-codemod.mjs');
473
+ const {default: transform, meta} = await import(
474
+ '../migrate-layout-components-to-experimental.mjs'
475
+ );
476
+ const jscodeshift = (await import('jscodeshift')).default;
477
+
478
+ const originalCwd = process.cwd();
479
+ const tmpDir = fs.mkdtempSync(
480
+ path.join(process.cwd(), '.astryx-v013-codemod-test-'),
481
+ );
482
+ const configSource = `const config = {};
483
+ config.layout = { components: { KpiCard: '@/components/KpiCard' } };
484
+ export default config;
485
+ `;
486
+ try {
487
+ process.chdir(tmpDir);
488
+ fs.writeFileSync(
489
+ path.join(tmpDir, 'package.json'),
490
+ JSON.stringify({name: 'consumer'}),
491
+ );
492
+ fs.writeFileSync(path.join(tmpDir, 'astryx.config.mjs'), configSource);
493
+
494
+ const entry = {
495
+ id: 'migrate-layout-components-to-experimental',
496
+ type: 'config',
497
+ codemod: {title: meta.title, transform},
498
+ package: 'core',
499
+ version: '0.1.3',
500
+ };
501
+ const log = {
502
+ step() {},
503
+ info() {},
504
+ success() {},
505
+ warn() {},
506
+ error() {},
507
+ message() {},
508
+ };
509
+ const result = runConfigCodemod(entry, {apply: true, log, jscodeshift});
510
+
511
+ expect(result.filesChanged).toBe(0);
512
+ expect(result.errors).toHaveLength(1);
513
+ expect(result.errors[0].error).toMatch(/statically analyze/);
514
+ expect(
515
+ fs.readFileSync(path.join(tmpDir, 'astryx.config.mjs'), 'utf-8'),
516
+ ).toBe(configSource);
517
+ } finally {
518
+ process.chdir(originalCwd);
519
+ fs.rmSync(tmpDir, {recursive: true, force: true});
520
+ }
521
+ });
522
+
309
523
  it('surfaces a thrown bail as a structured error through runConfigCodemod', async () => {
310
524
  const {runConfigCodemod} = await import('../../../run-codemod.mjs');
311
525
  const {default: transform, meta} = await import(
@@ -28,10 +28,14 @@
28
28
  * - object `{ from, description?, default? }` → carried over UNCHANGED
29
29
  * (from/description/default preserved, key order preserved).
30
30
  *
31
- * The transform recognizes the config default export as EITHER a bare object
32
- * literal (`export default { ... }`) or a `createConfig({ ... })` call wrapping
33
- * an object literal (`export default createConfig({ ... })`). Anything else is
34
- * not statically analyzable and the transform THROWS with a clear
31
+ * The transform recognizes the config default export as a bare object literal
32
+ * (`export default { ... }`), a `createConfig({ ... })` call wrapping an object
33
+ * literal (`export default createConfig({ ... })`), or an identifier bound by a
34
+ * top-level `const` to either form (`const config = { ... }; export default
35
+ * config;`, the shape generated configs use) when the binding is not
36
+ * exported any other way and the default export is its only reference, so
37
+ * nothing can mutate the object after its declaration. Anything else is not statically analyzable and the transform
38
+ * THROWS with a clear
35
39
  * migrate-manually message (the unified config-codemod contract has no
36
40
  * structured-error return — `runConfigCodemod` surfaces a thrown `err.message`
37
41
  * as `{file, codemod, error}`).
@@ -76,10 +80,16 @@ export default function transformer(file, api) {
76
80
 
77
81
  const declaration = defaultExports.paths()[0].node.declaration;
78
82
 
79
- // Resolve the config object literal from either form:
83
+ // Resolve the config object literal from any supported form:
80
84
  // export default { ... }
81
85
  // export default createConfig({ ... })
82
- const configObject = resolveConfigObject(j, declaration);
86
+ // const config = { ... } | createConfig({ ... }); export default config;
87
+ const configObject = resolveConfigObject(
88
+ j,
89
+ j.Identifier.check(declaration)
90
+ ? findTopLevelConstInit(j, root, declaration)
91
+ : declaration,
92
+ );
83
93
  if (!configObject) {
84
94
  throw new Error(
85
95
  `could not statically analyze astryx config; ${MANUAL}`,
@@ -179,6 +189,78 @@ function resolveConfigObject(/** @type {any} */ j, /** @type {any} */ declaratio
179
189
  return null;
180
190
  }
181
191
 
192
+ /**
193
+ * Find the initializer of the top-level, non-exported `const <name> = <init>`
194
+ * declaration that the default-exported identifier refers to. `let`/`var`
195
+ * bindings can be reassigned, so they are not treated as statically
196
+ * analyzable. Neither is a binding exported any other way (`export const`,
197
+ * `export { name }`, `export { name as other }`), since another module could
198
+ * import and mutate it, nor one referenced anywhere besides its declaration
199
+ * and the default export: a member write, an alias or a call argument could
200
+ * change the object after its initializer. A named export specifier is such a
201
+ * reference, so `hasOtherReference` rejects it.
202
+ * @returns {any} the initializer node, or null if there is no such binding
203
+ */
204
+ function findTopLevelConstInit(/** @type {any} */ j, /** @type {any} */ root, /** @type {any} */ exported) {
205
+ const name = exported.name;
206
+ for (const statement of root.get().node.program.body) {
207
+ // `export const` is skipped on purpose: another module can import the
208
+ // binding and mutate the object.
209
+ if (
210
+ !j.VariableDeclaration.check(statement) ||
211
+ statement.kind !== 'const'
212
+ ) {
213
+ continue;
214
+ }
215
+ for (const declarator of statement.declarations) {
216
+ if (
217
+ j.VariableDeclarator.check(declarator) &&
218
+ j.Identifier.check(declarator.id) &&
219
+ declarator.id.name === name
220
+ ) {
221
+ return hasOtherReference(j, root, name, [declarator.id, exported])
222
+ ? null
223
+ : declarator.init ?? null;
224
+ }
225
+ }
226
+ }
227
+ return null;
228
+ }
229
+
230
+ /**
231
+ * Whether any identifier named `name`, other than the `allowed` nodes, could
232
+ * refer to the binding. Non-computed member properties (`x.name`) and object
233
+ * keys (`{ name: 1 }`) name a property, not the binding, so they don't count;
234
+ * every other occurrence (including a shadowing one) does.
235
+ * @returns {boolean}
236
+ */
237
+ function hasOtherReference(/** @type {any} */ j, /** @type {any} */ root, /** @type {string} */ name, /** @type {any[]} */ allowed) {
238
+ return root
239
+ .find(j.Identifier, {name})
240
+ .some((/** @type {any} */ path) => {
241
+ const node = path.node;
242
+ if (allowed.includes(node)) return false;
243
+ const parent = path.parent?.node;
244
+ if (
245
+ (j.MemberExpression.check(parent) ||
246
+ j.OptionalMemberExpression.check(parent)) &&
247
+ parent.property === node &&
248
+ !parent.computed
249
+ ) {
250
+ return false;
251
+ }
252
+ if (
253
+ (j.ObjectProperty.check(parent) || j.Property.check(parent)) &&
254
+ parent.key === node &&
255
+ !parent.computed &&
256
+ !parent.shorthand
257
+ ) {
258
+ return false;
259
+ }
260
+ return true;
261
+ });
262
+ }
263
+
182
264
  /**
183
265
  * Find a (non-computed, non-spread) property on an object literal by key name.
184
266
  * Supports Identifier and string-literal keys.