Story format and analysis
Storybook interprets user-authored Component Story Format (CSF) and MDX files as a shared data model. It parses story declarations, turns them into index entries, extracts component and documentation metadata, and supplies that data to the preview, manager, docs pages, and developer tools. This page extends Storybook runtime architecture and relates to preview runtime, CLI and server lifecycle, and manager UI.
CSF source model
CSF is the source format that describes a component, its stories, and the annotations that control how each story is shown. The shared story contract also gives these annotations a common shape for args, argTypes, controls, parameters, tags, and lifecycle behavior. The analysis model keeps the component metadata, story metadata, export names, stable ids, tags, and source locations connected so later systems can load the right module and render the right story.
The model accepts the main CSF shapes without requiring the runtime to execute the source during indexing:
- A default export describes the component or story group.
- Named exports describe individual stories.
- Story annotations can be object fields or top-level assignments from older CSF forms.
- CSF factory calls and bound story functions are classified as story declarations.
- Tags, tests, custom names, and explicit ids become index metadata when they are statically clear.
- ArgTypes describe story inputs and the controls and table metadata that docs can expose for them.
The normalized runtime model then separates project annotations, component annotations, story annotations, and module exports. The preview uses that model to prepare a story, while the index uses the smaller static form to make stories discoverable before they render. References: code/…/story.ts• L18-159, code/…/story.ts• L359-576, code/…/indexer.ts• L32-41, code/…/CsfFile.ts• L319-350
CSF parsing and transformation
The CSF tools read story source as an abstract syntax tree (AST), which is a structured representation of the source code. They use that tree to identify the default export, story exports, imports, annotations, and tests without running user code. This gives Storybook a safe view of story metadata during builds, indexing, migration, and docs generation.
The parser normalizes JavaScript and TypeScript source into one tree model. It keeps source locations and the text that belongs to each node so analysis can report useful errors and source-preserving edits can target the authored code. Small node predicates and CSF-specific classifiers provide the shared vocabulary used by the parser and the CSF file model. References: code/…/ast.ts• L12-39, code/…/ast.ts• L133-182, code/…/nodes.ts• L9-63
Parsing and transformation follow a source-preserving path:
- The source is parsed and indexed as a CSF file.
- The tool discovers editable meta and story objects when their shape is clear.
- Transformations update the source representation instead of rebuilding the whole file.
- The result is printed with source maps when a builder needs to map generated code back to the authored file.
The same tools also classify story declarations for consumers that need a usable story shape. A declaration resolves to a configuration object, a function, or an empty factory configuration. Ambiguous bindings, unsupported expressions, and unsafe edits produce diagnostics instead of silently changing user code. References: code/…/README.md• L3-12, code/…/CsfFile.ts• L390-446, code/…/CsfFile.ts• L892-1037, code/…/nodes.ts• L102-143, code/…/normalize-story.ts• L5-38, code/…/normalize-story.ts• L132-157
The CSF file model also supports safe edits to story objects and imports. A group of edits can be treated as one transaction, so a refused edit leaves the authored file unchanged while diagnostics explain the unsupported target. The parser then re-indexes the current source after a committed edit. References: code/…/CsfFile.ts• L352-412, code/…/CsfFile.ts• L484-521, code/…/CsfFile.ts• L574-620
The docs CSF transform adds information that is useful after the story is loaded. It preserves the authored story source and leading JSDoc descriptions as docs parameters. Builders apply this transform to story files and pass through files that cannot be parsed, so a docs build does not fail only because enrichment was unavailable.
flowchart LR
A[Authored CSF] --> B[Parse and classify]
B --> C[Static story and meta data]
B --> D[Safe source edits]
C --> E[Story index]
C --> F[Preview story model]
D --> G[Enriched CSF with source maps]
G --> H[Docs and code panels]
References: code/…/enrichCsf.ts• L19-57 code/…/enrichCsf.ts• L92-149 code/…/rollup-based-plugin.ts• L11-39
Story index
The story index is the server-side catalog that maps user story files to the entries shown by Storybook. It is built from configured story specifiers and indexers, then shared through the /index.json route and invalidated when watched story or preview files change.
Index generation connects several facts into one entry:
- The file path identifies the module to load.
- The meta title or an automatic title identifies the sidebar location.
- The export name supplies the default story name.
- The meta id or title and export name produce a stable story id.
- The component import path links a story to component metadata.
- Tags control visibility and docs behavior.
- Tests can appear as child entries of their story.
CSF files and MDX files use related but distinct index entries. A CSF file produces story entries and can also produce an automatic docs entry when autodocs is enabled. An MDX file produces a docs entry that can refer to the CSF files it imports or names with Meta of. Duplicate ids are resolved with explicit errors or documented precedence rules. References: code/…/StoryIndexGenerator.ts• L82-103, code/…/StoryIndexGenerator.ts• L399-525, code/…/indexer.ts• L67-98
The index generator caches file results and invalidates only the affected files and their docs dependents. Preview configuration changes invalidate the full index because project tags and other shared annotations can affect every entry. The server debounces invalidation before it emits the story-index event to the manager. References: code/…/StoryIndexGenerator.ts• L807-875, code/…/index-json.ts• L17-75, code/…/watch-story-specifiers.ts• L42-75
Story order is a presentation contract rather than part of a story id. The generator first uses the configured story sort rules and otherwise keeps the order derived from matched files. Within a story kind, the order authored in the file remains significant unless a sort rule changes it. References: code/…/sortStories.ts• L46-79, code/…/storySort.ts• L9-17, code/…/storySort.ts• L31-81
Component metadata extraction
Component metadata extraction turns framework source information into data that docs and controls can display. It is separate from story parsing: CSF identifies which component a story describes, while a renderer-specific docgen provider reads the component source and reports descriptions, props, types, JSDoc tags, and subcomponents.
The metadata path has two useful layers:
- The CSF index records the component import path when
meta.componentrefers to an imported binding. - Renderer providers convert framework-specific docgen results into shared descriptions and argTypes data.
ArgTypes are the normalized descriptions of component inputs used by Controls and docs tables. User-authored argTypes take part in the final merge, so generated metadata supplies defaults without removing explicit story or meta annotations. The shared contract supports control settings such as color, text, number, choice, and file inputs, plus table descriptions and conditional display rules. References: code/…/story.ts• L36-159, code/…/CsfFile.ts• L693-757, code/…/CsfFile.ts• L1326-1339, code/…/CsfFile.ts• L1355-1415, code/…/enhanceArgTypes.ts• L5-20, code/…/extractDocgenProps.ts• L70-108
When server docgen is enabled, core runs the provider chain in a long-lived worker. The worker keeps framework type programs warm and keeps CPU-heavy extraction off the development server event loop. Providers can return no data when they do not support a file, allowing another provider or the normal fallback path to handle it. References: code/…/types.ts• L75-129, code/…/docgen-worker.ts• L1-9, code/…/docgen-worker.ts• L44-89
MDX and docs analysis
MDX is the documentation format that combines Markdown with JSX components. Storybook analyzes MDX before rendering it so it can find its title, linked CSF file, name, id, tags, imports, summary, and heading anchors. This lets the story index and docs manifest treat a docs page as a first-class entry.
The analysis recognizes the Meta element as the page-level contract. Its of value links the page to an imported CSF module, while its other attributes set the page identity and metadata. Heading text becomes navigation anchors when the related feature is enabled. Template MDX is analyzed but is not added as a user-facing index entry. References: code/…/analyze-mdx.ts• L17-27, code/…/analyze-mdx.ts• L265-293, code/…/StoryIndexGenerator.ts• L527-635
The docs manifest uses the analysis result to expose standalone docs and docs attached to a component. It can store full MDX content in the manifest or store references to an MDX service when server-backed docs are enabled. A small summary utility supplies readable text when the page has no explicit summary. References: code/…/manifest.ts• L67-105, code/…/manifest.ts• L167-239, code/…/extract-docs-summary.ts• L7-17
Shared docs tooling
Shared docs tooling gives framework packages one common contract for source snippets, descriptions, imports, and controls metadata. It keeps framework-specific extraction at the edge while allowing docs blocks, the manager, and open services to consume consistent payloads.
The main shared outputs are:
- Story docs: per-story source snippets, descriptions, warnings, and errors.
- Component docgen: component descriptions, summaries, JSDoc tags, argTypes, and subcomponents.
- Import statements: minimal imports reconstructed from the component and story bindings.
- Source selection: authored source, generated source, or a dynamically rendered snippet according to docs parameters and story shape.
The story-docs service extracts each contributing CSF file when a component spreads its stories across files. It keeps file-local imports with file-local snippets and reports extraction errors at story level where possible. Provider middleware can add framework output or fall back to the next provider. References: code/…/types.ts• L22-67, code/…/server.ts• L28-75, code/…/provider.ts• L26-69
Static story analysis resolves args and parameters only when the source is clear. For example, an authored docs.source.code value can be a string, disabled with null, missing, or left unresolved with a warning. This distinction lets docs choose a safe fallback instead of presenting guessed source. References: code/…/authored-source.ts• L8-59, code/…/shared.ts• L10-27
The preview can request static story-docs data through the open service. When enabled, a preview hook sends the resulting snippet to the manager Code panel while still allowing preview-side source transforms. This creates a path from authored CSF analysis to the user-facing docs and code views without coupling those views to a renderer’s internal parser. References: code/…/preview.ts• L9-23, code/…/README.md• L3-15
Docs presentation utilities turn this data into interactive story examples and source views. A docs preview can show one or more stories, offer zoom and reload actions, and show, hide, or copy a source snippet; when no valid source exists, it reports that state instead of showing misleading code. Controls use the same argType contract to edit values such as colors, keep preset values, and honor read-only metadata. References: code/…/Preview.tsx• L150-297, code/…/Color.tsx• L246-303, code/…/Color.tsx• L366-467, code/…/ArgRow.stories.tsx• L499-623, code/…/Color.stories.tsx• L7-141
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to CSF metadata fields must keep
CsfFileoutput,IndexInput, andStoryIndexEntryaligned. - Changes to story ids or export-name rules must also preserve links between index entries, preview loading, docs references, and test child entries.
- Changes to component import resolution must be checked against both the index
componentPathand snippet import generation. - Changes to AST node shape or shared predicates must preserve both parser traversal and the lint tooling bundle that imports node predicates without the parser runtime.
- Changes to MDX
Metaanalysis must preserve docs dependencies and invalidation forMeta ofpages. - Changes to docgen payload fields must preserve the worker provider contract and the merge used by Controls and docs blocks.
- Changes to story-docs payload imports must keep file-local snippets valid when stories share one component id across files.
- Changes to shared argType or control fields must preserve the contract between CSF annotations, generated metadata, ArgsTable rows, and control widgets.
- Changes to docs preview source states must preserve the distinction between valid source, source warnings, and no available source.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A story file has no valid default meta export | The file cannot produce a usable CSF index | CSF parsing reports a focused error with the source location |
| A story id collides with another entry | One or more stories or docs pages cannot be selected reliably | Index generation raises a duplicate-id indexing error |
An MDX Meta of reference does not resolve to an indexed CSF file | The docs page cannot inherit the component title or stories | MDX extraction checks the dependency and reports the missing CSF path |
| A component docgen worker fails or times out | Component descriptions and controls metadata are unavailable | The worker reports the failure and providers can fall back without blocking normal story indexing |
| Static source contains unresolved expressions | A docs source snippet may be incomplete or absent | Story-shape analysis returns a warning or selects another source mode |
| A docs preview receives a source error | The code panel cannot show a trustworthy snippet | The preview shows a disabled “No code available” state |
| A color control receives an empty or invalid value | The picker cannot represent the authored value directly | The control uses a safe fallback and keeps the text input available for correction |
| A CSF edit removes a binding needed by an export | The edited file becomes invalid and the migration cannot be kept | The edit is refused or rolled back with an invalid-csf diagnostic |
| Source parsing cannot use the fast tree transfer path | Parsing falls back to a compatible tree transfer path instead of failing the story analysis | The parser disables the failing path and reports syntax errors with source locations |
Key files
| File | Why to read it |
|---|---|
| code/…/CsfFile.ts | Main CSF parser, metadata model, story discovery, safe edits, and index input creation |
| code/…/ast.ts | Shared source parser, AST traversal, source locations, and source text rules |
| code/…/nodes.ts | Parser-independent node checks and CSF factory classification used by shared tooling |
| code/…/CsfFile.test.ts | Behavioral contract for CSF parsing, factory stories, index inputs, edits, and component imports |
| code/…/normalize-story.ts | Shared classification of authored story declarations |
| code/…/enrichCsf.ts | Source and description enrichment used by docs builds |
| code/…/StoryIndexGenerator.ts | End-to-end story and docs index assembly, caching, and invalidation |
| code/…/analyze-mdx.ts | MDX metadata, imports, and heading analysis |
| code/…/indexer.ts | Contracts for index inputs and final index entries |
| code/…/types.ts | Shared component metadata and provider contract |
| code/…/server.ts | Story snippet extraction across the story index |
| code/…/enhanceArgTypes.ts | Merge point for generated and user-authored argTypes |
| code/…/manifest.ts | Docs manifest construction for attached and standalone MDX |
| code/…/story.ts | Shared story annotations and argType contract used by preview and docs |
| code/…/Preview.tsx | Docs story preview and source actions |
| code/…/Color.tsx | Color control behavior for normalized argType metadata |