An open source design system that's fully customizable and agent ready
TypeScript
fix(api-report): an overloaded component's row reads its last signature (#9743)
Christopher Chedeau275a3f84c297
diff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex b23935f5fb..c9d3131599 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -1166,11 +1166,12 @@ component FieldLabel(props: FieldLabelProps)prop ref?: React.Ref<HTMLLabelElement>prop xstyle?: StyleXStylesinherits AriaAttributes, DOMAttributes, HTMLAttributes-component FieldStatus @deprecated+component FieldStatus(props: FieldStatusProps)+ overload (props: FieldStatusProps & { variant: 'tooltip' }) => React.JSX.Element @deprecatedprop message: stringprop ref?: React.Ref<HTMLDivElement>prop type: InputStatusType- prop variant: FieldStatusVariant = 'attached'+ prop variant?: FieldStatusVariant = 'attached'prop xstyle?: StyleXStylesinherits AriaAttributes, DOMAttributes, HTMLAttributescomponent FileInput(props: FileInputProps)@@ -2609,6 +2610,7 @@ component Token(props: TokenProps)prop xstyle?: StyleXStylesinherits AriaAttributes, DOMAttributes, HTMLAttributescomponent Tokenizer(props: TokenizerProps)+ overload <T extends SearchableItem>(props: Omit<TokenizerProps<T>, 'ref' | 'experimental'> & { experimental: NonNullable<TokenizerProps<T>['experimental']>; ref?: React.Ref<HTMLInputElement | HTMLButtonElement> }) => React.JSX.Element @experimentalprop containerClassName?: stringprop containerStyle?: CSSPropertiesprop containerXstyle?: StyleXStyles@@ -2620,6 +2622,7 @@ component Tokenizer(props: TokenizerProps)prop disabledMessage?: stringprop emptySearchText?: ReactNode = 'No results found'prop endContent?: ReactNode+ prop experimental?: { presentation?: 'popover' | 'bottom-sheet' | 'adaptive' } @experimentalprop handleRef?: React.Ref<TokenizerHandle>prop hasAutoFocus?: boolean = falseprop hasClear?: boolean = false@@ -4301,13 +4304,7 @@ interface FieldStatusInputmessageID?: stringtype: FieldStatusTypetype FieldStatusPlacement = keyof FieldStatusVariantMap | 'tooltip'-interface FieldStatusProps extends BaseProps<HTMLDivElement>- message: string- ref?: React.Ref<HTMLDivElement>- type: InputStatusType- variant?: FieldStatusVariant = 'attached'- xstyle?: StyleXStyles- inherits AriaAttributes, DOMAttributes, HTMLAttributes+interface FieldStatusProps extends BaseProps<HTMLDivElement> (props of FieldStatus)type FieldStatusType = 'warning' | 'error' | 'success'type FieldStatusVariant = keyof FieldStatusVariantMapinterface FieldStatusVariantMapdiff --git a/scripts/api-report/__fixtures__/repo/packages/demo/lib/index.d.ts b/scripts/api-report/__fixtures__/repo/packages/demo/lib/index.d.tsindex 5f30edea94..5f49a33795 100644--- a/scripts/api-report/__fixtures__/repo/packages/demo/lib/index.d.ts+++ b/scripts/api-report/__fixtures__/repo/packages/demo/lib/index.d.ts@@ -12,6 +12,38 @@ export interface ChipProps {onSelect?(id: string): void;}export declare function Chip(props: ChipProps): ReactNode;+export interface BadgeProps {+ /** Text the badge shows. */+ label: string;+ /** @default 'neutral' */+ tone?: 'neutral' | 'accent';+}+type BadgeExperimentalProps = Omit<BadgeProps, 'tone'> & {+ /** @experimental */+ experimental: {glow?: boolean};+};+interface BadgeColorProps extends BadgeProps {+ /** A color name. */+ color: string;+}+/** @deprecated `color` is gone: set `tone`. */+export declare function Badge(props: BadgeColorProps): ReactNode;+export declare function Badge(props: BadgeExperimentalProps): ReactNode;+export declare function Badge(props: BadgeProps): ReactNode;+export interface TagProps {+ text: string;+}+/** @deprecated Use Badge. */+export declare const Tag: {+ (props: TagProps & {color: string}): ReactNode;+ (props: TagProps): ReactNode;+};+export interface PillProps {+ size: number;+}+export declare function Pill(props: PillProps & {legacy: true}): ReactNode;+/** @internal */+export declare function Pill(props: PillProps): ReactNode;export declare function useChipState(initial?: boolean,): readonly [boolean, (next: boolean) => void];@@ -25,3 +57,6 @@ export interface ChipExperimentalOptions {pulse?: boolean;}export declare const THEME_ATTR = 'data-astryx-theme';+// Only the declarations marked `export` are public: the two Badge props types+// above without it stay private.+export {};diff --git a/scripts/api-report/api-report.test.mjs b/scripts/api-report/api-report.test.mjsindex 37d2ed119f..b5a1d9d57c 100644--- a/scripts/api-report/api-report.test.mjs+++ b/scripts/api-report/api-report.test.mjs@@ -3,8 +3,9 @@/*** @file Tests for the API report generator and the API changes renderer.* @input `__fixtures__/repo`: a built fixture package with every row kind, an- * `./internal/*` entry point, a stylesheet, a component doc with- * theming targets, a private package, and a public-attribute record+ * overloaded component, an `./internal/*` entry point, a stylesheet,+ * a component doc with theming targets, a private package, and a+ * public-attribute record* @output Vitest assertions on report content, order, determinism, and change rows* @position scripts/api-report — guards architecture:public-component-api INV24*/@@ -86,6 +87,32 @@ describe('generateReport', () => {expect(report).toContain('interface ChipExperimentalOptions @experimental');});+ it('reads an overloaded component as ComponentProps does, and lists its other signatures as tagged overloads', () => {+ expect(report).toMatch(/^component Badge\(props: BadgeProps\)$/m);+ expect(report).toContain(+ ' overload (props: BadgeProps & { color: string }) => ReactNode @deprecated',+ );+ expect(report).toContain(+ " overload (props: Omit<BadgeProps, 'tone'> & { experimental: { glow?: boolean } }) => ReactNode @experimental",+ );+ expect(report).toContain('interface BadgeProps (props of Badge)');+ expect(report).not.toContain('BadgeColorProps');+ expect(report).not.toContain('BadgeExperimentalProps');+ });++ it('keeps the statement tags of an overloaded component declared as a const', () => {+ expect(report).toMatch(/^component Tag\(props: TagProps\) @deprecated$/m);+ expect(report).toMatch(+ /^ {2}overload \(props: TagProps & \{color: string\}\) => ReactNode$/m,+ );+ expect(report).toContain('interface TagProps (props of Tag)');+ });++ it('lists an overloaded component as internal when its row is', () => {+ expect(report).toMatch(/^component Pill\(props: PillProps\) @internal$/m);+ expect(report).toContain('internal Pill via .');+ });+it('leaves out ./internal/*, commented-out custom properties, and unlisted attributes', () => {expect(report).not.toContain('secret');expect(report).not.toContain('--commented-out');@@ -350,6 +377,15 @@ describe('API changes', () => {);});+ it("gives a component's overload line the component's usage example", () => {+ const overloads = [...parseReport(report).values()].filter(+ r => r.item === 'component Badge' && r.member?.startsWith('overload '),+ );+ expect(overloads).toHaveLength(2);+ for (const row of overloads)+ expect(usageFor('@astryxdesign/demo', row)).toBe('<Badge … />');+ });+it('renders nothing when the API is unchanged and the committed report is current', () => {const changes = computeChanges([{diff --git a/scripts/api-report/changes.mjs b/scripts/api-report/changes.mjsindex 491e37c326..44d1ee4099 100644--- a/scripts/api-report/changes.mjs+++ b/scripts/api-report/changes.mjs@@ -160,6 +160,8 @@ export function usageFor(pkg, row) {: `import '${spec}'`;if (kind === 'component') {if (!row.member || row.member === 'inherits') return `<${name} />`;+ // An overload line is another call shape of the component, not a prop.+ if (row.member.startsWith('overload ')) return `<${name} … />`;const literal = row.line.match(/'([^']+)'/);const value = literal? `"${literal[1]}"`diff --git a/scripts/api-report/generate.mjs b/scripts/api-report/generate.mjsindex 0959b9950b..9c9401d2d5 100644--- a/scripts/api-report/generate.mjs+++ b/scripts/api-report/generate.mjs@@ -259,7 +259,11 @@ export async function generateReport(opts) {return out.length ? ` ${out.join(' ')}` : '';};+ // Array#map passes an index second, so oneSig keeps a single parameter.function oneSig(sig) {+ return sigText(sig, declared);+ }+ function sigText(sig, paramType) {const d = sig.getDeclaration();if (!d || !inPkg(d.getSourceFile()) || !d.parameters) {return cap(@@ -277,7 +281,7 @@ export async function generateReport(opts) {: '';const params = d.parameters.map(p => {const name = ts.isIdentifier(p.name) ? p.name.text : '{…}';- const t = p.type ? declared(p.type) : show(checker.getTypeAtLocation(p));+ const t = p.type ? paramType(p.type) : show(checker.getTypeAtLocation(p));return `${p.dotDotDotToken ? '...' : ''}${name}${p.questionToken || p.initializer ? '?' : ''}: ${t}`;});const ret = d.type ? declared(d.type) : show(sig.getReturnType());@@ -354,8 +358,12 @@ export async function generateReport(opts) {!!(type.getProperty('Provider') && type.getProperty('Consumer'));function componentProps(name, type) {if (!/^[A-Z]/.test(name) || isContext(type)) return null;- const sig = type.getCallSignatures()[0];+ // `ComponentProps<typeof X>` reads an overloaded component's last+ // signature, so the component row does too; the others become overloads.+ const sigs = type.getCallSignatures();+ const sig = sigs.at(-1);if (!sig || sig.parameters.length > 2) return null;+ const overloads = sigs.slice(0, -1);const exotic = !!type.getProperty('$$typeof');const returnsElement =/\b(JSX\.Element|ReactNode|ReactElement|Element)\b/.test(@@ -363,15 +371,96 @@ export async function generateReport(opts) {);if (!exotic && !returnsElement) return null;const p = sig.parameters[0];- if (!p) return {propsName: null, propsType: null};+ if (!p) return {propsName: null, propsType: null, sig, overloads};const propsType = checker.getTypeOfSymbol(p);const alias = propsType.aliasSymbol?.name ?? propsType.symbol?.name;return {propsName: alias && !alias.startsWith('__') ? alias : null,propsType,+ sig,+ overloads,};}+ // The symbols the entry points export. An overload line prints a private+ // props alias or interface by its definition instead of its name. A private+ // type nested deeper still prints by name.+ const publicSymbols = new Set();+ for (const e of entries.filter(e => e.kind === 'code')) {+ const sf = program.getSourceFile(e.abs);+ const modSym = sf && (checker.getSymbolAtLocation(sf) ?? sf.symbol);+ for (const ex of modSym ? checker.getExportsOfModule(modSym) : []) {+ publicSymbols.add(+ ex.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(ex) : ex,+ );+ }+ }+ const privateTypeSymbol = node => {+ if (!ts.isTypeReferenceNode(node)) return null;+ let s = checker.getSymbolAtLocation(node.typeName);+ if (s && s.flags & ts.SymbolFlags.Alias) s = checker.getAliasedSymbol(s);+ const d = s?.declarations?.[0];+ return d && inPkg(d.getSourceFile()) && !publicSymbols.has(s) ? s : null;+ };+ const printer = ts.createPrinter({removeComments: true});+ const print = node =>+ norm(+ printer.printNode(ts.EmitHint.Unspecified, node, node.getSourceFile()),+ );+ const definition = sym => {+ const alias = sym.declarations.find(ts.isTypeAliasDeclaration);+ if (alias) return {text: print(alias.type), params: alias.typeParameters};+ const faces = sym.declarations.filter(ts.isInterfaceDeclaration);+ if (!faces.length) return null;+ const bases = faces.flatMap(+ f => f.heritageClauses?.flatMap(h => h.types.map(print)) ?? [],+ );+ const members = faces.flatMap(f => f.members.map(print));+ const body = members.length ? [`{ ${members.join('; ')} }`] : [];+ return {+ text: [...bases, ...body].join(' & ') || '{}',+ params: faces[0].typeParameters,+ };+ };+ // A private props type prints as its definition, without comments, with+ // the reference's type arguments in place of its own parameters.+ const publicTypeText = node => {+ const sym = privateTypeSymbol(node);+ const def = sym && definition(sym);+ if (!def) return declared(node);+ const args = new Map(+ (def.params ?? []).map((tp, i) => [+ tp.name.text,+ norm(+ (node.typeArguments?.[i] ?? tp.default)?.getText() ?? tp.name.text,+ ),+ ]),+ );+ // The rename is textual, so a key or literal spelled like a parameter+ // changes too.+ const renamed = [...args].filter(([from, to]) => from !== to);+ return cap(+ renamed.length+ ? def.text.replace(+ new RegExp(+ `\\b(${renamed.map(([from]) => from).join('|')})\\b`,+ 'g',+ ),+ from => args.get(from),+ )+ : def.text,+ );+ };+ // An overload line carries its own declaration's tags, and @experimental+ // when its props type's name says so, as a member's name does.+ const overloadLine = sig => {+ const d = sig.getDeclaration();+ const t = d?.parameters?.[0]?.type;+ const propsName =+ t && ts.isTypeReferenceNode(t) ? t.typeName.getText() : '';+ return ` overload ${sigText(sig, publicTypeText)}${marks(d, propsName)}`;+ };+// ---- entry point sections; each declaration is detailed once -----------const seen = new Map(); // declaration identity -> first entry pointconst propsOf = new Map(); // props type name -> component@@ -443,7 +532,8 @@ export async function generateReport(opts) {}seen.set(identity, e.subpath);const m = marks(decl, name);- if (m.includes('@internal')) internal.push(`${name} via ${e.subpath}`);+ // The internal list reads the same tags as the item's row.+ let rowTags = m;if (sym.flags & ts.SymbolFlags.Class) {groups.Classes.push([@@ -458,8 +548,16 @@ export async function generateReport(opts) {const comp = componentProps(name, type);if (comp) {if (comp.propsName) propsOf.set(comp.propsName, name);+ // A function's overloads carry their own tags, so its row takes the+ // last one's. A `const` keeps its statement's tags.+ const last = comp.sig.getDeclaration();+ rowTags =+ comp.overloads.length && last && ts.isFunctionDeclaration(last)+ ? marks(last, name)+ : m;groups.Components.push([- `component ${name}${comp.propsName ? `(props: ${comp.propsName})` : ''}${m}`,+ `component ${name}${comp.propsName ? `(props: ${comp.propsName})` : ''}${rowTags}`,+ ...comp.overloads.map(overloadLine),...(comp.propsType ? members(comp.propsType, 'prop ') : []),]);} else if (isContext(type)) {@@ -527,6 +625,8 @@ export async function generateReport(opts) {body: () => d.members.map(x => ` ${norm(x.getText())}`),});}+ if (rowTags.includes('@internal'))+ internal.push(`${name} via ${e.subpath}`);}sections.push({head, groups, empty: !exported.length});}