@astryxdesign/cli 0.7.0-canary.4ec1f4e → 0.7.0-canary.5442d61

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 (66) hide show
  1. package/README.md +61 -61
  2. package/api/build/build.mjs +9 -0
  3. package/api/component/_adapter.d.mts +2 -0
  4. package/api/component/_adapter.mjs +3 -1
  5. package/api/component/component.doc.mjs +5 -1
  6. package/api/docs/compiled-topics.test.mjs +16 -0
  7. package/api/integration/pack-check.test.mjs +8 -0
  8. package/api/template/list/list.mjs +23 -2
  9. package/api/template/list/list.test.mjs +52 -0
  10. package/api/template/template.doc.mjs +5 -4
  11. package/api/template/template.type.mjs +1 -1
  12. package/api/theme/build/build.d.mts +0 -1
  13. package/api/theme/build/build.mjs +4 -29
  14. package/api/theme/build/family.mjs +1 -1
  15. package/assets/codemods/transforms/next/__tests__/migrate-field-input-styling.test.mjs +108 -0
  16. package/assets/codemods/transforms/next/__tests__/validate-data-token-ownership.test.mjs +84 -0
  17. package/assets/codemods/transforms/next/index.mjs +16 -0
  18. package/assets/codemods/transforms/next/migrate-field-input-styling.mjs +198 -0
  19. package/assets/codemods/transforms/next/validate-data-token-ownership.mjs +102 -0
  20. package/assets/docs/author-a-theme.doc.mjs +4 -4
  21. package/assets/docs/tree/tokens-data.doc.mjs +2 -2
  22. package/assets/docs/tree/tokens-usage.doc.mjs +1 -1
  23. package/assets/templates/blocks/components/ComplexSelector/ComplexSelectorDeadlinePicker.tsx +1 -1
  24. package/assets/templates/blocks/components/ComplexSelector/ComplexSelectorShowcase.tsx +1 -1
  25. package/assets/templates/blocks/components/ComplexSelector/ComplexSelectorTreeSearch.tsx +1 -1
  26. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider01ShippedLocale.tsx +1 -1
  27. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider02Overrides.tsx +1 -1
  28. package/assets/templates/blocks/components/Selector/SelectorClearable.tsx +1 -1
  29. package/assets/templates/blocks/components/Selector/SelectorOptionDescriptions.tsx +2 -2
  30. package/assets/templates/blocks/components/Selector/SelectorShowcase.tsx +1 -1
  31. package/assets/templates/blocks/components/Selector/SelectorWithSections.tsx +1 -1
  32. package/assets/templates/blocks/components/SelectorOption/SelectorOptionBasic.tsx +1 -1
  33. package/assets/templates/blocks/components/SelectorOption/SelectorOptionShowcase.tsx +1 -1
  34. package/assets/templates/blocks/components/Slider/SliderFormattedValue.tsx +1 -1
  35. package/assets/templates/blocks/components/Slider/SliderRangeSlider.tsx +1 -1
  36. package/assets/templates/blocks/components/Slider/SliderShowcase.tsx +1 -1
  37. package/assets/templates/blocks/components/Slider/SliderWithMarks.tsx +1 -1
  38. package/assets/templates/blocks/components/Tokenizer/TokenizerClear.tsx +1 -1
  39. package/assets/templates/blocks/components/Tokenizer/TokenizerCreatable.tsx +2 -2
  40. package/assets/templates/blocks/components/Tokenizer/TokenizerEndContent.tsx +1 -1
  41. package/assets/templates/blocks/components/Tokenizer/TokenizerIcon.tsx +1 -1
  42. package/assets/templates/blocks/components/Tokenizer/TokenizerMaxEntries.tsx +1 -1
  43. package/assets/templates/blocks/components/Tokenizer/TokenizerOverflow.tsx +2 -2
  44. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +1 -1
  45. package/assets/templates/blocks/components/Tokenizer/TokenizerStates.tsx +4 -4
  46. package/assets/templates/blocks/components/Toolbar/ToolbarTableFilter.tsx +1 -1
  47. package/assets/templates/pages/canvas-editor/page.tsx +2 -2
  48. package/assets/templates/pages/form-wizard-vertical/page.tsx +1 -1
  49. package/assets/templates/pages/payment-form/page.tsx +1 -1
  50. package/assets/templates/pages/table-filter/page.tsx +3 -3
  51. package/assets/templates/pages/theme-showcase/page.tsx +2 -2
  52. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +10 -9
  53. package/clients/cli/commands/build-theme.color-scheme.test.mjs +10 -6
  54. package/clients/cli/commands/build-theme.data-tokens.test.mjs +23 -75
  55. package/clients/cli/commands/build.doc.mjs +1 -1
  56. package/clients/cli/commands/build.mjs +1 -1
  57. package/clients/cli/commands/component-ownership.test.mjs +2 -2
  58. package/clients/cli/commands/integration.mjs +2 -1
  59. package/clients/cli/commands/silent-success-refusals.test.mjs +15 -0
  60. package/clients/cli/commands/template.doc.mjs +1 -1
  61. package/foundation/discovery/template-needs.mjs +93 -11
  62. package/foundation/discovery/template-needs.test.mjs +106 -3
  63. package/foundation/env/package-manager.d.mts +13 -0
  64. package/foundation/env/package-manager.mjs +106 -63
  65. package/foundation/response/response-types.doc.mjs +1 -2
  66. package/package.json +9 -9
@@ -99,14 +99,12 @@ import {resolveIconImports} from './icon-imports.mjs';
99
99
  // capability instead, required only by a theme that actually uses it:
100
100
  // requiring it unconditionally made every theme build — adaptations or not —
101
101
  // fail against an older published core. This is a targeted allowance for that
102
- // one capability, not a general scheme; the other two optional reads below
103
- // (`generateOnMediaCSS`, `dataTokenDefaults`) both exist in every core that
104
- // ships adaptations' predecessor surface.
102
+ // one capability, not a general scheme; `generateOnMediaCSS` exists in every
103
+ // core that ships adaptations' predecessor surface.
105
104
  /** @type {any} */ let _defineTheme = null;
106
105
  /** @type {any} */ let _generateThemeRulesSplit = null;
107
106
  /** @type {any} */ let _generateOnMediaCSS = null;
108
107
  /** @type {any} */ let _generateAdaptationCSS = null;
109
- /** @type {any} */ let _dataTokenDefaults = null;
110
108
  /**
111
109
  * The whole `@astryxdesign/core/theme` namespace. A theme file handed a
112
110
  * wrapped core must still get every export the installed one has, including
@@ -129,7 +127,6 @@ try {
129
127
  _generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
130
128
  _generateOnMediaCSS = coreTheme.generateOnMediaCSS;
131
129
  _generateAdaptationCSS = coreTheme.generateAdaptationCSS;
132
- _dataTokenDefaults = coreTheme.dataTokenDefaults;
133
130
  try {
134
131
  _coreRootModule = await import('@astryxdesign/core');
135
132
  } catch {
@@ -156,7 +153,6 @@ try {
156
153
  * generateThemeRulesSplit: any,
157
154
  * generateOnMediaCSS: any,
158
155
  * generateAdaptationCSS: any,
159
- * dataTokenDefaults: any,
160
156
  * }} CoreBindings
161
157
  */
162
158
 
@@ -173,7 +169,6 @@ const _cliCore = {
173
169
  generateThemeRulesSplit: _generateThemeRulesSplit,
174
170
  generateOnMediaCSS: _generateOnMediaCSS,
175
171
  generateAdaptationCSS: _generateAdaptationCSS,
176
- dataTokenDefaults: _dataTokenDefaults,
177
172
  };
178
173
 
179
174
  /**
@@ -188,7 +183,6 @@ function setCore(core) {
188
183
  _generateThemeRulesSplit = core.generateThemeRulesSplit;
189
184
  _generateOnMediaCSS = core.generateOnMediaCSS;
190
185
  _generateAdaptationCSS = core.generateAdaptationCSS;
191
- _dataTokenDefaults = core.dataTokenDefaults;
192
186
  }
193
187
 
194
188
  /**
@@ -295,7 +289,6 @@ async function loadProjectCore(cwd) {
295
289
  generateThemeRulesSplit: themeModule.generateThemeRulesSplit,
296
290
  generateOnMediaCSS: themeModule.generateOnMediaCSS,
297
291
  generateAdaptationCSS: themeModule.generateAdaptationCSS,
298
- dataTokenDefaults: themeModule.dataTokenDefaults,
299
292
  };
300
293
  }
301
294
 
@@ -2739,26 +2732,8 @@ async function themeBuildInternal(
2739
2732
  logger.log(`${source}No overrides found; nothing to build.`);
2740
2733
  return null;
2741
2734
  }
2742
- // The data-token defaults are theme-independent and go in @layer
2743
- // astryx-base, below the theme's own overrides. Formatted here from the
2744
- // public `dataTokenDefaults` export, byte for byte as the `<Theme>`
2745
- // runtime emits it — build-theme.data-tokens.test.mjs is the drift guard.
2746
- // Placed after the reset block and before the theme block: a layer's order
2747
- // is fixed by where it is first declared, so emitting it anywhere else in
2748
- // the file would invert reset < astryx-base < astryx-theme for a consumer
2749
- // who imports this stylesheet on its own.
2750
- const baseCss = _dataTokenDefaults
2751
- ? `:root {\n${Object.entries(_dataTokenDefaults)
2752
- .map(([name, value]) => ` ${name}: ${value};`)
2753
- .join('\n')}\n}`
2754
- : '';
2755
- if (baseCss) {
2756
- cssParts.splice(
2757
- prose.length > 0 ? 1 : 0,
2758
- 0,
2759
- `@layer astryx-base {\n${baseCss}\n}`,
2760
- );
2761
- }
2735
+ cssParts.unshift('@layer reset, astryx-base, astryx-theme;');
2736
+ const baseCss = '';
2762
2737
  cssPlan = {
2763
2738
  base: baseCss,
2764
2739
  prose,
@@ -438,5 +438,5 @@ export function generateFamilyCSS(members) {
438
438
  parts.push(`@layer astryx-base {\n${base.join('\n\n')}\n}`);
439
439
  if (themed.length > 0)
440
440
  parts.push(`@layer astryx-theme {\n${themed.join('\n\n')}\n}`);
441
- return `${parts.join('\n\n')}\n`;
441
+ return `@layer reset, astryx-base, astryx-theme;\n\n${parts.join('\n\n')}\n`;
442
442
  }
@@ -0,0 +1,108 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ import {describe, expect, it} from 'vitest';
4
+ import jscodeshift from 'jscodeshift';
5
+ import transform from '../migrate-field-input-styling.mjs';
6
+
7
+ const j = jscodeshift.withParser('tsx');
8
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
9
+
10
+ /** @param {string} source */
11
+ function apply(source) {
12
+ return transform({source, path: 'test.tsx'}, api) ?? source;
13
+ }
14
+
15
+ describe('migrate-field-input-styling', () => {
16
+ it('moves control-box members to control*', () => {
17
+ const input = `import {TextInput, Selector, DateInput} from '@astryxdesign/core';
18
+ const a = <TextInput label="Name" xstyle={styles.input} className="name" style={{width: 200}} />;
19
+ const b = <Selector label="Fruit" options={options} xstyle={styles.selector} />;
20
+ const c = <DateInput label="Due" className="due" />;`;
21
+ const output = apply(input);
22
+ expect(output).toContain(
23
+ '<TextInput label="Name" controlXstyle={styles.input} controlClassName="name" controlStyle={{width: 200}} />',
24
+ );
25
+ expect(output).toContain('controlXstyle={styles.selector}');
26
+ expect(output).toContain(
27
+ '<DateInput label="Due" controlClassName="due" />',
28
+ );
29
+ });
30
+
31
+ it('moves Field-root members to container*', () => {
32
+ const input = `import {Typeahead} from '@astryxdesign/core/Typeahead';
33
+ import {RadioList, Slider} from '@astryxdesign/core';
34
+ const a = <Typeahead label="Fruit" xstyle={styles.wide} />;
35
+ const b = <RadioList label="Plan" style={{marginTop: 8}}>{items}</RadioList>;
36
+ const c = <Slider label="Volume" className="volume" value={1} />;`;
37
+ const output = apply(input);
38
+ expect(output).toContain('containerXstyle={styles.wide}');
39
+ expect(output).toContain('containerStyle={{marginTop: 8}}');
40
+ expect(output).toContain('containerClassName="volume"');
41
+ });
42
+
43
+ it('moves a Typeahead inside InputGroup to control*, where its root styling painted the surface', () => {
44
+ const input = `import {InputGroup, Typeahead} from '@astryxdesign/core';
45
+ const a = (
46
+ <InputGroup label="Produce">
47
+ <Typeahead label="Fruit" className="grouped" />
48
+ </InputGroup>
49
+ );
50
+ const b = <Typeahead label="Fruit" className="standalone" />;`;
51
+ const output = apply(input);
52
+ expect(output).toContain('controlClassName="grouped"');
53
+ expect(output).toContain('containerClassName="standalone"');
54
+ });
55
+
56
+ it('follows aliased and namespace imports', () => {
57
+ const input = `import {TextArea as Notes} from '@astryxdesign/core';
58
+ import * as Astryx from '@astryxdesign/core';
59
+ const a = <Notes label="Notes" className="notes" />;
60
+ const b = <Astryx.Tokenizer label="Tags" xstyle={styles.tags} />;`;
61
+ const output = apply(input);
62
+ expect(output).toContain(
63
+ '<Notes label="Notes" controlClassName="notes" />',
64
+ );
65
+ expect(output).toContain(
66
+ '<Astryx.Tokenizer label="Tags" containerXstyle={styles.tags} />',
67
+ );
68
+ });
69
+
70
+ it('leaves unrelated components, other packages, nested JSX, and spreads alone', () => {
71
+ const input = `import {TextInput} from 'some-other-library';
72
+ import {Button, NumberInput} from '@astryxdesign/core';
73
+ const a = <TextInput className="kept" />;
74
+ const b = <Button xstyle={styles.button} />;
75
+ const c = <NumberInput label="Qty" {...rest} startIcon={<Icon className="icon" />} />;`;
76
+ expect(apply(input)).toBe(input);
77
+ });
78
+
79
+ it('leaves tags whose name is shadowed by a local binding', () => {
80
+ const input = `import {TextInput} from '@astryxdesign/core';
81
+ import * as Astryx from '@astryxdesign/core';
82
+ function Row({TextInput}) {
83
+ return <TextInput className="kept" />;
84
+ }
85
+ function Other(Astryx) {
86
+ return <Astryx.Typeahead className="kept" />;
87
+ }`;
88
+ expect(apply(input)).toBe(input);
89
+ });
90
+
91
+ it('marks a conflict with a TODO instead of dropping a value', () => {
92
+ const input = `import {TextInput} from '@astryxdesign/core';
93
+ const a = <TextInput label="Name" className="old" controlClassName="new" />;`;
94
+ const output = apply(input);
95
+ expect(output).toContain('controlClassName="new"');
96
+ expect(output).toContain('className="old"');
97
+ expect(output).toContain('TODO(astryx upgrade)');
98
+ });
99
+
100
+ it('is idempotent', () => {
101
+ const input = `import {TextInput, CheckboxList} from '@astryxdesign/core';
102
+ const a = <TextInput label="Name" className="old" controlClassName="new" />;
103
+ const b = <TextInput label="Email" xstyle={styles.email} />;
104
+ const c = <CheckboxList label="Prefs" style={{margin: 4}}>{items}</CheckboxList>;`;
105
+ const once = apply(input);
106
+ expect(apply(once)).toBe(once);
107
+ });
108
+ });
@@ -0,0 +1,84 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ import {describe, expect, it} from 'vitest';
4
+ import transform from '../validate-data-token-ownership.mjs';
5
+
6
+ async function run(source, file = 'test.tsx') {
7
+ const jscodeshift = (await import('jscodeshift')).default;
8
+ const parser =
9
+ file.endsWith('.ts') || file.endsWith('.tsx') ? 'tsx' : 'babel';
10
+ const api = {
11
+ jscodeshift: jscodeshift.withParser(parser),
12
+ stats: () => {},
13
+ report: () => {},
14
+ };
15
+ return transform({source, path: file}, api);
16
+ }
17
+
18
+ describe('validate-data-token-ownership', () => {
19
+ it('reports direct string and static-template consumers with both migration paths', async () => {
20
+ for (const source of [
21
+ `const fill = 'var(--color-data-categorical-green)';`,
22
+ 'const fill = `var(--color-data-categorical-green)`;',
23
+ `const border = '1px solid var(--color-data-categorical-green)';`,
24
+ 'const border = `${width}px solid var(--color-data-categorical-green)`;',
25
+ ]) {
26
+ await expect(run(source)).rejects.toThrow(
27
+ /CSS-capable code imports dataVars.*Canvas.*resolveThemeToken/s,
28
+ );
29
+ }
30
+ });
31
+
32
+ it('leaves fallbacks, dataVars access, and comments unchanged', async () => {
33
+ const source = `
34
+ // var(--color-data-categorical-green)
35
+ const fallback = 'var(--color-data-categorical-green, #008000)';
36
+ const fill = dataVars['--color-data-categorical-green'];
37
+ `;
38
+ expect(await run(source)).toBeUndefined();
39
+ });
40
+
41
+ it('reports stale generated theme CSS with root data defaults', async () => {
42
+ const source = `/* @generated by \`astryx theme build\` */
43
+ @layer astryx-base {
44
+ :root { --color-data-categorical-green: #008000; }
45
+ }`;
46
+ await expect(run(source, 'theme.css')).rejects.toThrow(
47
+ /Rebuild it with `astryx theme build`/,
48
+ );
49
+ });
50
+
51
+ it('reports raw stylesheet uses without a fallback', async () => {
52
+ await expect(
53
+ run('.bar { fill: var(--color-data-categorical-green); }', 'chart.css'),
54
+ ).rejects.toThrow(/Raw var\(--color-data-categorical-green\).*line 1/s);
55
+ });
56
+
57
+ it('leaves stylesheet uses with a fallback, and comments, unchanged', async () => {
58
+ expect(
59
+ await run(
60
+ `/* var(--color-data-categorical-green) */
61
+ .bar { fill: var(--color-data-categorical-green, #008000); }`,
62
+ 'chart.css',
63
+ ),
64
+ ).toBeUndefined();
65
+ });
66
+
67
+ it('does not claim ownership of hand-authored CSS or sparse theme overrides', async () => {
68
+ expect(
69
+ await run(
70
+ ':root { --color-data-categorical-green: #008000; }',
71
+ 'app.css',
72
+ ),
73
+ ).toBeUndefined();
74
+ expect(
75
+ await run(
76
+ `/* @generated by \`astryx theme build\` */
77
+ @scope ([data-astryx-theme="ocean"]) {
78
+ :scope { --color-data-categorical-green: #008000; }
79
+ }`,
80
+ 'theme.css',
81
+ ),
82
+ ).toBeUndefined();
83
+ });
84
+ });
@@ -10,6 +10,12 @@
10
10
  import migrateDeprecatedThemeSurface, {
11
11
  meta as migrateDeprecatedThemeSurfaceMeta,
12
12
  } from './migrate-deprecated-theme-surface.mjs';
13
+ import migrateFieldInputStyling, {
14
+ meta as migrateFieldInputStylingMeta,
15
+ } from './migrate-field-input-styling.mjs';
16
+ import validateDataTokenOwnership, {
17
+ meta as validateDataTokenOwnershipMeta,
18
+ } from './validate-data-token-ownership.mjs';
13
19
 
14
20
  export default [
15
21
  {
@@ -17,4 +23,14 @@ export default [
17
23
  transform: migrateDeprecatedThemeSurface,
18
24
  meta: migrateDeprecatedThemeSurfaceMeta,
19
25
  },
26
+ {
27
+ name: 'validate-data-token-ownership',
28
+ transform: validateDataTokenOwnership,
29
+ meta: validateDataTokenOwnershipMeta,
30
+ },
31
+ {
32
+ name: 'migrate-field-input-styling',
33
+ transform: migrateFieldInputStyling,
34
+ meta: migrateFieldInputStylingMeta,
35
+ },
20
36
  ];
@@ -0,0 +1,198 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Migrate root styling on Field-composed inputs to their named parts.
5
+ *
6
+ * Field-composed inputs no longer accept root `xstyle`, `className`, or
7
+ * `style` (family:input-fields FR10). Each rename keeps the element the
8
+ * styling reached before: components whose root styling painted the visual
9
+ * control box move to `controlXstyle`/`controlClassName`/`controlStyle`;
10
+ * components whose root styling reached the Field box move to
11
+ * `containerXstyle`/`containerClassName`/`containerStyle`.
12
+ *
13
+ * Only JSX attributes written directly on an element bound to an Astryx import
14
+ * are renamed (named, aliased, or namespace imports). Spread attributes,
15
+ * wrappers that forward their own props, and unrelated components of the same
16
+ * name are left alone; those callsites fail type-checking and are migrated by
17
+ * hand. When the target attribute is already present, the root attribute gets a
18
+ * TODO instead of a rename so no value is silently dropped.
19
+ */
20
+
21
+ import {transformProp} from '../../transform-prop.mjs';
22
+
23
+ export const meta = {
24
+ title: 'Migrate input root styling to container/control parts',
25
+ description:
26
+ 'Renames root `xstyle`/`className`/`style` on Field-composed inputs to the `control*` or `container*` part they styled before.',
27
+ fileExtensions: ['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs'],
28
+ };
29
+
30
+ /** Components whose root styling painted the visual control box. */
31
+ const CONTROL_COMPONENTS = [
32
+ 'TextInput',
33
+ 'TextArea',
34
+ 'NumberInput',
35
+ 'FileInput',
36
+ 'DateInput',
37
+ 'DateRangeInput',
38
+ 'DateTimeInput',
39
+ 'TimeInput',
40
+ 'Selector',
41
+ 'MultiSelector',
42
+ 'ComplexSelector',
43
+ ];
44
+
45
+ /** Components whose root styling reached the Field box. */
46
+ const CONTAINER_COMPONENTS = [
47
+ 'Typeahead',
48
+ 'Tokenizer',
49
+ 'CheckboxList',
50
+ 'RadioList',
51
+ 'Slider',
52
+ ];
53
+
54
+ /**
55
+ * Field-root members that also render inside InputGroup. There Field is absent
56
+ * and root styling painted the control surface, so it moves to `control*`.
57
+ */
58
+ const GROUPED_CONTROL_COMPONENTS = new Set(['Typeahead']);
59
+
60
+ /** @type {ReadonlyMap<string, 'control' | 'container'>} */
61
+ const PART_BY_COMPONENT = new Map([
62
+ ...CONTROL_COMPONENTS.map(name => /** @type {const} */ ([name, 'control'])),
63
+ ...CONTAINER_COMPONENTS.map(
64
+ name => /** @type {const} */ ([name, 'container']),
65
+ ),
66
+ ]);
67
+
68
+ const ROOT_STYLE_PROPS = /** @type {const} */ ({
69
+ xstyle: 'Xstyle',
70
+ className: 'ClassName',
71
+ style: 'Style',
72
+ });
73
+
74
+ const PACKAGE_PATTERN = /^@(astryxdesign|xds)\/core(\/[A-Za-z]+)?$/u;
75
+
76
+ const TODO =
77
+ ' TODO(astryx upgrade): root styling is no longer accepted here; merge it into ';
78
+
79
+ /** @type {ReadonlyMap<string, ReadonlySet<string>>} */
80
+ const COMPONENT_PROPS = new Map(
81
+ [...PART_BY_COMPONENT.keys()].map(name => [
82
+ name,
83
+ new Set(Object.keys(ROOT_STYLE_PROPS)),
84
+ ]),
85
+ );
86
+
87
+ /**
88
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
89
+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
90
+ * @returns {string | undefined}
91
+ */
92
+ export default function migrateFieldInputStyling(file, api) {
93
+ if (!/xstyle|className|style/u.test(file.source)) return undefined;
94
+ if (![...PART_BY_COMPONENT.keys()].some(name => file.source.includes(name))) {
95
+ return undefined;
96
+ }
97
+
98
+ const j = api.jscodeshift;
99
+ const root = j(file.source);
100
+ const matchesImport = (/** @type {string} */ source) =>
101
+ PACKAGE_PATTERN.test(source);
102
+
103
+ // Local names that resolve to an Astryx InputGroup (named or namespace).
104
+ /** @type {Set<string>} */
105
+ const inputGroupNames = new Set();
106
+ /** @type {Set<string>} */
107
+ const namespaceNames = new Set();
108
+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {
109
+ const source = path.node.source.value;
110
+ if (path.node.importKind === 'type') return;
111
+ if (typeof source !== 'string' || !matchesImport(source)) return;
112
+ for (const specifier of path.node.specifiers ?? []) {
113
+ if (specifier.importKind === 'type') continue;
114
+ if (
115
+ specifier.type === 'ImportSpecifier' &&
116
+ specifier.imported?.name === 'InputGroup'
117
+ ) {
118
+ inputGroupNames.add(specifier.local?.name ?? 'InputGroup');
119
+ } else if (specifier.type === 'ImportNamespaceSpecifier') {
120
+ namespaceNames.add(specifier.local.name);
121
+ }
122
+ }
123
+ });
124
+
125
+ /** @param {any} elementPath a JSXElement path */
126
+ const isInputGroup = elementPath => {
127
+ const name = elementPath.node.openingElement.name;
128
+ let localName;
129
+ if (name.type === 'JSXIdentifier' && inputGroupNames.has(name.name)) {
130
+ localName = name.name;
131
+ } else if (
132
+ name.type === 'JSXMemberExpression' &&
133
+ name.object?.type === 'JSXIdentifier' &&
134
+ name.property?.type === 'JSXIdentifier' &&
135
+ name.property.name === 'InputGroup' &&
136
+ namespaceNames.has(name.object.name)
137
+ ) {
138
+ localName = name.object.name;
139
+ } else {
140
+ return false;
141
+ }
142
+ const scope = elementPath.scope?.lookup(localName);
143
+ return scope?.path.node.type === 'Program';
144
+ };
145
+
146
+ /** @param {any} openingPath a JSXOpeningElement path */
147
+ const isInsideInputGroup = openingPath => {
148
+ for (let p = openingPath.parent?.parent; p; p = p.parent) {
149
+ if (p.node.type === 'JSXElement' && isInputGroup(p)) return true;
150
+ }
151
+ return false;
152
+ };
153
+
154
+ let changed = false;
155
+ transformProp(
156
+ root,
157
+ j,
158
+ {matchesImport, components: COMPONENT_PROPS},
159
+ (propPath, {component}) => {
160
+ const attribute = propPath.node;
161
+ const openingPath = propPath.parent;
162
+ let part = PART_BY_COMPONENT.get(component);
163
+ if (!part) return;
164
+ if (
165
+ part === 'container' &&
166
+ GROUPED_CONTROL_COMPONENTS.has(component) &&
167
+ isInsideInputGroup(openingPath)
168
+ ) {
169
+ part = 'control';
170
+ }
171
+ const name = /** @type {keyof typeof ROOT_STYLE_PROPS} */ (
172
+ attribute.name.name
173
+ );
174
+ const next = part + ROOT_STYLE_PROPS[name];
175
+ const present = (openingPath.node.attributes ?? []).some(
176
+ (/** @type {any} */ a) =>
177
+ a.type === 'JSXAttribute' && a.name?.name === next,
178
+ );
179
+ if (present) {
180
+ const comment = `${TODO}\`${next}\`. `;
181
+ attribute.comments ??= [];
182
+ if (
183
+ !attribute.comments.some(
184
+ (/** @type {any} */ c) => c.value === comment,
185
+ )
186
+ ) {
187
+ attribute.comments.push(j.commentBlock(comment, true, false));
188
+ changed = true;
189
+ }
190
+ return;
191
+ }
192
+ attribute.name = j.jsxIdentifier(next);
193
+ changed = true;
194
+ },
195
+ );
196
+
197
+ return changed ? root.toSource({quote: 'single'}) : undefined;
198
+ }
@@ -0,0 +1,102 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Report data-token consumers that need an ownership migration.
5
+ *
6
+ * @input Consumer JavaScript/TypeScript source and generated theme CSS
7
+ * @output No rewritten source; actionable upgrade errors for fallback-less
8
+ * `var(--color-data-*)` uses (in JS strings, embedded or whole, and in CSS)
9
+ * and stale generated root-default artifacts
10
+ * @position Next-release upgrade validation for spec:AST-066
11
+ */
12
+
13
+ import * as path from 'node:path';
14
+
15
+ export const meta = {
16
+ title: 'Validate data-token ownership',
17
+ description:
18
+ 'Reports fallback-less data-token var() uses in source strings and stylesheets for manual CSS/non-CSS migration, and stale generated theme CSS that still owns root defaults.',
19
+ fileExtensions: ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.css'],
20
+ };
21
+
22
+ // A use without a fallback; `var(--color-data-x, <fallback>)` stays valid.
23
+ const DIRECT_DATA_VAR = /var\(\s*(--color-data-[a-z0-9-]+)\s*\)/u;
24
+ const CSS_COMMENT = /\/\*[\s\S]*?\*\//gu;
25
+ const GENERATED_THEME_HEADER = '@generated by `astryx theme build`';
26
+ const ROOT_DATA_DECLARATION = /:root\s*\{[^}]*--color-data-/su;
27
+
28
+ /** @param {any} node */
29
+ function staticString(node) {
30
+ if (
31
+ (node?.type === 'StringLiteral' || node?.type === 'Literal') &&
32
+ typeof node.value === 'string'
33
+ ) {
34
+ return node.value;
35
+ }
36
+ if (node?.type === 'TemplateLiteral') {
37
+ // Each static chunk of the template; a use can sit between expressions.
38
+ return (node.quasis ?? [])
39
+ .map((/** @type {any} */ q) => q?.value?.cooked ?? q?.value?.raw ?? '')
40
+ .join('\u0000');
41
+ }
42
+ return undefined;
43
+ }
44
+
45
+ /**
46
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
47
+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
48
+ * @returns {undefined}
49
+ */
50
+ export default function validateDataTokenOwnership(file, api) {
51
+ if (!file.source.includes('--color-data-')) return undefined;
52
+
53
+ if (path.extname(file.path) === '.css') {
54
+ if (
55
+ file.source.includes(GENERATED_THEME_HEADER) &&
56
+ ROOT_DATA_DECLARATION.test(file.source)
57
+ ) {
58
+ throw new Error(
59
+ 'This generated theme CSS still emits canonical data defaults at :root. Rebuild it with `astryx theme build`; defaults now come from compiled dataVars consumers.',
60
+ );
61
+ }
62
+ const uncommented = file.source.replace(CSS_COMMENT, comment =>
63
+ comment.replace(/[^\n]/gu, ' '),
64
+ );
65
+ const cssMatch = DIRECT_DATA_VAR.exec(uncommented);
66
+ if (cssMatch) {
67
+ const line = uncommented.slice(0, cssMatch.index).split('\n').length;
68
+ throw new Error(
69
+ `Raw var(${cssMatch[1]}) without a fallback at line ${line} needs manual migration: compiled dataVars output is not guaranteed in this stylesheet, so add an explicit fallback or style the element from code that imports dataVars from @astryxdesign/core/theme/dataTokens.stylex.`,
70
+ );
71
+ }
72
+ return undefined;
73
+ }
74
+
75
+ const j = api.jscodeshift;
76
+ const root = j(file.source);
77
+ /** @type {{token: string, line: number|null}|null} */
78
+ let found = null;
79
+ const inspect = (/** @type {any} */ node) => {
80
+ if (found) return;
81
+ const value = staticString(node);
82
+ const match =
83
+ typeof value === 'string' ? value.match(DIRECT_DATA_VAR) : null;
84
+ if (match) {
85
+ found = {token: match[1], line: node.loc?.start?.line ?? null};
86
+ }
87
+ };
88
+
89
+ /** @param {any} nodePath */
90
+ const inspectPath = nodePath => inspect(nodePath.node);
91
+ root.find(j.StringLiteral).forEach(inspectPath);
92
+ root.find(j.Literal).forEach(inspectPath);
93
+ root.find(j.TemplateLiteral).forEach(inspectPath);
94
+
95
+ if (found) {
96
+ const {token, line} = found;
97
+ throw new Error(
98
+ `Direct var(${token})${line == null ? '' : ` at line ${line}`} needs manual migration: CSS-capable code imports dataVars from @astryxdesign/core/theme/dataTokens.stylex; Canvas and other non-CSS APIs use resolveThemeToken() or useTheme().token().`,
99
+ );
100
+ }
101
+ return undefined;
102
+ }
@@ -34,10 +34,10 @@ export const docs = {
34
34
  {
35
35
  title: 'defineTheme',
36
36
  content: [
37
- {type: 'prose', text: "defineTheme creates a theme from token overrides and optional scale configs. Only override tokens that differ from defaults; omitted tokens use the design system defaults. Scale configs generate tokens from parameters. Explicit token overrides always take precedence over scale-generated values, token by token. localTokens accepts any valid CSS custom-property name; prefixes do not establish ownership. One caveat for the accent: overriding --color-accent in tokens re-points the reference tokens (--color-accent-muted, --color-text-accent, --color-icon-accent) but NOT --color-on-accent, which stays baked from the color.accent seed. To give each scheme its own accent with a consistent derived palette, pass a [light, dark] tuple to color.accent instead of overriding the token."},
38
- {type: 'code', lang: 'tsx', label: 'defineTheme with scale configs', code: "import {defineTheme} from '@astryxdesign/core/theme';\n\nconst myTheme = defineTheme({\n name: 'my-theme',\n // accent: single hex, or [light, dark] tuple to seed each scheme separately\n color: { accent: ['#7B61FF', '#9B85FF'], neutralStyle: 'cool' },\n typography: {\n scale: { base: 14, ratio: 1.2 },\n body: { family: 'Inter', fallbacks: '-apple-system, sans-serif' },\n },\n radius: { base: 4, multiplier: 1 },\n motion: { fast: 175, medium: 410, ratio: 0.75 },\n tokens: {\n // Explicit overrides take precedence over scale-generated values\n '--color-background-body': ['#FFFFFF', '#0A0A0A'],\n },\n});"},
37
+ {type: 'prose', text: 'defineTheme creates a theme from explicit token overrides and optional scale configs. Existing themes may use `color` to expand an accent seed into neutral, surface, text, border, and related values; it is not an accent-only edit. Keep that configuration when preserving existing output. For new complete palettes, generate and review a committed palette module, then import its `palette` export and reference stable stops from semantic tokens. This keeps mapped roles coherent when the accepted palette is regenerated; generation itself does not rewrite the theme. Other scale configs generate typography, radius, and motion values from parameters. Explicit token overrides always take precedence over scale-generated values, token by token. When an existing `color` config is in use, overriding `--color-accent` in `tokens` re-points `--color-accent-muted`, `--color-text-accent`, and `--color-icon-accent`, but `--color-on-accent` stays baked from the `color.accent` seed. Prefer a `[light, dark]` tuple for `color.accent` over overriding `--color-accent` alone. localTokens accepts any valid CSS custom-property name; prefixes do not establish ownership.'},
38
+ {type: 'code', lang: 'tsx', label: 'defineTheme with generated palette references and non-color scale configs', code: "import {defineTheme} from '@astryxdesign/core/theme';\nimport {palette} from './palette.generated';\n\nconst myTheme = defineTheme({\n name: 'my-theme',\n typography: {\n scale: { base: 14, ratio: 1.2 },\n body: { family: 'Inter', fallbacks: '-apple-system, sans-serif' },\n },\n radius: { base: 4, multiplier: 1 },\n motion: { fast: 175, medium: 410, ratio: 0.75 },\n tokens: {\n '--color-background-surface': [\n palette.neutral.light[100],\n palette.neutral.dark[15],\n ],\n },\n});"},
39
39
  {type: 'table', headers: ['Config', 'Generates', 'Parameters'], rows: [
40
- ['color', '--color-accent, --color-background-*, --color-text-*, --color-border, etc.', 'accent? (hex or [light, dark] tuple; omit for neutral-only), neutralStyle? (warm|cool|neutral), contrast? (standard|high)'],
40
+ ['color (existing themes)', '--color-accent, --color-background-*, --color-text-*, --color-border, etc.', 'Supported broad scale: accent? (hex or [light, dark] tuple), neutralStyle? (warm|cool|neutral), contrast? (standard|high). Use theme palette generate for new complete palettes.'],
41
41
  ['typography.scale', '--text-heading-*-size/weight/leading, --text-body-size/weight/leading', 'base (px), ratio'],
42
42
  ['typography.body/heading/code', '--font-family-body, --font-family-heading, --font-family-code', 'family, fallbacks?, url?, weight?'],
43
43
  ['radius', '--radius-inner, --radius-element, --radius-container, --radius-page, --radius-chat', 'base (px), multiplier (0–2)'],
@@ -157,7 +157,7 @@ export const docs = {
157
157
  {
158
158
  title: 'useTheme Hook',
159
159
  content: [
160
- {type: 'prose', text: '`useTheme()` reads the nearest Theme and effective color mode from React context. Use it inside client components for SVG, canvas, charts, maps, and third-party configuration objects that need token values in JavaScript.'},
160
+ {type: 'prose', text: '`useTheme()` reads the nearest Theme and effective color mode from React context. Prefer `dataVars` for CSS-capable SVG and DOM values. Use this hook for canvas, charts, maps, third-party configuration objects, or an SVG API that requires a concrete JavaScript color instead of a `var(...)` reference.'},
161
161
  {type: 'code', lang: 'tsx', label: 'Access resolved token values in React', code: "import {useMemo} from 'react';\nimport {useTheme} from '@astryxdesign/core/theme';\n\nfunction ChartConfig() {\n const {mode, tokens} = useTheme();\n const options = useMemo(() => ({\n mode,\n textColor: tokens['--color-text-primary'],\n gridColor: tokens['--color-border'],\n seriesColor: tokens['--color-data-categorical-blue'],\n }), [mode, tokens]);\n return <Chart options={options} />;\n}"},
162
162
  {type: 'prose', text: 'Prefer CSS variables for ordinary styling. See {@link generic:use-a-theme} for the provider setup, and {@link namespace:tokens} for the full token reference.'},
163
163
  ],
@@ -17,14 +17,14 @@ export const docs = {
17
17
  "order": 20
18
18
  },
19
19
  "category": "foundations",
20
- "description": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex.",
20
+ "description": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import dataVars from @astryxdesign/core/theme/dataTokens.stylex for CSS-capable code. Retaining any member emits the complete 56-variable group; an unused graph emits none.",
21
21
  "sections": [
22
22
  {
23
23
  "title": "Data Visualization Tokens",
24
24
  "content": [
25
25
  {
26
26
  "type": "prose",
27
- "text": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import their public StyleX variables from @astryxdesign/core/theme/dataTokens.stylex."
27
+ "text": "Colors for charts and graphs: one categorical accent per series, a neutral for labels and reference lines, and sequential ramps from 5 (darkest) to 1 (lightest) for ordered scales and heatmaps. Import dataVars from @astryxdesign/core/theme/dataTokens.stylex for CSS-capable code. Retaining any member emits the complete 56-variable group; an unused graph emits none."
28
28
  },
29
29
  {
30
30
  "type": "table",