/** * Prop extractor — resolves React component props via TypeScript's type checker. * * Two extraction paths: * * **Path 1 (primary)**: `resolvePropsFromStoryFile()` — finds JSX elements in an existing story * file that match the target component, then calls `checker.getResolvedSignature()` to extract the * full props type. Works for ~95% of components (any story with JSX usage). * * **Path 2 (fallback)**: `resolvePropsFromComponentType()` — for args-only stories with no JSX, * inspects the component's type directly via `getCallSignatures()[0].parameters[0]` (similar to * Vue's component-meta approach). Does NOT work for polymorphic/generic components (TS #61133). * * The story path returns the selected component target together with its props type, and the * fallback path still resolves the props type directly. `serializeComponentDoc()` uses the selected * symbol and component ref from that target so member components keep their own metadata. * * TypeScript resolves props the same way as autocompletion — by calling * `checker.getResolvedSignature()` on the JSX element. For polymorphic components with generic call * signatures (e.g. Mantine's polymorphicFactory), TypeScript instantiates the generic with its * default type parameter, giving the correct concrete props. This avoids the `ComponentProps` / * `infer P` limitation (TS #61133). */ import type ts from 'typescript'; import { extractComponentJsDocInfo } from 'storybook/internal/component-meta'; import type { ComponentRef, ResolvedComponentTarget } from '../types.ts'; import { groupByToMap } from '../utils.ts'; import type { DocgenTypeChecker, DocgenTypeScript } from '@storybook/component-meta-typescript'; // --------------------------------------------------------------------------- // Output types — compatible with react-docgen-typescript's ComponentDoc shape // --------------------------------------------------------------------------- export interface PropItemType { name: string; raw?: string; value?: { value: string }[]; // Array element type, such as `string` for `string[]`. element?: PropItemType; } export interface ParentType { name: string; fileName: string; } export interface PropItem { name: string; required: boolean; type: PropItemType; description: string; defaultValue: { value: string } | null; parent?: ParentType; declarations?: ParentType[]; } export interface ComponentDoc { displayName?: string; exportName: string; filePath: string; description: string; jsDocTags?: Record; props: Record; } // --------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------- /** * Props from a single `.d.ts` or `node_modules` declaration file exceeding this count are * bulk-excluded from the manifest. This filters out HTML attribute interfaces (100+ props) and * generated CSS-in-JS types (e.g. Panda CSS styled-system) while keeping user-defined props. * * The threshold is per source file — a user's own interface with 31 props in a `.tsx` file is NOT * affected (only `.d.ts` and `node_modules` paths are checked). */ const LARGE_SOURCE_THRESHOLD = 30; /** Max recursion depth for unwrapping React.memo/forwardRef/Object.assign chains. */ const MAX_UNWRAP_DEPTH = 5; const MAX_SERIALIZATION_DEPTH = 5; const ARRAY_SYMBOL_NAMES = new Set(['Array', 'ReadonlyArray']); type WrappedExpression = | ts.ParenthesizedExpression | ts.AsExpression | ts.NonNullExpression | ts.SatisfiesExpression; function isLiteralType(type: ts.Type): type is ts.LiteralType { return type.isStringLiteral() || type.isNumberLiteral(); } function isUnionType(type: ts.Type): type is ts.UnionType { return type.isUnion(); } function isWrappedExpression( typescript: DocgenTypeScript, expression: ts.Expression ): expression is WrappedExpression { return ( typescript.isParenthesizedExpression(expression) || typescript.isAsExpression(expression) || typescript.isNonNullExpression(expression) || (typescript.isSatisfiesExpression?.(expression) ?? false) ); } function resolveAliasedSymbol( typescript: DocgenTypeScript, checker: DocgenTypeChecker, symbol: ts.Symbol ): ts.Symbol { return symbol.flags & typescript.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol; } function getSymbolContextNode(symbol: ts.Symbol): ts.Node | undefined { return symbol.valueDeclaration ?? symbol.getDeclarations()?.[0]; } function resolveComponentSymbolFromNode( typescript: DocgenTypeScript, checker: DocgenTypeChecker, node: ts.Node | undefined ): ts.Symbol | undefined { if (!node) { return undefined; } const symbol = checker.getSymbolAtLocation(node); return symbol ? resolveComponentSymbol(typescript, checker, symbol, node) : undefined; } /** * Normalizes the symbol we get from JSX/member resolution to the declaration symbol that owns the * component metadata. * * For top-level components, TypeScript usually gives us the declaration symbol directly. For member * selections it often gives an intermediate symbol instead, for example: * * - A shorthand/property symbol from `export const Accordion = { Root }` * - An attached-member symbol from `ButtonRoot.Aligner = Aligner` * - A property signature from `Aligner: typeof Aligner` * - An anonymous function symbol (`__function`) for `const Aligner = () => ...` * * Those symbols do not reliably carry the selected member's JSDoc/defaults, so we follow them back * to the actual component declaration before serialization. */ function resolveComponentSymbol( typescript: DocgenTypeScript, checker: DocgenTypeChecker, symbol: ts.Symbol, contextNode: ts.Node, depth = 0 ): ts.Symbol { let resolved = resolveAliasedSymbol(typescript, checker, symbol); if (depth > MAX_UNWRAP_DEPTH) { return resolved; } const declarationForPromotion = getSymbolContextNode(resolved); if ( declarationForPromotion && (typescript.isArrowFunction(declarationForPromotion) || typescript.isFunctionExpression(declarationForPromotion)) && declarationForPromotion.parent && typescript.isVariableDeclaration(declarationForPromotion.parent) && typescript.isIdentifier(declarationForPromotion.parent.name) ) { const variableSymbol = checker.getSymbolAtLocation(declarationForPromotion.parent.name); if (variableSymbol) { resolved = resolveAliasedSymbol(typescript, checker, variableSymbol); } } const declaration = getSymbolContextNode(resolved); if (declaration) { if (typescript.isShorthandPropertyAssignment(declaration)) { const valueSymbol = checker.getShorthandAssignmentValueSymbol(declaration); if (valueSymbol) { return resolveComponentSymbol( typescript, checker, valueSymbol, declaration.name, depth + 1 ); } } if (typescript.isPropertyAssignment(declaration)) { const next = resolveComponentSymbolFromNode(typescript, checker, declaration.initializer); if (next) { return next; } } if ( typescript.isBinaryExpression(declaration) && declaration.operatorToken.kind === typescript.SyntaxKind.EqualsToken ) { const next = resolveComponentSymbolFromNode(typescript, checker, declaration.right); if (next) { return next; } } } const shouldUseTypeSymbolFallback = Boolean(resolved.flags & typescript.SymbolFlags.Property) || (declaration !== undefined && (typescript.isPropertyAssignment(declaration) || typescript.isShorthandPropertyAssignment(declaration) || typescript.isPropertySignature(declaration) || typescript.isPropertyDeclaration(declaration) || (typescript.isBinaryExpression(declaration) && declaration.operatorToken.kind === typescript.SyntaxKind.EqualsToken))); const typeSymbol = shouldUseTypeSymbolFallback && checker.getTypeOfSymbolAtLocation(resolved, contextNode).getSymbol?.(); if (typeSymbol) { const resolvedTypeSymbol = resolveAliasedSymbol(typescript, checker, typeSymbol); const typeDeclaration = getSymbolContextNode(resolvedTypeSymbol); if (resolvedTypeSymbol !== resolved && typeDeclaration) { return resolveComponentSymbol( typescript, checker, resolvedTypeSymbol, typeDeclaration, depth + 1 ); } } return resolved; } // --------------------------------------------------------------------------- // Story-based prop extraction (probe-free) // --------------------------------------------------------------------------- /** Finds the story-local import binding for a {@link ComponentRef}. */ export function findImportSymbolInStoryFile( typescript: DocgenTypeScript, checker: DocgenTypeChecker, storySourceFile: ts.SourceFile, componentRef: ComponentRef ): ts.Symbol | undefined { const importSpecifier = componentRef.importId; const importName = componentRef.importName; const memberAccess = componentRef.member; if (!importSpecifier) { return undefined; } // Step 1: Find the import binding symbol in the story file. // This is the local symbol that the story uses in JSX (e.g., `Button` from `import { Button } from './Button'`). for (const stmt of storySourceFile.statements) { if (!typescript.isImportDeclaration(stmt)) { continue; } const moduleSpec = stmt.moduleSpecifier; if (!typescript.isStringLiteral(moduleSpec)) { continue; } if (moduleSpec.text !== importSpecifier) { continue; } const clause = stmt.importClause; if (!clause) { continue; } let importSymbol: ts.Symbol | undefined; if (importName === 'default') { // Default import: import Button from '...' if (clause.name) { importSymbol = checker.getSymbolAtLocation(clause.name); } // Also check named imports for `{ default as Button }` pattern if ( !importSymbol && clause.namedBindings && typescript.isNamedImports(clause.namedBindings) ) { for (const spec of clause.namedBindings.elements) { const originalName = (spec.propertyName ?? spec.name).text; if (originalName === 'default') { importSymbol = checker.getSymbolAtLocation(spec.name); break; } } } } else if (clause.namedBindings && typescript.isNamedImports(clause.namedBindings)) { // Named import: import { Button } from '...' or import { Button as Btn } from '...' for (const spec of clause.namedBindings.elements) { const originalName = (spec.propertyName ?? spec.name).text; if (originalName === importName) { importSymbol = checker.getSymbolAtLocation(spec.name); break; } } } // Namespace import: import * as Ns from '...' // Only applies when memberAccess is set (compound components accessed as ). // Without this guard, a namespace import from the same module could shadow a named // import we're actually looking for (e.g. `import * as X from './m'; import { Y } from './m'`). if ( !importSymbol && memberAccess && clause.namedBindings && typescript.isNamespaceImport(clause.namedBindings) ) { importSymbol = checker.getSymbolAtLocation(clause.namedBindings.name); } if (importSymbol) { return importSymbol; } } return undefined; } /** Returns whether `componentRef` is the story meta's `component`, not a declared subcomponent. */ export function metaComponentMatchesRef( typescript: DocgenTypeScript, checker: DocgenTypeChecker, storySourceFile: ts.SourceFile, componentRef: ComponentRef, metaComponentInitializer: ts.Expression ): boolean { const refSymbol = findImportSymbolInStoryFile(typescript, checker, storySourceFile, componentRef); const metaSymbol = resolveComponentSymbolFromNode(typescript, checker, metaComponentInitializer); // Plain symbol equality only when the ref is not a member expression — otherwise // `Button.Aligner` would match `meta.component: Button` because both resolve to the Button import. if (refSymbol && metaSymbol && !componentRef.member) { return ( resolveAliasedSymbol(typescript, checker, refSymbol) === resolveAliasedSymbol(typescript, checker, metaSymbol) ); } if (typescript.isIdentifier(metaComponentInitializer)) { return componentRef.componentName === metaComponentInitializer.text; } if ( typescript.isPropertyAccessExpression(metaComponentInitializer) && typescript.isIdentifier(metaComponentInitializer.expression) ) { const metaName = `${metaComponentInitializer.expression.text}.${metaComponentInitializer.name.text}`; return componentRef.componentName === metaName; } return false; } /** * Resolves the selected component symbol and props type by finding JSX usage of the target * component in a story file. * * Story files already contain JSX like `