diff --git a/.changeset/ast-proptypes-imports.md b/.changeset/ast-proptypes-imports.md new file mode 100644 index 00000000000..db86a15371a --- /dev/null +++ b/.changeset/ast-proptypes-imports.md @@ -0,0 +1,7 @@ +--- +'@react-docgen/core': patch +--- + +Recognize PropTypes imports from the parsed AST instead of scanning source text +with a potentially slow regular expression. Comments and string literals no +longer count as module imports. diff --git a/.changeset/calm-types-travel.md b/.changeset/calm-types-travel.md index 44b74e46d7b..f27e1f81d8f 100644 --- a/.changeset/calm-types-travel.md +++ b/.changeset/calm-types-travel.md @@ -3,3 +3,6 @@ --- Preserve function types wrapped in parentheses when parsing TypeScript unions. + +Thanks [@sean0407](https://github.com/sean0407) for +[#1142](https://github.com/reactjs/react-docgen/pull/1142). diff --git a/.changeset/giant-worlds-swim.md b/.changeset/giant-worlds-swim.md index 7c25cfff22b..3978a273ba7 100644 --- a/.changeset/giant-worlds-swim.md +++ b/.changeset/giant-worlds-swim.md @@ -3,6 +3,10 @@ 'react-docgen': major --- -Drop support for Node.js 20, 21 and 23 +Drop support for Node.js 20, 21, 23, 25 and pre-LTS Node.js 26 releases. -Minimum Supported Node.js version is now 22.13.0 +Supported Node.js versions are now: + +- Node.js 22.13.0 or newer 22.x releases +- Node.js 24.11.0 or newer 24.x releases +- Node.js 26.13.0 (the first Node.js 26 LTS release) or newer stable releases diff --git a/.changeset/mixin-class-props.md b/.changeset/mixin-class-props.md new file mode 100644 index 00000000000..b87defee716 --- /dev/null +++ b/.changeset/mixin-class-props.md @@ -0,0 +1,14 @@ +--- +'react-docgen': patch +'@react-docgen/typescript': patch +--- + +Extract TypeScript props from React class components extending mixin calls, +including aliased component bases and wrapped props. Preserve declared props +when a mixin receives unrelated generic arguments. + +Ported from [#1145](https://github.com/reactjs/react-docgen/pull/1145) by +[@mfazekas](https://github.com/mfazekas), merged with follow-up fixes in +[#1157](https://github.com/reactjs/react-docgen/pull/1157). Shared regression +fixtures cover the legacy parser, TypeScript adapter, and TypeScript handlers +composed with the normalized Babel adapter. diff --git a/.changeset/neutral-imperative-callbacks.md b/.changeset/neutral-imperative-callbacks.md new file mode 100644 index 00000000000..b2dcbe8bac2 --- /dev/null +++ b/.changeset/neutral-imperative-callbacks.md @@ -0,0 +1,10 @@ +--- +'@react-docgen/core': patch +--- + +Document methods wrapped in React `useCallback` and exposed through +`useImperativeHandle`, preserving their parameters, return types, descriptions, +and async/generator modifiers across parser adapters. + +Ported from [#1139](https://github.com/reactjs/react-docgen/pull/1139) by +[@askalf](https://github.com/askalf). diff --git a/.changeset/pre.json b/.changeset/pre.json new file mode 100644 index 00000000000..9a89b8a38fa --- /dev/null +++ b/.changeset/pre.json @@ -0,0 +1,4 @@ +{ + "mode": "pre", + "tag": "alpha" +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..2a6d1be741a --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Portable fixtures have one canonical source representation on every platform. +packages/integration-tests/cases/** text eol=lf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 620981446b8..f882b0b28a6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,19 +10,20 @@ on: permissions: {} env: - NODE_VERSION: 24 + NODE_VERSION: 24.11.0 jobs: tests: strategy: + fail-fast: false matrix: - node: ["22.13.0", "24", "25", "26"] + node: ["22.13.0", "24.11.0", "26.13.0", "^27.0.0-0"] os: ["ubuntu"] include: - os: macos - node: "24" + node: "24.11.0" - os: windows - node: "24" + node: "24.11.0" name: Tests (Node.js v${{ matrix.node }}, ${{ matrix.os }}) runs-on: ${{ matrix.os }}-latest @@ -38,16 +39,17 @@ jobs: uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: ${{ matrix.node }} + check-latest: ${{ startsWith(matrix.node, '^') }} cache: "pnpm" - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Unit tests with coverage + - name: Tests with coverage if: "${{ matrix.node == env.NODE_VERSION }}" - run: pnpm test -- --coverage + run: pnpm test:coverage - - name: Unit tests + - name: Tests if: "${{ matrix.node != env.NODE_VERSION }}" run: pnpm test @@ -57,6 +59,7 @@ jobs: uses: coverallsapp/github-action@8d6379e14d29928660c4ba802d8e85393440b329 # v2 with: parallel: true + file: coverage/lcov.info flag-name: test-${{ matrix.os }} finish: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7b34655b005..6c3a72fc471 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,6 +14,14 @@ We actively welcome your pull requests. 4. Ensure the test suite passes. 5. Make sure your code lints and typechecks. +## Tests and coverage + +Run `pnpm test` for the package suites. Run `pnpm test:coverage` for the CI +coverage report at `coverage/lcov.info`. Coverage runs all package projects in +one Vitest process and resolves parser packages to their sources, so shared core +code exercised by adapter tests is included. The legacy coverage thresholds +remain enforced. + ## Issues We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 00000000000..9b45d12ca9f --- /dev/null +++ b/PLAN.md @@ -0,0 +1,431 @@ +# Parser-Neutral react-docgen Roadmap + +## Status + +- Current milestone: 6 — Stable release and migration +- Overall status: Default extraction parity complete; public API and release + hardening remain +- Last updated: 2026-10-31 + +## Release-readiness summary + +- Default JavaScript and PropTypes behavior is covered across the TypeScript, + Hermes, and Babel adapters. +- TypeScript behavior is covered except for one fixture that uses Babel-only + `export defaultFrom from` syntax and must be reclassified. +- Flow behavior is covered through Hermes. +- Defaults, descriptions, methods, imports, exports, and parser-neutral error + output are represented by portable fixtures. +- Neutral handler, resolver, importer, and parser contracts exist, but not every + legacy public extension point has a stable replacement yet. +- Parser routing is implemented per file, but the mixed TypeScript/Hermes exit + criterion still needs a real cross-parser integration fixture. +- The parser-neutral `react-docgen` facade, native CLI parser configuration, + migration documentation, and package release validation are not complete. + +## Decisions + +1. `@react-docgen/core` will not depend on Babel, Hermes, or TypeScript. +2. The core will own the smallest path, traversal, and scope implementation + needed by react-docgen. +3. Parser adapters will normalize their ASTs into an ESTree-inspired internal + representation. +4. TypeScript will be the first production adapter. Hermes and Flow will follow. +5. Parser selection will happen per file, including imported files. +6. The next `react-docgen` major will be a parser-neutral facade with no default + parser. +7. Babel-shaped extension APIs may break in that major. `react-docgen@8` remains + the legacy line during migration. +8. Documentation output, not raw AST equality, is the compatibility contract. + +## Target packages + +- `@react-docgen/core`: normalized AST, paths, traversal, scopes, extraction, + and parser routing. +- `@react-docgen/typescript`: `typescript-estree` adapter and preconfigured + `parse()`. +- `@react-docgen/hermes`: Hermes adapter and preconfigured `parse()`. +- `@react-docgen/babel`: optional compatibility adapter and differential-test + reference. +- `react-docgen@8`: maintained legacy Babel implementation. +- Next `react-docgen` major: facade over `@react-docgen/core` composition APIs. + +## Milestone 0 — Stabilize and specify + +- [x] Keep the existing package build and test suite green while experimental + work proceeds separately. +- [x] Record architecture and package decisions in this plan. +- [x] Classify fixtures as `common`, `typescript`, `flow`, or `babel-specific`. +- [x] Reuse the existing integration snapshot harness as parser-independent + golden output. +- [x] Use the current Babel integration snapshots as the migration reference. + +Exit criteria: existing build and tests pass; fixtures have explicit +capabilities and stable expected documentation output. + +## Milestone 1 — Core foundation + +- [x] Add `@react-docgen/core` without a parser dependency. +- [x] Define the parser-neutral base node; add concrete normalized nodes only + with their first TypeScript caller. +- [x] Implement `AstPath`, visitor keys, traversal controls, and minimal + value/type scope services. +- [x] Add the parser-neutral `Parser`, `FileState`, `ProjectContext`, and + `Importer` contracts needed for import routing. +- [x] Route imported files back through `ProjectContext` so each file can select + its parser. + +Exit criteria: focused synthetic tests cover paths, traversal, scopes, bindings, +and import routing. + +## Milestone 2 — TypeScript vertical slice + +- [x] Add `@react-docgen/typescript` using + `@typescript-eslint/typescript-estree`. +- [x] Normalize JS, JSX, TS, TSX, imports, exports, and required TypeScript type + nodes. +- [x] Add parser-neutral `Handler` and `Resolver` contracts with their first + callers. +- [x] Support one complete exported function-component flow: props, + descriptions, defaults, and documentation output. +- [x] Export both a composable `parser` and a preconfigured `parse()`. + +Exit criteria: selected common and TypeScript fixtures match legacy output; +production dependencies contain no Babel package. Scoped `0.x` packages are +ready for an explicitly requested release. + +## Milestone 3 — JavaScript and TypeScript parity + +- [x] Port resolvers, imports, value resolution, PropTypes, defaults, classes, + methods, docblocks, and TypeScript type extraction. +- [x] Add normalized Babel adapter for differential testing. +- [x] Define public neutral extension APIs and compile-test custom handlers, + resolvers, and importers. + +Exit criteria: all applicable `common` and `typescript` fixtures match legacy +output; no Babel types leak from new APIs. + +## Sidestep — Portable integration fixture corpus + +- [x] Move legacy fixtures into a private parser-free workspace package. +- [x] Organize cases by language, behavior, and descriptive case ID. +- [x] Replace the monolithic snapshot with one JSON outcome per case. +- [x] Run all cases through legacy `react-docgen` and a temporary supported-case + allowlist through `@react-docgen/typescript`. +- [x] Map disabled unit-test behaviors to portable fixtures or narrow, evidenced + exclusions. +- [x] Add coverage-driven fixtures without production changes or coverage hints. +- [x] Record the integration-only plateau and enforce its integer-floor coverage + thresholds. + +Exit criteria: migrated output remains unchanged; all public behavior +represented by disabled unit tests is covered or classified; legacy integration +coverage cannot silently regress. + +## Milestone 4 — Hermes and Flow + +- [x] Add `@react-docgen/hermes` and normalize Hermes ESTree and Flow nodes. +- [x] Port Flow extraction and component patterns. +- [x] Run common fixtures through TypeScript, Hermes, and Babel adapters. +- [x] Report unsupported syntax as explicit parser capability errors. + +Exit criteria: common JS/JSX output agrees across adapters and Flow output +matches the legacy implementation. + +## Milestone 3.1 — Shared React extraction + +- [x] Move parser-neutral resolvers, handlers, and value/documentation helpers + from `@react-docgen/typescript` into `@react-docgen/core`. +- [x] Split shared component metadata extraction from TypeScript prop/type + extraction. +- [x] Keep TypeScript-only type helpers and handler composition in + `@react-docgen/typescript`. +- [x] Expose preconfigured `parse()` from `@react-docgen/babel` using only Babel + plus shared core extraction. +- [x] Keep focused utility tests and JavaScript differential fixtures green. + +Exit criteria: Babel and TypeScript adapters share React extraction without +depending on each other; only TypeScript semantics remain in the TypeScript +package; all applicable JavaScript output remains identical. + +## Milestone 5 — Mixed-parser projects + +- [x] Add ordered `createParserRouter()` rules using filename, glob, or a custom + selector. +- [x] Require filenames when multiple parsers are configured. +- [x] Route every imported file independently. +- [x] Support parser-specific options per route and explicit no-match errors. +- [x] Add CLI config for single-parser and mixed-parser projects. + +Exit criteria: TypeScript and Hermes files can import each other while +preserving exports, bindings, descriptions, and props. + +## Milestone 6 — Stable release and migration + +- [ ] Decide the final package boundary before freezing APIs: keep shared React + extraction in core or move it to `@react-docgen/react`, and decide whether + method JSDoc parsing becomes an optional composition package. +- [ ] Reconcile the intended convenience API with the current composition API: + either make `createDocgen({ parser })` supply standard React behavior or + document the required handlers and resolver explicitly. +- [ ] Add a real mixed-parser integration fixture in which TypeScript and Hermes + files import each other while preserving exports, bindings, descriptions, + defaults, and props. +- [ ] Reclassify `typescript/imports/reexported-default-values`, whose + `export defaultFrom from` syntax is Babel-specific, or assert an explicit + parser capability error. +- [ ] Stabilize scoped packages after parity and extension API validation, + including exported types and parser-specific options. +- [ ] Release the next `react-docgen` major as a parser-neutral facade with no + implicit `parse()` backend. +- [ ] Remove Babel-specific extension contracts from the new major. +- [ ] Inventory every legacy public handler, resolver, importer, utility, error, + `FileState`, and Babel `NodePath` export; implement or document its + neutral replacement. +- [ ] Update the CLI to configure scoped single-parser and mixed-parser projects + directly instead of relying only on a custom `parse` function escape + hatch. +- [ ] Publish package READMEs, a migration guide, release notes, and CLI + configuration documentation. +- [ ] Validate packed tarballs, clean consumer installs, declaration output, + package exports, changesets, and the supported Node matrix before + versioning. +- [ ] Keep `react-docgen@8` available for legacy Babel behavior. + +Exit criteria: users must explicitly install/select a parser, and every legacy +public extension point has a documented replacement. + +## Public API direction + +```ts +import { createDocgen, createParserRouter } from '@react-docgen/core'; +import { parser as typescript } from '@react-docgen/typescript'; +import { parser as hermes } from '@react-docgen/hermes'; + +const parser = createParserRouter([ + { test: /\.(?:ts|tsx|mts|cts)$/, parser: typescript }, + { test: /\.(?:js|jsx|mjs|cjs)$/, parser: hermes }, +]); + +// Final milestone 6 decision: either this convenience form supplies the +// standard React resolver/handlers, or callers compose them explicitly. +const docgen = createDocgen({ parser }); +``` + +Convenience packages will also expose preconfigured APIs: + +```ts +import { parse } from '@react-docgen/typescript'; +``` + +## Test policy + +- Core tests use synthetic normalized ASTs and load no parser. +- Every adapter runs shared conformance tests for comments, visitor keys, paths, + scopes, imports, locations, and errors. +- Golden documentation fixtures define compatibility. +- Differential tests compare applicable fixtures across legacy Babel, normalized + Babel, TypeScript, and Hermes. +- Raw AST equality is never required. + +## Plan change log + +Record every material plan change here before or with implementation. + +### 2026-10-31 — Made CI fixtures portable and unified coverage reporting + +- Pin shared fixture line endings to LF and compare CLI paths in their existing + slash-normalized form on Windows. +- Collect one source-based coverage report across all package projects, so + adapter integration tests contribute to shared core coverage. +- Keep the existing legacy coverage thresholds and let every CI platform finish + even when another matrix job fails. + +### 2026-10-31 — Ported mixin class props from the maintained legacy line + +- Carried #1145/#1157 into the legacy reference and TypeScript adapter, + preserving React base validation, wrapped props, aliased imports, and + declared-props fallback. +- Added portable golden cases and composed the TypeScript handler with the Babel + adapter to check the same output across parser representations. +- Credited the original contribution by @mfazekas in the changeset. + +### 2026-09-21 — Audited release readiness after mixed-parser implementation + +- Confirmed default JavaScript, TypeScript, and Flow extraction parity across + the portable corpus, apart from one Babel-only export-syntax fixture currently + classified as TypeScript. +- Distinguished implemented parser routing from the still-missing real + TypeScript/Hermes cross-import integration proof. +- Expanded Milestone 6 to cover package boundaries, facade/API stabilization, + legacy extension migration, native CLI configuration, documentation, and + packed-package validation. +- Reason: the extraction engine is largely complete, but the stable public + product surface requires more than publishing the scoped packages. + +### 2026-09-21 — Completed mixed-parser projects milestone + +- Added ordered parser routing for exact filenames, globs, regular expressions, + and custom selectors, including per-route parser options and explicit no-match + errors. +- Required entry filenames when a router has multiple routes and kept imported + files on the same independent routing path. +- Added CLI config modules that can supply a preconfigured single-parser or + mixed-parser parse function. +- Reason: parser choice now follows each file through the whole project instead + of being fixed by the entry point. + +### 2026-09-21 — Completed Hermes and Flow milestone + +- Added `@react-docgen/hermes` as a thin Hermes parser adapter over shared core + extraction, with normalization for Hermes ESTree and Flow nodes. +- Ported Flow props and type extraction, including aliases, interfaces, + utilities, imports, generics, and recursive type protection. +- Added file-based Flow/JavaScript corpus coverage and Babel differential tests; + unsupported TypeScript-family files now produce an explicit parser capability + error. +- Reason: Hermes now matches legacy Flow output while common JavaScript output + remains consistent across parser adapters. + +### 2026-08-16 — Added shared React extraction milestone + +- Inserted Milestone 3.1 before Hermes work and temporarily made it current. +- Moved parser-neutral React behavior toward `@react-docgen/core`; parser + packages will compose that behavior with parser/language-specific handlers. +- Reason: Milestone 3 proved Babel could reuse normalized ASTs, but its + differential runner depended on TypeScript-owned handlers. That dependency + direction would duplicate behavior for Babel and Hermes. + +### 2026-08-16 — Completed shared React extraction milestone + +- Moved shared React handlers, exported-definition resolution, and + value/documentation helpers into `@react-docgen/core` while preserving their + one-purpose-file layout. +- Split TypeScript prop extraction into `typescriptPropsHandler`; kept only + composed-type, props-member, TypeScript-type, and TypeScript-name helpers in + `@react-docgen/typescript`. +- Made method extraction accept an optional type resolver, allowing core and + Babel to handle JavaScript/JSDoc while TypeScript supplies `getTSType`. +- Added Babel's preconfigured `parse()` and changed differential tests to use + public Babel and TypeScript APIs, removing their implementation dependency. +- Reason: parser adapters now select syntax while core owns shared observable + React behavior; new adapters need only contribute language-specific logic. + +### 2026-08-16 — Initial roadmap + +- Added parser-neutral package architecture and six delivery milestones. +- Chose TypeScript as first adapter to validate the smallest useful vertical + slice before adding Hermes. +- Chose an owned minimal path/traversal/scope layer because react-docgen needs + only a subset of general AST tooling and has custom type-binding behavior. +- Chose a breaking parser-neutral `react-docgen` major so new APIs do not + preserve Babel types indefinitely. +- Deferred detailed normalized node schemas, router fallback rules, and parser + capability matrices until a real milestone needs them; defining them now would + be speculative. + +### 2026-08-16 — Reused existing golden harness + +- Replaced planned new golden-output infrastructure with the existing + integration snapshot suite. +- Added explicit fixture capability metadata and a guard that fails when a new + fixture is not classified. +- Reason: existing snapshots already capture the compatibility contract; a + second harness would duplicate behavior and maintenance. + +### 2026-08-16 — Deferred caller-shaped contracts + +- Moved concrete normalized node fields and `Handler`/`Resolver` contracts from + the core-foundation milestone to their first TypeScript vertical-slice + callers. +- Kept only the generic node, path, traversal, scope, parser, file, project, and + importer mechanics in Milestone 1. +- Reason: defining adapter and extraction shapes before a real caller would + create speculative API surface. + +### 2026-08-16 — Separated implementation from publication + +- Changed the Milestone 2 exit criterion from publishing experimental packages + to making them publish-ready. +- Added public package metadata while leaving the actual npm release as a + separate explicit action. +- Reason: publishing is an external, irreversible release decision and is not + implied by implementing the milestone. + +### 2026-08-16 — Hardened portable integration corpus before Milestone 3 + +- Paused Milestone 3 to move 49 legacy fixtures and golden outputs into + `@react-docgen-internal/integration-tests`, grouped by language and behavior. +- Replaced parser capability metadata with language directories and added a + validating dependency-free loader. +- Added coverage-driven public behavior cases and a TypeScript adapter + allowlist; the legacy package remains the complete reference runner. +- Started disabled unit-test dispositions in the corpus audit and expanded + integration-only coverage from 71.33% to 79.28% statements. +- Reason: parser implementations need one portable observable-output contract; + unit tests tied to Babel paths cannot provide that contract. + +### 2026-08-16 — Reopened coverage expansion + +- Removed the initial 79/68/89/79 thresholds and withdrew the claimed behavioral + plateau. +- Kept 92% coverage from the complete unit-and-integration suite as the + practical reachability benchmark for the integration corpus. +- Reason: the earlier audit classified broad utility groups too aggressively; + the existing unit suite proves substantially more production code is + reachable. + +### 2026-08-16 — Established default-parse coverage plateau + +- Expanded the corpus to 79 cases and reached 84.05% statements, 74.06% + branches, 94.62% functions, and 84.61% lines without production changes. +- Set integer-floor thresholds at 84/74/94/84 after the final batch gained only + 0.20 statement points and remaining regions were classified by reachability. +- Explained the difference from the former 92% combined suite: unit tests cover + custom resolvers, directly exported helpers, and synthetic invalid AST states + excluded from the default parser corpus. + +### 2026-08-16 — Converted internal tooling packages + +- Converted `@react-docgen-internal/integration-tests` from handwritten MJS plus + declarations to a compiled TypeScript package. +- Moved `@react-docgen-internal/benchmark` from the workspace root to + `packages/benchmark` and updated workspace, Renovate, lint, lockfile, and + runtime paths. +- Reason: internal packages now follow the same workspace layout and TypeScript + build conventions as the parser packages. + +### 2026-08-16 — Recorded separate coverage contracts + +- Recorded 84.05/74.06/94.62/84.61 as the portable default-parse integration + baseline and 95.03/88.78/98.41/95.45 as the complete unit-and-integration + baseline. +- Kept integration thresholds tied to the portable corpus rather than raising + them to complete-suite values. +- Reason: unit tests additionally cover Babel-specific internals, public helper + APIs, custom resolvers, and synthetic AST states that parser adapters should + not need to reproduce through integration fixtures. + +### 2026-08-16 — Completed JavaScript and TypeScript parity milestone + +- Expanded `@react-docgen/typescript` from the vertical slice to the complete + applicable JavaScript and TypeScript corpus: exports, stable resolver errors, + local/imported values and types, PropTypes, contexts, defaults, classes, + methods, docblocks, HOCs, imperative handles, and TypeScript type shapes. +- Kept extraction utilities in one-purpose files and added focused tests for new + resolution, type, docblock, class, enum, expression, and method helpers. +- Added parser-neutral `createDocgen()` composition to `@react-docgen/core` and + compile/runtime-tested custom `Parser`, `Resolver`, `Handler`, and `Importer` + contracts without Babel types. +- Added `@react-docgen/babel`, which normalizes Babel 7/8 AST node names into + the shared representation and declares both Babel majors as peer ranges. + Differential tests now require all 40 portable JavaScript golden outputs to + agree between normalized Babel and TypeScript ESTree. +- Excluded only `typescript/imports/reexported-default-values` from the + TypeScript adapter. Its support file uses Babel's nonstandard + `export defaultFrom` proposal, which TypeScript ESTree rejects before an + importer can expose its values; the same observable import/value behavior is + covered by standard-syntax import fixtures. +- Reason: Milestone 3's contract is observable output parity for syntax a + selected parser supports, plus explicit parser boundaries—not emulation of + another parser's proposal syntax. diff --git a/eslint.config.mjs b/eslint.config.mjs index 620f7d4815a..bae9e519167 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,8 +6,9 @@ import tseslint from 'typescript-eslint'; export default tseslint.config([ globalIgnores([ - 'benchmark/suites/', + 'packages/benchmark/suites/', '**/__fixtures__/', + 'packages/integration-tests/cases/', '**/dist/', '**/.nx/', '**/coverage', diff --git a/package.json b/package.json index 4cd56b8b043..ab9e13f38ae 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "engines": { - "node": "^22.13.0 || >=24", + "node": "^22.13.0 || ^24.11.0 || >=26.13.0", "pnpm": ">=10.6.2" }, "type": "module", @@ -13,7 +13,8 @@ "copy:changelog:react-docgen": "cp ./packages/react-docgen/CHANGELOG.md ./packages/website/src/app/docs/release-notes/react-docgen/page.mdx", "copy:changelog:cli": "cp ./packages/react-docgen-cli/CHANGELOG.md ./packages/website/src/app/docs/release-notes/cli/page.mdx", "changesets-release": "pnpm build && changeset publish", - "changesets-version": "changeset version && pnpm install --lockfile-only && pnpm copy:changelog:react-docgen && pnpm copy:changelog:cli" + "changesets-version": "changeset version && pnpm install --lockfile-only && pnpm copy:changelog:react-docgen && pnpm copy:changelog:cli", + "test:coverage": "pnpm build && vitest run --coverage" }, "license": "MIT", "devDependencies": { diff --git a/packages/babel/package.json b/packages/babel/package.json new file mode 100644 index 00000000000..5ed8b2abd81 --- /dev/null +++ b/packages/babel/package.json @@ -0,0 +1,38 @@ +{ + "name": "@react-docgen/babel", + "version": "0.0.0", + "description": "Normalized Babel parser adapter for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/babel" + }, + "type": "module", + "files": ["dist"], + "engines": { + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "dependencies": { + "@react-docgen/core": "workspace:*" + }, + "peerDependencies": { + "@babel/core": "^7.28.0 || ^8.0.0", + "@babel/types": "^7.28.2 || ^8.0.0" + }, + "devDependencies": { + "@babel/core": "7.29.7", + "@babel/types": "7.29.8", + "@types/babel__core": "7.20.5" + }, + "license": "MIT" +} diff --git a/packages/babel/src/__tests__/parser-test.ts b/packages/babel/src/__tests__/parser-test.ts new file mode 100644 index 00000000000..59773ce28e7 --- /dev/null +++ b/packages/babel/src/__tests__/parser-test.ts @@ -0,0 +1,56 @@ +import { expect, test } from 'vitest'; +import parser, { parse } from '../index.js'; + +test('normalizes Babel-specific node names', () => { + const ast = parser.parse({ + code: 'class Button { static propTypes = { label: "text" }; }', + filename: 'button.jsx', + }); + + expect(ast).toMatchObject({ + type: 'Program', + body: [ + { + type: 'ClassDeclaration', + body: { + body: [ + { + type: 'PropertyDefinition', + value: { + type: 'ObjectExpression', + properties: [{ type: 'Property', value: { type: 'Literal' } }], + }, + }, + ], + }, + }, + ], + }); +}); + +test('extracts React documentation with shared handlers', () => { + expect( + parse(` + import PropTypes from 'prop-types'; + + /** Button description. */ + export function Button() {} + Button.propTypes = { label: PropTypes.string.isRequired }; + Button.defaultProps = { label: 'Save' }; + `), + ).toEqual([ + { + description: 'Button description.', + displayName: 'Button', + methods: [], + props: { + label: { + defaultValue: { computed: false, value: "'Save'" }, + description: '', + required: false, + type: { name: 'string' }, + }, + }, + }, + ]); +}); diff --git a/packages/babel/src/index.ts b/packages/babel/src/index.ts new file mode 100644 index 00000000000..e18ef90e54b --- /dev/null +++ b/packages/babel/src/index.ts @@ -0,0 +1,55 @@ +import { parseSync, type TransformOptions } from '@babel/core'; +import { VISITOR_KEYS } from '@babel/types'; +import { + createDocgen, + reactHandlers, + resolveComponentDefinitions, + type ComponentDocumentation, + type DocgenParseOptions, + type Parser, + type VisitorKeys, +} from '@react-docgen/core'; +import normalize from './normalize.js'; + +export const visitorKeys: VisitorKeys = { + ...VISITOR_KEYS, + Literal: [], + MethodDefinition: ['key', 'value', 'decorators'], + Property: ['key', 'value', 'decorators'], + PropertyDefinition: ['key', 'value', 'decorators'], +}; + +const parser: Parser = { + parse(source, options) { + const ast = parseSync(source.code, { + ast: true, + code: false, + filename: source.filename, + parserOpts: { + plugins: ['jsx', 'typescript', 'estree'], + }, + ...(options as TransformOptions | undefined), + }); + + if (!ast) throw new TypeError('Babel did not return an AST.'); + + return normalize(ast); + }, + visitorKeys, +}; + +export default parser; +export { parser }; + +const docgen = createDocgen({ + handlers: reactHandlers, + parser, + resolver: resolveComponentDefinitions, +}); + +export function parse( + code: string, + options?: DocgenParseOptions, +): ComponentDocumentation[] { + return docgen(code, options); +} diff --git a/packages/babel/src/normalize.ts b/packages/babel/src/normalize.ts new file mode 100644 index 00000000000..713c966b16a --- /dev/null +++ b/packages/babel/src/normalize.ts @@ -0,0 +1,52 @@ +import { isAstNode, type AstNode } from '@react-docgen/core'; + +const typeNames: Record = { + ClassPrivateProperty: 'PropertyDefinition', + ClassProperty: 'PropertyDefinition', + CommentBlock: 'Block', + CommentLine: 'Line', +}; + +function normalizeValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(normalizeValue); + if (!value || typeof value !== 'object') return value; + + const input = value as Record; + + if (input.type === 'File') { + const program = normalizeValue(input.program); + + if (program && typeof program === 'object') { + (program as Record).comments = normalizeValue( + input.comments, + ); + } + + return program; + } + + const output: Record = {}; + + for (const [key, child] of Object.entries(input)) { + output[key] = normalizeValue(child); + } + + const originalType = typeof input.type === 'string' ? input.type : ''; + + output.type = typeNames[originalType] ?? originalType; + if (typeof input.start === 'number' && typeof input.end === 'number') { + output.range = [input.start, input.end]; + } + + return output; +} + +export default function normalize(node: unknown): AstNode { + const normalized = normalizeValue(node); + + if (!isAstNode(normalized)) { + throw new TypeError('Babel did not return an AST node.'); + } + + return normalized; +} diff --git a/packages/babel/tsconfig.json b/packages/babel/tsconfig.json new file mode 100644 index 00000000000..a1f3d920bb4 --- /dev/null +++ b/packages/babel/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "exclude": ["**/__tests__/**/*"], + "include": ["src/**/*"] +} diff --git a/packages/babel/vitest.config.ts b/packages/babel/vitest.config.ts new file mode 100644 index 00000000000..427827c013a --- /dev/null +++ b/packages/babel/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'babel-adapter', + include: ['**/__tests__/**/*-test.ts'], + }, +}); diff --git a/benchmark/index.mjs b/packages/benchmark/index.mjs similarity index 97% rename from benchmark/index.mjs rename to packages/benchmark/index.mjs index 68408bf2844..914e31eb0b4 100644 --- a/benchmark/index.mjs +++ b/packages/benchmark/index.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from 'url'; import Table from 'cli-table'; import glob from 'fast-glob'; import Benchmark from 'benchmark'; -import { parse } from '../packages/react-docgen/dist/main.js'; +import { parse } from '../react-docgen/dist/main.js'; import { parse as parse5 } from 'react-docgen5'; import { parse as parse6 } from 'react-docgen6'; diff --git a/benchmark/package.json b/packages/benchmark/package.json similarity index 100% rename from benchmark/package.json rename to packages/benchmark/package.json diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 00000000000..32cd968974a --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,32 @@ +{ + "name": "@react-docgen/core", + "version": "0.0.0", + "description": "Parser-neutral foundations for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/core" + }, + "type": "module", + "files": [ + "dist" + ], + "engines": { + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "license": "MIT", + "dependencies": { + "comment-parser": "^1.4.9", + "jsdoc-type-pratt-parser": "8.0.0" + } +} diff --git a/packages/core/src/AstNode.ts b/packages/core/src/AstNode.ts new file mode 100644 index 00000000000..1bb1d965d42 --- /dev/null +++ b/packages/core/src/AstNode.ts @@ -0,0 +1,14 @@ +export interface AstNode { + readonly type: string; + readonly [key: string]: unknown; +} + +export type VisitorKeys = Readonly>>; + +export function isAstNode(value: unknown): value is AstNode { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { type?: unknown }).type === 'string' + ); +} diff --git a/packages/core/src/AstPath.ts b/packages/core/src/AstPath.ts new file mode 100644 index 00000000000..7fced6272c5 --- /dev/null +++ b/packages/core/src/AstPath.ts @@ -0,0 +1,62 @@ +import { isAstNode, type AstNode } from './AstNode.js'; +import type Scope from './Scope.js'; + +interface AstPathOptions { + node: N; + parentPath?: AstPath; + key?: number | string; + listKey?: string; + scope?: Scope; +} + +export default class AstPath { + readonly node: N; + readonly parentPath: AstPath | null; + readonly key: number | string | null; + readonly listKey: string | null; + readonly scope: Scope | null; + + shouldSkip = false; + shouldStop = false; + + constructor({ node, parentPath, key, listKey, scope }: AstPathOptions) { + this.node = node; + this.parentPath = parentPath ?? null; + this.key = key ?? null; + this.listKey = listKey ?? null; + this.scope = scope ?? parentPath?.scope ?? null; + } + + get(name: string): AstPath | AstPath[] | null { + const value = this.node[name]; + + if (isAstNode(value)) { + return new AstPath({ node: value, parentPath: this, key: name }); + } + + if (Array.isArray(value)) { + return value.flatMap((node, index) => + isAstNode(node) + ? [ + new AstPath({ + node, + parentPath: this, + key: index, + listKey: name, + }), + ] + : [], + ); + } + + return null; + } + + skip(): void { + this.shouldSkip = true; + } + + stop(): void { + this.shouldStop = true; + } +} diff --git a/packages/core/src/ProjectContext.ts b/packages/core/src/ProjectContext.ts new file mode 100644 index 00000000000..7910d46bf23 --- /dev/null +++ b/packages/core/src/ProjectContext.ts @@ -0,0 +1,80 @@ +import type { AstNode } from './AstNode.js'; +import AstPath from './AstPath.js'; +import type { VisitorKeys } from './AstNode.js'; +import traverse, { type Visitor } from './traverse.js'; + +export interface SourceFile { + readonly code: string; + readonly filename: string; +} + +export interface Parser { + readonly visitorKeys: VisitorKeys; + parse(source: SourceFile, options?: unknown): AstNode; +} + +export interface ParserSelection { + readonly options?: unknown; + readonly parser: Parser; +} + +export type ParserSelector = (filename: string) => Parser | ParserSelection; +export type Importer = (specifier: string, fromFilename: string) => SourceFile; + +export class FileState { + readonly ast: AstNode; + readonly path: AstPath; + readonly source: SourceFile; + readonly visitorKeys: VisitorKeys; + + readonly #project: ProjectContext; + + constructor( + project: ProjectContext, + source: SourceFile, + ast: AstNode, + visitorKeys: VisitorKeys, + ) { + this.#project = project; + this.source = source; + this.ast = ast; + this.path = new AstPath({ node: ast }); + this.visitorKeys = visitorKeys; + } + + import(specifier: string): FileState { + return this.#project.import(specifier, this.source.filename); + } + + traverse(visitor: Visitor, state: State): void { + traverse(this.ast, this.visitorKeys, visitor, state); + } +} + +interface ProjectContextOptions { + importer: Importer; + selectParser: ParserSelector; +} + +export default class ProjectContext { + readonly #importer: Importer; + readonly #selectParser: ParserSelector; + + constructor({ importer, selectParser }: ProjectContextOptions) { + this.#importer = importer; + this.#selectParser = selectParser; + } + + parse(source: SourceFile): FileState { + const selection = this.#selectParser(source.filename); + const { options, parser } = + 'parser' in selection ? selection : { parser: selection }; + const ast = parser.parse(source, options); + + return new FileState(this, source, ast, parser.visitorKeys); + } + + import(specifier: string, fromFilename: string): FileState { + return this.parse(this.#importer(specifier, fromFilename)); + } +} diff --git a/packages/core/src/Scope.ts b/packages/core/src/Scope.ts new file mode 100644 index 00000000000..3d01f6d3f52 --- /dev/null +++ b/packages/core/src/Scope.ts @@ -0,0 +1,42 @@ +import type AstPath from './AstPath.js'; + +export type BindingKind = 'type' | 'value'; + +export interface Binding { + readonly kind: BindingKind; + readonly name: string; + readonly path: AstPath; +} + +export default class Scope { + readonly parent: Scope | null; + + readonly #bindings = { + type: new Map(), + value: new Map(), + }; + + constructor(parent?: Scope) { + this.parent = parent ?? null; + } + + declare(name: string, path: AstPath, kind: BindingKind = 'value'): Binding { + const binding = { kind, name, path }; + + this.#bindings[kind].set(name, binding); + + return binding; + } + + getOwnBinding(name: string, kind: BindingKind = 'value'): Binding | null { + return this.#bindings[kind].get(name) ?? null; + } + + getBinding(name: string, kind: BindingKind = 'value'): Binding | null { + return ( + this.getOwnBinding(name, kind) ?? + this.parent?.getBinding(name, kind) ?? + null + ); + } +} diff --git a/packages/core/src/__tests__/ProjectContext-test.ts b/packages/core/src/__tests__/ProjectContext-test.ts new file mode 100644 index 00000000000..14530d7123f --- /dev/null +++ b/packages/core/src/__tests__/ProjectContext-test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test, vi } from 'vitest'; +import { ProjectContext, type Parser } from '../index.js'; + +describe('ProjectContext', () => { + test('selects a parser for every imported file', () => { + const typescript: Parser = { + parse: ({ filename }) => ({ type: 'TypeScriptFile', filename }), + visitorKeys: {}, + }; + const hermes: Parser = { + parse: ({ filename }) => ({ type: 'HermesFile', filename }), + visitorKeys: {}, + }; + const selectParser = vi.fn((filename: string) => + filename.endsWith('.tsx') ? typescript : hermes, + ); + const importer = vi.fn(() => ({ + code: 'export default function Button() {}', + filename: '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/project/Button.js', + })); + const project = new ProjectContext({ importer, selectParser }); + + const entry = project.parse({ code: '', filename: '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/project/App.tsx' }); + const imported = entry.import('./Button.js'); + + expect(entry.ast.type).toBe('TypeScriptFile'); + expect(imported.ast.type).toBe('HermesFile'); + expect(selectParser).toHaveBeenCalledWith('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/project/App.tsx'); + expect(selectParser).toHaveBeenCalledWith('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/project/Button.js'); + expect(importer).toHaveBeenCalledWith('./Button.js', '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/project/App.tsx'); + }); +}); diff --git a/packages/core/src/__tests__/Scope-test.ts b/packages/core/src/__tests__/Scope-test.ts new file mode 100644 index 00000000000..7a3c286e1bf --- /dev/null +++ b/packages/core/src/__tests__/Scope-test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from 'vitest'; +import { AstPath, Scope } from '../index.js'; + +const path = new AstPath({ node: { type: 'Identifier', name: 'Props' } }); + +describe('Scope', () => { + test('keeps value and type bindings separate', () => { + const scope = new Scope(); + const value = scope.declare('Props', path); + const type = scope.declare('Props', path, 'type'); + + expect(scope.getBinding('Props')).toBe(value); + expect(scope.getBinding('Props', 'type')).toBe(type); + expect(scope.getBinding('missing')).toBeNull(); + }); + + test('resolves and shadows parent bindings', () => { + const parent = new Scope(); + const child = new Scope(parent); + const parentBinding = parent.declare('Component', path); + + expect(child.getBinding('Component')).toBe(parentBinding); + + const childBinding = child.declare('Component', path); + + expect(child.getOwnBinding('Component')).toBe(childBinding); + expect(child.getBinding('Component')).toBe(childBinding); + }); +}); diff --git a/packages/core/src/__tests__/createParserRouter-test.ts b/packages/core/src/__tests__/createParserRouter-test.ts new file mode 100644 index 00000000000..a875ea82ed1 --- /dev/null +++ b/packages/core/src/__tests__/createParserRouter-test.ts @@ -0,0 +1,109 @@ +import { describe, expect, test, vi } from 'vitest'; +import { + createDocgen, + createParserRouter, + type Handler, + type Parser, + type Resolver, +} from '../index.js'; + +const resolver: Resolver = (file) => [file.path]; +const handler: Handler = (documentation, _path, file) => { + documentation.description = file.ast.type; +}; + +function makeParser(type: string): Parser { + return { + parse: vi.fn((_source, options) => ({ type, options })), + visitorKeys: {}, + }; +} + +describe('createParserRouter', () => { + test('uses the first matching filename, glob, or custom rule', () => { + const exact = makeParser('Exact'); + const glob = makeParser('Glob'); + const custom = makeParser('Custom'); + const router = createParserRouter([ + { test: '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/project/special.tsx', parser: exact }, + { test: '**/*.tsx', parser: glob, options: { jsx: true } }, + { test: (filename) => filename.endsWith('.js'), parser: custom }, + ]); + + expect(router('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/project/special.tsx')).toEqual({ + options: undefined, + parser: exact, + }); + expect(router('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/project/Button.tsx')).toEqual({ + options: { jsx: true }, + parser: glob, + }); + expect(router('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/project/Button.js')).toEqual({ + options: undefined, + parser: custom, + }); + }); + + test('supports standard glob syntax', () => { + const parser = makeParser('Matched'); + const router = createParserRouter([{ test: '**/*.{js,tsx}', parser }]); + + expect(router('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/project/Button.tsx').parser).toBe(parser); + expect(router('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/project/Button.js').parser).toBe(parser); + expect(() => router('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/project/Button.css')).toThrow(); + }); + + test('passes route options and requires a filename for multiple parsers', () => { + const typescript = makeParser('TypeScriptFile'); + const hermes = makeParser('HermesFile'); + const parse = createDocgen({ + handlers: [handler], + parser: createParserRouter([ + { test: /\.tsx$/, parser: typescript, options: { jsx: true } }, + { test: /\.js$/, parser: hermes }, + ]), + resolver, + }); + + expect(() => parse('')).toThrow( + 'A filename is required when multiple parsers are configured.', + ); + expect(parse('', { filename: 'Button.tsx' })).toEqual([ + { description: 'TypeScriptFile', methods: [] }, + ]); + expect(typescript.parse).toHaveBeenCalledWith( + { code: '', filename: 'Button.tsx' }, + { jsx: true }, + ); + }); + + test('routes imported files independently', () => { + const parse = createDocgen({ + handlers: [ + (_documentation, _path, file) => { + _documentation.description = file.import('./support.js').ast.type; + }, + ], + importer: () => ({ code: '', filename: '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/project/support.js' }), + parser: createParserRouter([ + { test: '**/*.tsx', parser: makeParser('TypeScriptFile') }, + { test: '**/*.js', parser: makeParser('HermesFile') }, + ]), + resolver, + }); + + expect(parse('', { filename: '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/project/Button.tsx' })).toEqual([ + { description: 'HermesFile', methods: [] }, + ]); + }); + + test('reports an explicit no-match error', () => { + const router = createParserRouter([ + { test: '**/*.tsx', parser: makeParser('TypeScriptFile') }, + ]); + + expect(() => router('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/project/Button.js')).toThrow( + 'No parser route matched "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/project/Button.js".', + ); + }); +}); diff --git a/packages/core/src/__tests__/extension-api-test.ts b/packages/core/src/__tests__/extension-api-test.ts new file mode 100644 index 00000000000..715b275ac9a --- /dev/null +++ b/packages/core/src/__tests__/extension-api-test.ts @@ -0,0 +1,34 @@ +import { expect, test } from 'vitest'; +import { + createDocgen, + type Handler, + type Importer, + type Parser, + type Resolver, +} from '../index.js'; + +test('composes neutral parser, resolver, handler, and importer APIs', () => { + const parser: Parser = { + visitorKeys: { Program: ['body'] }, + parse: ({ code }) => ({ type: 'Program', body: [], code }), + }; + const resolver: Resolver = (file) => [file.path]; + const handler: Handler = (documentation, _path, file) => { + documentation.description = file.import('./description').source.code; + }; + const importer: Importer = (specifier) => ({ + code: specifier === './description' ? 'Portable description.' : '', + filename: 'description.js', + }); + + const parse = createDocgen({ + handlers: [handler], + importer, + parser, + resolver, + }); + + expect(parse('')).toEqual([ + { description: 'Portable description.', methods: [] }, + ]); +}); diff --git a/packages/core/src/__tests__/findImperativeHandleMethods-test.ts b/packages/core/src/__tests__/findImperativeHandleMethods-test.ts new file mode 100644 index 00000000000..6c9584729f2 --- /dev/null +++ b/packages/core/src/__tests__/findImperativeHandleMethods-test.ts @@ -0,0 +1,159 @@ +import { expect, test } from 'vitest'; +import { ProjectContext, type AstNode } from '../index.js'; +import findImperativeHandleMethods from '../utils/findImperativeHandleMethods.js'; + +const id = (name: string): AstNode => ({ type: 'Identifier', name }); +const fn = (): AstNode => ({ + type: 'ArrowFunctionExpression', + params: [], + body: { type: 'BlockStatement', body: [] }, +}); +const variable = (name: string, init: AstNode): AstNode => ({ + type: 'VariableDeclaration', + declarations: [{ type: 'VariableDeclarator', id: id(name), init }], +}); +const call = (name: string, args: AstNode[]): AstNode => ({ + type: 'CallExpression', + callee: id(name), + arguments: args, +}); + +function findMethods({ + declarations = [], + params = [], + source = 'react', + value = call('useCb', [fn()]), + factories, +}: { + declarations?: AstNode[]; + params?: AstNode[]; + source?: string; + value?: AstNode; + factories?: AstNode[]; +} = {}) { + const property = { type: 'Property', key: id('focus'), value: id('method') }; + const ast: AstNode = { + type: 'Program', + body: [ + { + type: 'ImportDeclaration', + source: { type: 'Literal', value: source }, + specifiers: ['useCallback', 'useImperativeHandle'].map( + (name, index) => ({ + type: 'ImportSpecifier', + imported: id(name), + local: id(index === 0 ? 'useCb' : name), + }), + ), + }, + { + type: 'FunctionDeclaration', + id: id('Input'), + params, + body: { + type: 'BlockStatement', + body: [ + ...declarations, + variable('method', value), + ...( + factories ?? [ + { + type: 'ArrowFunctionExpression', + params: [], + body: { type: 'ObjectExpression', properties: [property] }, + }, + ] + ).map((factory) => ({ + type: 'ExpressionStatement', + expression: call('useImperativeHandle', [id('ref'), factory]), + })), + ], + }, + }, + ], + }; + const project = new ProjectContext({ + importer() { + throw new Error('Unexpected import'); + }, + selectParser: () => ({ + parse: () => ast, + visitorKeys: { + BlockStatement: ['body'], + ExpressionStatement: ['expression'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + }, + }), + }); + const file = project.parse({ code: '', filename: 'input.js' }); + const body = file.path.get('body'); + const component = Array.isArray(body) ? body[1] : null; + + if (!component) throw new Error('Missing component'); + + return findImperativeHandleMethods(file, component); +} + +test('resolves React aliases and component-local callback identifiers', () => { + const callback = fn(); + const methods = findMethods({ + declarations: [variable('callback', callback)], + value: call('useCb', [id('callback')]), + }); + + expect(methods).toHaveLength(1); + expect(methods[0]?.fn).toBe(callback); +}); + +test('does not mistake a component parameter for an imported React hook', () => { + expect(findMethods({ params: [id('useCb')] })).toEqual([]); +}); + +test('does not unwrap hooks imported from another package', () => { + expect(findMethods({ source: 'other-library' })).toEqual([]); +}); + +test('stops resolving circular callback aliases', () => { + expect( + findMethods({ + declarations: [ + variable('first', id('second')), + variable('second', id('first')), + ], + value: call('useCb', [id('first')]), + }), + ).toEqual([]); +}); + +test('keeps visitor state separate across factories and extractions', () => { + const first = fn(); + const second = fn(); + const factories: AstNode[] = [first, second].map((callback) => ({ + type: 'ArrowFunctionExpression', + params: [], + body: { + type: 'BlockStatement', + body: [ + variable('handle', { + type: 'ObjectExpression', + properties: [ + { + type: 'Property', + key: id('focus'), + value: call('useCb', [callback]), + }, + ], + }), + { type: 'ReturnStatement', argument: id('handle') }, + ], + }, + })); + + expect(findMethods({ factories }).map((method) => method.fn)).toEqual([ + first, + second, + ]); + expect(findMethods({ source: 'other-library' })).toEqual([]); + expect(findMethods()).toHaveLength(1); +}); diff --git a/packages/core/src/__tests__/propTypesImports-test.ts b/packages/core/src/__tests__/propTypesImports-test.ts new file mode 100644 index 00000000000..204bf46ba3e --- /dev/null +++ b/packages/core/src/__tests__/propTypesImports-test.ts @@ -0,0 +1,140 @@ +import { expect, test } from 'vitest'; +import { createDocgen, propTypesHandler, type AstNode } from '../index.js'; + +const id = (name: string): AstNode => ({ type: 'Identifier', name }); +const literal = (value: string): AstNode => ({ type: 'Literal', value }); +const imported = (source: string, named = false): AstNode => ({ + type: 'ImportDeclaration', + source: literal(source), + specifiers: [ + { + type: named ? 'ImportSpecifier' : 'ImportDefaultSpecifier', + local: id('PropTypes'), + ...(named ? { imported: id('PropTypes') } : {}), + }, + ], +}); + +function propType(imports: AstNode[], prefix = '') { + const raw = 'PropTypes.string'; + const code = `${prefix}\n${raw}`; + const component: AstNode = { + type: 'FunctionDeclaration', + id: id('Button'), + params: [], + }; + const ast: AstNode = { + type: 'Program', + body: [ + ...imports, + component, + { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'MemberExpression', + computed: false, + object: id('Button'), + property: id('propTypes'), + }, + right: { + type: 'ObjectExpression', + properties: [ + { + type: 'Property', + key: id('value'), + value: { + type: 'MemberExpression', + computed: false, + object: id('PropTypes'), + property: id('string'), + range: [code.length - raw.length, code.length], + }, + }, + ], + }, + }, + }, + ], + }; + const parse = createDocgen({ + parser: { + parse: () => ast, + visitorKeys: { + Program: ['body'], + ImportDeclaration: ['specifiers', 'source'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + CallExpression: ['callee', 'arguments'], + }, + }, + resolver(file) { + const body = file.path.get('body'); + + return Array.isArray(body) + ? body.filter((path) => path.node === component) + : []; + }, + handlers: [propTypesHandler], + }); + + return parse(code, { filename: 'button.js' })[0]?.props?.value?.type; +} + +test('recognizes a package import with long whitespace from its AST', () => { + expect( + propType( + [imported('prop-types')], + `import ${' '.repeat(20_000)}PropTypes from 'prop-types';`, + ), + ).toEqual({ name: 'string' }); +}); + +test('recognizes named React PropTypes imports', () => { + expect( + propType([imported('react', true)], "import { PropTypes } from 'react';"), + ).toEqual({ name: 'string' }); +}); + +test('recognizes require calls with whitespace and comments', () => { + const declaration: AstNode = { + type: 'VariableDeclaration', + declarations: [ + { + type: 'VariableDeclarator', + id: id('PropTypes'), + init: { + type: 'CallExpression', + callee: id('require'), + arguments: [literal('prop-types')], + }, + }, + ], + }; + + expect( + propType( + [declaration], + "const PropTypes = require( /* package */ 'prop-types' );", + ), + ).toEqual({ name: 'string' }); +}); + +test.each([ + { name: 'a comment', source: "// import { PropTypes } from 'react';" }, + { + name: 'a string literal', + source: `const example = "require('prop-types')";`, + }, + { + name: 'a long unrelated import', + source: `import ${' '.repeat(20_000)}PropTypes from 'custom-validators';`, + }, +])('does not infer imports from $name', ({ source }) => { + expect(propType([imported('custom-validators')], source)).toEqual({ + name: 'custom', + raw: 'PropTypes.string', + }); +}); diff --git a/packages/core/src/__tests__/traverse-test.ts b/packages/core/src/__tests__/traverse-test.ts new file mode 100644 index 00000000000..d4f5f4ca7b4 --- /dev/null +++ b/packages/core/src/__tests__/traverse-test.ts @@ -0,0 +1,97 @@ +import { describe, expect, test } from 'vitest'; +import { AstPath, traverse, type AstNode, type VisitorKeys } from '../index.js'; + +const visitorKeys: VisitorKeys = { + Identifier: [], + Program: ['body'], + Wrapper: ['value'], +}; + +const ast: AstNode = { + type: 'Program', + body: [ + { type: 'Identifier', name: 'first' }, + { + type: 'Wrapper', + value: { type: 'Identifier', name: 'nested' }, + }, + { type: 'Identifier', name: 'last' }, + ], +}; + +describe('AstPath', () => { + test('addresses node and list children', () => { + const root = new AstPath({ node: ast }); + const body = root.get('body'); + + expect(body).toHaveLength(3); + expect((body as AstPath[])[0]).toMatchObject({ + key: 0, + listKey: 'body', + parentPath: root, + }); + expect((body as AstPath[])[1]?.get('value')).toMatchObject({ + key: 'value', + listKey: null, + parentPath: (body as AstPath[])[1], + }); + expect(root.get('missing')).toBeNull(); + }); +}); + +describe('traverse', () => { + test('visits nodes in enter/exit order', () => { + const visited: string[] = []; + + traverse( + ast, + visitorKeys, + { + enter(path) { + visited.push(`enter:${path.node.type}`); + }, + exit(path) { + visited.push(`exit:${path.node.type}`); + }, + }, + undefined, + ); + + expect(visited).toEqual([ + 'enter:Program', + 'enter:Identifier', + 'exit:Identifier', + 'enter:Wrapper', + 'enter:Identifier', + 'exit:Identifier', + 'exit:Wrapper', + 'enter:Identifier', + 'exit:Identifier', + 'exit:Program', + ]); + }); + + test('supports type visitors, skip, stop, and state', () => { + const names: string[] = []; + + traverse( + ast, + visitorKeys, + { + Identifier(path, state) { + state.push(path.node.name as string); + + if (path.node.name === 'last') { + path.stop(); + } + }, + Wrapper(path) { + path.skip(); + }, + }, + names, + ); + + expect(names).toEqual(['first', 'last']); + }); +}); diff --git a/packages/core/src/createDocgen.ts b/packages/core/src/createDocgen.ts new file mode 100644 index 00000000000..f9c95ae2b78 --- /dev/null +++ b/packages/core/src/createDocgen.ts @@ -0,0 +1,61 @@ +import extract, { + type ComponentDocumentation, + type Handler, + type Resolver, +} from './extract.js'; +import ProjectContext, { + type Importer, + type Parser, + type ParserSelector, +} from './ProjectContext.js'; +import type { ParserRouter } from './createParserRouter.js'; + +export interface CreateDocgenOptions { + handlers: readonly Handler[]; + importer?: Importer; + parser: Parser | ParserSelector; + resolver: Resolver; +} + +export interface DocgenParseOptions { + filename?: string; + importer?: Importer; +} + +export default function createDocgen({ + handlers, + importer: defaultImporter, + parser, + resolver, +}: CreateDocgenOptions): ( + code: string, + options?: DocgenParseOptions, +) => ComponentDocumentation[] { + return (code, options = {}) => { + const { importer } = options; + const filename = options.filename ?? 'component.js'; + + if ( + typeof parser === 'function' && + (parser as ParserRouter).requiresFilename && + options.filename == null + ) { + throw new TypeError( + 'A filename is required when multiple parsers are configured.', + ); + } + + const project = new ProjectContext({ + importer: + importer ?? + defaultImporter ?? + (() => { + throw new Error('An importer is required to resolve imported files.'); + }), + selectParser: typeof parser === 'function' ? parser : () => parser, + }); + const file = project.parse({ code, filename }); + + return extract(file, resolver, handlers); + }; +} diff --git a/packages/core/src/createParserRouter.ts b/packages/core/src/createParserRouter.ts new file mode 100644 index 00000000000..390fc51f122 --- /dev/null +++ b/packages/core/src/createParserRouter.ts @@ -0,0 +1,49 @@ +import { matchesGlob } from 'node:path'; +import type { + Parser, + ParserSelection, + ParserSelector, +} from './ProjectContext.js'; + +export type ParserRouteTest = RegExp | string | ((filename: string) => boolean); + +export interface ParserRoute { + readonly options?: unknown; + readonly parser: Parser; + readonly test: ParserRouteTest; +} + +export interface ParserRouter extends ParserSelector { + readonly requiresFilename: boolean; +} + +function matches(test: ParserRouteTest, filename: string): boolean { + if (typeof test === 'function') return test(filename); + if (typeof test === 'string') return matchesGlob(filename, test); + + test.lastIndex = 0; + + return test.test(filename); +} + +export default function createParserRouter( + routes: readonly ParserRoute[], +): ParserRouter { + if (routes.length === 0) { + throw new TypeError('Parser routes must not be empty.'); + } + + const router = (filename: string): ParserSelection => { + const route = routes.find(({ test }) => matches(test, filename)); + + if (!route) { + throw Object.assign(new Error(`No parser route matched "${filename}".`), { + code: 'ERR_REACTDOCGEN_PARSER_NO_MATCH', + }); + } + + return { options: route.options, parser: route.parser }; + }; + + return Object.assign(router, { requiresFilename: routes.length > 1 }); +} diff --git a/packages/core/src/extract.ts b/packages/core/src/extract.ts new file mode 100644 index 00000000000..6cc304e47a5 --- /dev/null +++ b/packages/core/src/extract.ts @@ -0,0 +1,57 @@ +import type AstPath from './AstPath.js'; +import type { FileState } from './ProjectContext.js'; + +export interface TypeDescriptor { + readonly name: string; + readonly [key: string]: unknown; +} + +export interface DefaultValueDescriptor { + readonly computed: boolean; + readonly value: string; +} + +export interface PropDescriptor { + defaultValue?: DefaultValueDescriptor; + description?: string; + flowType?: TypeDescriptor; + required: boolean; + tsType?: TypeDescriptor; + type?: TypeDescriptor; +} + +export interface ComponentDocumentation { + composes?: string[]; + childContext?: Record>; + context?: Record>; + description: string; + displayName?: number | string; + methods: unknown[]; + props?: Record; +} + +export type Resolver = (file: FileState) => AstPath[]; +export type Handler = ( + documentation: ComponentDocumentation, + path: AstPath, + file: FileState, +) => void; + +export default function extract( + file: FileState, + resolver: Resolver, + handlers: readonly Handler[], +): ComponentDocumentation[] { + return resolver(file).map((path) => { + const documentation: ComponentDocumentation = { + description: '', + methods: [], + }; + + for (const handler of handlers) { + handler(documentation, path, file); + } + + return documentation; + }); +} diff --git a/packages/core/src/guards.ts b/packages/core/src/guards.ts new file mode 100644 index 00000000000..0a119ea8451 --- /dev/null +++ b/packages/core/src/guards.ts @@ -0,0 +1,127 @@ +import type { AstNode } from './AstNode.js'; +import type { + AssignmentPattern, + AssignmentExpression, + BlockStatement, + ArrayExpression, + ArrowFunctionExpression, + CallExpression, + ClassDeclaration, + ClassExpression, + ExportNamedDeclaration, + ExportDefaultDeclaration, + ExpressionStatement, + FunctionDeclaration, + FunctionExpression, + Identifier, + Literal, + MemberExpression, + MethodDefinition, + ObjectPattern, + ObjectExpression, + Program, + Property, + PropertyDefinition, + ReturnStatement, + SpreadElement, + TSBooleanKeyword, + TSInterfaceDeclaration, + TSPropertySignature, + TSStringKeyword, + TSTypeAliasDeclaration, + TSTypeAnnotation, + TSTypeLiteral, + TSTypeReference, + VariableDeclaration, + VariableDeclarator, +} from './nodes.js'; + +function isType(node: AstNode, type: T['type']): node is T { + return node.type === type; +} + +export const isAssignmentPattern = (node: AstNode): node is AssignmentPattern => + isType(node, 'AssignmentPattern'); +export const isAssignmentExpression = ( + node: AstNode, +): node is AssignmentExpression => isType(node, 'AssignmentExpression'); +export const isArrayExpression = (node: AstNode): node is ArrayExpression => + isType(node, 'ArrayExpression'); +export const isBlockStatement = (node: AstNode): node is BlockStatement => + isType(node, 'BlockStatement'); +export const isArrowFunctionExpression = ( + node: AstNode, +): node is ArrowFunctionExpression => isType(node, 'ArrowFunctionExpression'); +export const isCallExpression = (node: AstNode): node is CallExpression => + isType(node, 'CallExpression'); +export const isClassDeclaration = (node: AstNode): node is ClassDeclaration => + isType(node, 'ClassDeclaration'); +export const isClassExpression = (node: AstNode): node is ClassExpression => + isType(node, 'ClassExpression'); +export const isExportDefaultDeclaration = ( + node: AstNode, +): node is ExportDefaultDeclaration => isType(node, 'ExportDefaultDeclaration'); +export const isExportNamedDeclaration = ( + node: AstNode, +): node is ExportNamedDeclaration => isType(node, 'ExportNamedDeclaration'); +export const isExpressionStatement = ( + node: AstNode, +): node is ExpressionStatement => isType(node, 'ExpressionStatement'); +export const isFunctionDeclaration = ( + node: AstNode, +): node is FunctionDeclaration => isType(node, 'FunctionDeclaration'); +export const isFunctionExpression = ( + node: AstNode, +): node is FunctionExpression => isType(node, 'FunctionExpression'); +export const isIdentifier = ( + node: AstNode, + options?: { name?: string }, +): node is Identifier => + isType(node, 'Identifier') && + (options?.name === undefined || node.name === options.name); +export const isLiteral = (node: AstNode): node is Literal => + isType(node, 'Literal'); +export const isMemberExpression = (node: AstNode): node is MemberExpression => + isType(node, 'MemberExpression'); +export const isMethodDefinition = (node: AstNode): node is MethodDefinition => + isType(node, 'MethodDefinition'); +export const isObjectPattern = (node: AstNode): node is ObjectPattern => + isType(node, 'ObjectPattern'); +export const isObjectExpression = (node: AstNode): node is ObjectExpression => + isType(node, 'ObjectExpression'); +export const isProgram = (node: AstNode): node is Program => + isType(node, 'Program'); +export const isProperty = (node: AstNode): node is Property => + isType(node, 'Property'); +export const isPropertyDefinition = ( + node: AstNode, +): node is PropertyDefinition => isType(node, 'PropertyDefinition'); +export const isReturnStatement = (node: AstNode): node is ReturnStatement => + isType(node, 'ReturnStatement'); +export const isSpreadElement = (node: AstNode): node is SpreadElement => + isType(node, 'SpreadElement'); +export const isTSBooleanKeyword = (node: AstNode): node is TSBooleanKeyword => + isType(node, 'TSBooleanKeyword'); +export const isTSInterfaceDeclaration = ( + node: AstNode, +): node is TSInterfaceDeclaration => isType(node, 'TSInterfaceDeclaration'); +export const isTSPropertySignature = ( + node: AstNode, +): node is TSPropertySignature => isType(node, 'TSPropertySignature'); +export const isTSStringKeyword = (node: AstNode): node is TSStringKeyword => + isType(node, 'TSStringKeyword'); +export const isTSTypeAliasDeclaration = ( + node: AstNode, +): node is TSTypeAliasDeclaration => isType(node, 'TSTypeAliasDeclaration'); +export const isTSTypeAnnotation = (node: AstNode): node is TSTypeAnnotation => + isType(node, 'TSTypeAnnotation'); +export const isTSTypeLiteral = (node: AstNode): node is TSTypeLiteral => + isType(node, 'TSTypeLiteral'); +export const isTSTypeReference = (node: AstNode): node is TSTypeReference => + isType(node, 'TSTypeReference'); +export const isVariableDeclaration = ( + node: AstNode, +): node is VariableDeclaration => isType(node, 'VariableDeclaration'); +export const isVariableDeclarator = ( + node: AstNode, +): node is VariableDeclarator => isType(node, 'VariableDeclarator'); diff --git a/packages/core/src/handlers/componentHandler.ts b/packages/core/src/handlers/componentHandler.ts new file mode 100644 index 00000000000..c610f324ab5 --- /dev/null +++ b/packages/core/src/handlers/componentHandler.ts @@ -0,0 +1,47 @@ +import { + isClassDeclaration, + isClassExpression, + isCallExpression, + isArrowFunctionExpression, + isFunctionDeclaration, + isFunctionExpression, + isLiteral, + type Handler, +} from '../internal.js'; +import getComponentDescription from '../utils/getComponentDescription.js'; +import getComponentName from '../utils/getComponentName.js'; +import getExplicitDisplayName from '../utils/getExplicitDisplayName.js'; +import getClassStaticValue from '../utils/getClassStaticValue.js'; + +const componentHandler: Handler = (documentation, path, file) => { + if ( + !isFunctionDeclaration(path.node) && + !isClassDeclaration(path.node) && + !isClassExpression(path.node) && + !isFunctionExpression(path.node) && + !isArrowFunctionExpression(path.node) && + !isCallExpression(path.node) + ) { + return; + } + + const componentName = getComponentName(path); + + if (componentName) { + const staticDisplayName = getClassStaticValue(file, path, 'displayName'); + const explicitDisplayName = + staticDisplayName && + isLiteral(staticDisplayName) && + (typeof staticDisplayName.value === 'string' || + typeof staticDisplayName.value === 'number') + ? staticDisplayName.value + : getExplicitDisplayName(file, componentName); + + if (explicitDisplayName !== null) { + documentation.displayName = explicitDisplayName ?? componentName; + } + } + documentation.description = getComponentDescription(file, path); +}; + +export default componentHandler; diff --git a/packages/core/src/handlers/contextHandler.ts b/packages/core/src/handlers/contextHandler.ts new file mode 100644 index 00000000000..745f9d3d95d --- /dev/null +++ b/packages/core/src/handlers/contextHandler.ts @@ -0,0 +1,65 @@ +import { + isAssignmentExpression, + isExpressionStatement, + isIdentifier, + isMemberExpression, + isObjectExpression, + isProperty, + type Handler, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import getComponentName from '../utils/getComponentName.js'; +import getPropType from '../utils/getPropType.js'; + +const contextHandler: Handler = (documentation, path, file) => { + const componentName = getComponentName(path); + + if (!componentName) { + return; + } + + for (const statement of getBody(file)) { + if (!isExpressionStatement(statement.node)) { + continue; + } + + const assignment = statement.node.expression; + + if ( + !isAssignmentExpression(assignment) || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(assignment.left.object, { name: componentName }) || + !isIdentifier(assignment.left.property) || + !isObjectExpression(assignment.right) + ) { + continue; + } + + const target = + assignment.left.property.name === 'contextTypes' + ? 'context' + : assignment.left.property.name === 'childContextTypes' + ? 'childContext' + : null; + + if (!target) { + continue; + } + + for (const property of assignment.right.properties) { + if (!isProperty(property) || !isIdentifier(property.key)) { + continue; + } + + const propType = getPropType(property.value); + + if (propType) { + documentation[target] ??= {}; + documentation[target][property.key.name] = propType; + } + } + } +}; + +export default contextHandler; diff --git a/packages/core/src/handlers/defaultPropsHandler.ts b/packages/core/src/handlers/defaultPropsHandler.ts new file mode 100644 index 00000000000..242ca77e405 --- /dev/null +++ b/packages/core/src/handlers/defaultPropsHandler.ts @@ -0,0 +1,104 @@ +import { + isArrowFunctionExpression, + isAssignmentExpression, + isExpressionStatement, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isMemberExpression, + isObjectPattern, + type Handler, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import getComponentName from '../utils/getComponentName.js'; +import getDefaultValue from '../utils/getDefaultValue.js'; +import getParameterDefaults from '../utils/getParameterDefaults.js'; +import getObjectProperties from '../utils/getObjectProperties.js'; +import getPropertyName from '../utils/getPropertyName.js'; +import getClassStaticValue from '../utils/getClassStaticValue.js'; +import unwrapExpression from '../utils/unwrapExpression.js'; + +const defaultPropsHandler: Handler = (documentation, path, file) => { + const componentName = getComponentName(path); + + if ( + isFunctionDeclaration(path.node) || + isFunctionExpression(path.node) || + isArrowFunctionExpression(path.node) + ) { + const [parameter] = path.node.params; + + if (parameter && isObjectPattern(parameter)) { + for (const [name, value] of getParameterDefaults(parameter)) { + const prop = documentation.props?.[name]; + + if (prop) { + prop.defaultValue = getDefaultValue(file, value); + prop.required = false; + } else { + documentation.props ??= {}; + documentation.props[name] = { + defaultValue: getDefaultValue(file, value), + required: false, + }; + } + } + } + } + + if (!componentName) { + return; + } + + const staticDefaults = getClassStaticValue(file, path, 'defaultProps'); + const defaultObjects = staticDefaults ? [staticDefaults] : []; + + for (const statement of getBody(file)) { + if (!isExpressionStatement(statement.node)) { + continue; + } + + const assignment = statement.node.expression; + + if ( + !isAssignmentExpression(assignment) || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(unwrapExpression(assignment.left.object), { + name: componentName, + }) || + !isIdentifier(assignment.left.property, { name: 'defaultProps' }) + ) { + continue; + } + + defaultObjects.push(assignment.right); + } + + for (const defaultsObject of defaultObjects) { + for (const property of getObjectProperties(file, defaultsObject)) { + const keyName = getPropertyName(property.key); + const propertyName = + keyName && property.computed && isIdentifier(property.key) + ? `@computed#${keyName}` + : keyName; + + if (!propertyName) continue; + + const prop = documentation.props?.[propertyName]; + + if (prop) { + prop.defaultValue = getDefaultValue(file, property.value); + prop.required = false; + } else { + documentation.props ??= {}; + documentation.props[propertyName] = { + defaultValue: getDefaultValue(file, property.value), + required: false, + }; + } + } + } +}; + +export default defaultPropsHandler; diff --git a/packages/core/src/handlers/methodHandler.ts b/packages/core/src/handlers/methodHandler.ts new file mode 100644 index 00000000000..dba59dc624e --- /dev/null +++ b/packages/core/src/handlers/methodHandler.ts @@ -0,0 +1,192 @@ +import { + isArrowFunctionExpression, + isClassDeclaration, + isClassExpression, + isIdentifier, + isFunctionDeclaration, + isFunctionExpression, + isMethodDefinition, + isPropertyDefinition, + type AstNode, + type Handler, + type FileState, + type TypeDescriptor, +} from '../internal.js'; +import getDescription from '../utils/getDescription.js'; +import getPropertyName from '../utils/getPropertyName.js'; +import parseMethodDocblock from '../utils/parseMethodDocblock.js'; +import findImperativeHandleMethods from '../utils/findImperativeHandleMethods.js'; + +const reactMethods = new Set([ + 'componentDidMount', + 'componentDidReceiveProps', + 'componentDidUpdate', + 'componentWillMount', + 'UNSAFE_componentWillMount', + 'componentWillReceiveProps', + 'UNSAFE_componentWillReceiveProps', + 'componentWillUnmount', + 'componentWillUpdate', + 'UNSAFE_componentWillUpdate', + 'getChildContext', + 'getDefaultProps', + 'getInitialState', + 'render', + 'shouldComponentUpdate', + 'getDerivedStateFromProps', + 'getDerivedStateFromError', + 'getSnapshotBeforeUpdate', + 'componentDidCatch', +]); + +function addImperativeMethods( + documentation: Parameters[0], + path: Parameters[1], + file: Parameters[2], + getType?: TypeResolver, +): void { + if ( + !isFunctionDeclaration(path.node) && + !isFunctionExpression(path.node) && + !isArrowFunctionExpression(path.node) + ) + return; + for (const { property, fn } of findImperativeHandleMethods(file, path)) { + const name = getPropertyName(property.key); + + if (!name || reactMethods.has(name)) continue; + const modifiers: string[] = []; + + if (fn.generator) modifiers.push('generator'); + if (fn.async) modifiers.push('async'); + documentation.methods.push( + methodDocumentation(file, property, fn, name, modifiers, getType), + ); + } +} + +export type TypeResolver = ( + file: FileState, + annotation: AstNode, +) => TypeDescriptor | null; + +function methodDocumentation( + file: FileState, + member: AstNode, + fn: AstNode, + name: string, + modifiers: string[], + getType?: TypeResolver, +) { + const params = Array.isArray(fn.params) ? (fn.params as AstNode[]) : []; + const returnType = + fn.returnType && + typeof fn.returnType === 'object' && + 'type' in fn.returnType + ? (fn.returnType as AstNode) + : null; + const description = getDescription(file, member); + const parsedDocblock = parseMethodDocblock(description); + + return { + name, + docblock: description || null, + modifiers, + params: params.map((parameter) => { + const annotation = + parameter.typeAnnotation && + typeof parameter.typeAnnotation === 'object' && + 'type' in parameter.typeAnnotation + ? (parameter.typeAnnotation as AstNode) + : null; + const rawName = Array.isArray(parameter.range) + ? file.source.code + .slice(parameter.range[0], parameter.range[1]) + .replace(/\??:\s*[\s\S]*$/, '') + : isIdentifier(parameter) + ? parameter.name + : ''; + const normalizedName = rawName + .replace(/^\.\.\./, '') + .replace(/\s*=.*$/, ''); + const documented = + parameter.type === 'Identifier' || + parameter.type === 'AssignmentPattern' + ? parsedDocblock.params.get(normalizedName) + : undefined; + const type = + documented?.type ?? + (annotation && getType ? getType(file, annotation) : null); + + return { + name: rawName.replace(/\s*=.*$/, ''), + optional: Boolean( + documented?.optional || + parameter.optional || + parameter.type === 'AssignmentPattern', + ), + ...(!description || documented || parameter.type === 'Identifier' + ? { type } + : {}), + ...(documented?.description + ? { description: documented.description } + : {}), + }; + }), + returns: + parsedDocblock.returns ?? + (returnType && getType ? { type: getType(file, returnType) } : null), + ...(parsedDocblock.description + ? { description: parsedDocblock.description } + : {}), + }; +} + +export default function createMethodHandler(getType?: TypeResolver): Handler { + return (documentation, path, file) => { + addImperativeMethods(documentation, path, file, getType); + if (!isClassDeclaration(path.node) && !isClassExpression(path.node)) return; + + for (const member of path.node.body.body) { + if (member.accessibility === 'private') continue; + let name: string | null = null; + let fn: AstNode | null = null; + const modifiers: string[] = []; + + if (isMethodDefinition(member)) { + name = getPropertyName(member.key); + fn = member.value; + if (member.static) modifiers.push('static'); + if (member.kind === 'get' || member.kind === 'set') { + modifiers.push(member.kind); + } + if (member.value.async) modifiers.push('async'); + if (member.value.generator) modifiers.push('generator'); + } else if ( + isPropertyDefinition(member) && + member.value && + isArrowFunctionExpression(member.value) + ) { + name = getPropertyName(member.key); + fn = member.value; + if (member.static) modifiers.push('static'); + if (member.value.async) modifiers.push('async'); + } + + if ( + !name || + !fn || + name === 'constructor' || + name === 'render' || + name === 'UNSAFE_componentWillReceiveProps' || + name === 'componentDidMount' || + name === 'componentWillUnmount' + ) + continue; + + documentation.methods.push( + methodDocumentation(file, member, fn, name, modifiers, getType), + ); + } + }; +} diff --git a/packages/core/src/handlers/propTypesHandler.ts b/packages/core/src/handlers/propTypesHandler.ts new file mode 100644 index 00000000000..60f8a132bfa --- /dev/null +++ b/packages/core/src/handlers/propTypesHandler.ts @@ -0,0 +1,167 @@ +import { + isAssignmentExpression, + isCallExpression, + isExpressionStatement, + isIdentifier, + isLiteral, + isMemberExpression, + type FileState, + type Handler, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import getComponentName from '../utils/getComponentName.js'; +import getDescription from '../utils/getDescription.js'; +import getPropType from '../utils/getPropType.js'; +import getObjectProperties from '../utils/getObjectProperties.js'; +import getMemberName from '../utils/getMemberName.js'; +import getPropertyName from '../utils/getPropertyName.js'; +import resolveValue from '../utils/resolveValue.js'; +import getClassStaticValue from '../utils/getClassStaticValue.js'; +import getResolvedEnumValues from '../utils/getResolvedEnumValues.js'; +import unwrapExpression from '../utils/unwrapExpression.js'; +import type { Visitor } from '../traverse.js'; + +interface PropTypesImportState { + found: boolean; +} + +const propTypesImportVisitor: Visitor = { + ImportDeclaration(path, state) { + const source = path.get('source'); + + if (!source || Array.isArray(source) || !isLiteral(source.node)) return; + if (source.node.value === 'prop-types') { + state.found = true; + } else if (source.node.value === 'react') { + const specifiers = path.get('specifiers'); + + state.found = + Array.isArray(specifiers) && + specifiers.some((specifier) => { + if (specifier.node.type !== 'ImportSpecifier') return false; + const imported = specifier.get('imported'); + + return Boolean( + imported && + !Array.isArray(imported) && + isIdentifier(imported.node, { name: 'PropTypes' }), + ); + }); + } + if (state.found) path.stop(); + }, + CallExpression(path, state) { + if ( + !isCallExpression(path.node) || + !isIdentifier(path.node.callee, { name: 'require' }) + ) + return; + const [source] = path.node.arguments; + + if (source && isLiteral(source) && source.value === 'prop-types') { + state.found = true; + path.stop(); + } + }, +}; + +function hasPropTypesImport(file: FileState): boolean { + const state: PropTypesImportState = { found: false }; + + file.traverse(propTypesImportVisitor, state); + + return state.found; +} + +const propTypesHandler: Handler = (documentation, path, file) => { + const componentName = getComponentName(path); + + if (!componentName) { + return; + } + + const staticPropTypes = getClassStaticValue(file, path, 'propTypes'); + const propTypesObjects = staticPropTypes ? [staticPropTypes] : []; + + for (const statement of getBody(file)) { + if (!isExpressionStatement(statement.node)) { + continue; + } + + const assignment = statement.node.expression; + + if ( + !isAssignmentExpression(assignment) || + assignment.operator !== '=' || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(unwrapExpression(assignment.left.object), { + name: componentName, + }) || + !isIdentifier(assignment.left.property, { name: 'propTypes' }) + ) { + continue; + } + + propTypesObjects.push(assignment.right); + } + + if (propTypesObjects.length === 0) return; + const importedPropTypes = hasPropTypesImport(file); + + for (const propTypesObject of propTypesObjects) { + for (const property of getObjectProperties(file, propTypesObject)) { + const keyName = getPropertyName(property.key); + const propertyName = + keyName && property.computed && isIdentifier(property.key) + ? `@computed#${keyName}` + : keyName; + + if (!propertyName) continue; + + const propType = getPropType( + property.value, + (node) => getDescription(file, node), + (node) => + Array.isArray(node.range) + ? file.source.code.slice(node.range[0], node.range[1]) + : '', + ); + + const resolvedValue = resolveValue(file, property.value); + const raw = Array.isArray(resolvedValue.range) + ? file.source.code.slice(resolvedValue.range[0], resolvedValue.range[1]) + : ''; + + if (!propType) { + documentation.props ??= {}; + documentation.props[propertyName] = { + description: getDescription(file, property), + required: false, + type: { name: 'custom', raw }, + }; + continue; + } + + documentation.props ??= {}; + const memberName = getMemberName(property.value); + const enumValues = getResolvedEnumValues(file, property.value); + const type = enumValues + ? { name: 'enum', value: enumValues } + : memberName?.startsWith('PropTypes.') && !importedPropTypes + ? { + name: 'custom', + raw, + } + : propType.type; + + documentation.props[propertyName] = { + description: getDescription(file, property), + required: propType.required, + type, + }; + } + } +}; + +export default propTypesHandler; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 00000000000..bfcce2b70b3 --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,72 @@ +export { default as AstPath } from './AstPath.js'; +export { default as createDocgen } from './createDocgen.js'; +export { default as createParserRouter } from './createParserRouter.js'; +export { isAstNode } from './AstNode.js'; +export { default as extract } from './extract.js'; +export * from './guards.js'; +export { FileState, default as ProjectContext } from './ProjectContext.js'; +export { default as Scope } from './Scope.js'; +export { default as traverse } from './traverse.js'; +export { default as componentHandler } from './handlers/componentHandler.js'; +export { default as contextHandler } from './handlers/contextHandler.js'; +export { default as defaultPropsHandler } from './handlers/defaultPropsHandler.js'; +export { default as createMethodHandler } from './handlers/methodHandler.js'; +export { default as propTypesHandler } from './handlers/propTypesHandler.js'; +export { default as reactHandlers } from './reactHandlers.js'; +export { default as findExportedDefinitions } from './resolver/findExportedDefinitions.js'; +export { default as resolveComponentDefinitions } from './resolver/resolveComponentDefinitions.js'; +export { default as findImperativeHandleMethods } from './utils/findImperativeHandleMethods.js'; +export { default as findTopLevelDefinition } from './utils/findTopLevelDefinition.js'; +export { default as getBody } from './utils/getBody.js'; +export { default as getClassStaticValue } from './utils/getClassStaticValue.js'; +export { default as getComponentDescription } from './utils/getComponentDescription.js'; +export { default as getComponentName } from './utils/getComponentName.js'; +export { default as getDefaultValue } from './utils/getDefaultValue.js'; +export { default as getDescription } from './utils/getDescription.js'; +export { default as getExplicitDisplayName } from './utils/getExplicitDisplayName.js'; +export { default as getMemberName } from './utils/getMemberName.js'; +export { default as getObjectProperties } from './utils/getObjectProperties.js'; +export { default as getParameterDefaults } from './utils/getParameterDefaults.js'; +export { default as getPropType } from './utils/getPropType.js'; +export { default as getPropertyName } from './utils/getPropertyName.js'; +export { default as getResolvedEnumValues } from './utils/getResolvedEnumValues.js'; +export { default as hasComponentAnnotation } from './utils/hasComponentAnnotation.js'; +export { default as parseMethodDocblock } from './utils/parseMethodDocblock.js'; +export { default as resolveComponentDefinition } from './utils/resolveComponentDefinition.js'; +export { default as resolveValue, getValueFile } from './utils/resolveValue.js'; +export { default as unwrapExpression } from './utils/unwrapExpression.js'; + +export type { AstNode, VisitorKeys } from './AstNode.js'; +export type { + ComponentDocumentation, + DefaultValueDescriptor, + Handler, + PropDescriptor, + Resolver, + TypeDescriptor, +} from './extract.js'; +export type * from './nodes.js'; +export type { + Importer, + Parser, + ParserSelection, + ParserSelector, + SourceFile, +} from './ProjectContext.js'; +export type { + CreateDocgenOptions, + DocgenParseOptions, +} from './createDocgen.js'; +export type { + ParserRoute, + ParserRouter, + ParserRouteTest, +} from './createParserRouter.js'; +export type { Binding, BindingKind } from './Scope.js'; +export type { TypeResolver } from './handlers/methodHandler.js'; +export type { + Visit, + Visitor, + VisitorEntry, + VisitorHandler, +} from './traverse.js'; diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts new file mode 100644 index 00000000000..1b889568be8 --- /dev/null +++ b/packages/core/src/internal.ts @@ -0,0 +1,11 @@ +export * from './guards.js'; +export type { AstNode } from './AstNode.js'; +export type { default as AstPath } from './AstPath.js'; +export type { + DefaultValueDescriptor, + Handler, + Resolver, + TypeDescriptor, +} from './extract.js'; +export type { FileState } from './ProjectContext.js'; +export type * from './nodes.js'; diff --git a/packages/core/src/nodes.ts b/packages/core/src/nodes.ts new file mode 100644 index 00000000000..c3895edac5b --- /dev/null +++ b/packages/core/src/nodes.ts @@ -0,0 +1,230 @@ +import type { AstNode } from './AstNode.js'; + +export interface RangedNode extends AstNode { + readonly range: readonly [number, number]; +} + +export interface Identifier extends RangedNode { + readonly type: 'Identifier'; + readonly name: string; + readonly typeAnnotation?: TSTypeAnnotation; +} + +export interface Program extends RangedNode { + readonly type: 'Program'; + readonly body: AstNode[]; + readonly comments?: Comment[]; +} + +export interface Comment extends RangedNode { + readonly type: 'Block' | 'Line'; + readonly value: string; +} + +export interface ExportNamedDeclaration extends RangedNode { + readonly type: 'ExportNamedDeclaration'; + readonly declaration: AstNode | null; +} + +export interface ExportDefaultDeclaration extends RangedNode { + readonly type: 'ExportDefaultDeclaration'; + readonly declaration: AstNode; +} + +export interface ExpressionStatement extends RangedNode { + readonly type: 'ExpressionStatement'; + readonly expression: AstNode; +} + +export interface AssignmentExpression extends RangedNode { + readonly type: 'AssignmentExpression'; + readonly left: AstNode; + readonly operator: string; + readonly right: AstNode; +} + +export interface CallExpression extends RangedNode { + readonly type: 'CallExpression'; + readonly arguments: AstNode[]; + readonly callee: AstNode; +} + +export interface ArrayExpression extends RangedNode { + readonly type: 'ArrayExpression'; + readonly elements: Array; +} + +export interface MemberExpression extends RangedNode { + readonly type: 'MemberExpression'; + readonly computed: boolean; + readonly object: AstNode; + readonly property: AstNode; +} + +export interface FunctionDeclaration extends RangedNode { + readonly type: 'FunctionDeclaration'; + readonly id: Identifier | null; + readonly params: AstNode[]; +} + +export interface FunctionExpression extends RangedNode { + readonly type: 'FunctionExpression'; + readonly id: Identifier | null; + readonly params: AstNode[]; + readonly body: AstNode; + readonly async?: boolean; + readonly generator?: boolean; + readonly returnType?: TSTypeAnnotation; +} + +export interface ArrowFunctionExpression extends RangedNode { + readonly type: 'ArrowFunctionExpression'; + readonly params: AstNode[]; + readonly body: AstNode; + readonly async?: boolean; + readonly returnType?: TSTypeAnnotation; +} + +export interface VariableDeclaration extends RangedNode { + readonly type: 'VariableDeclaration'; + readonly declarations: AstNode[]; +} + +export interface VariableDeclarator extends RangedNode { + readonly type: 'VariableDeclarator'; + readonly id: AstNode; + readonly init: AstNode | null; +} + +export interface ClassDeclaration extends RangedNode { + readonly type: 'ClassDeclaration'; + readonly body: ClassBody; + readonly id: Identifier | null; + readonly superTypeArguments?: TSTypeParameterInstantiation; +} + +export interface ClassExpression extends RangedNode { + readonly type: 'ClassExpression'; + readonly body: ClassBody; + readonly id: Identifier | null; + readonly superTypeArguments?: TSTypeParameterInstantiation; +} + +export interface ClassBody extends RangedNode { + readonly type: 'ClassBody'; + readonly body: AstNode[]; +} + +export interface PropertyDefinition extends RangedNode { + readonly type: 'PropertyDefinition'; + readonly computed: boolean; + readonly key: AstNode; + readonly static: boolean; + readonly value: AstNode | null; +} + +export interface MethodDefinition extends RangedNode { + readonly type: 'MethodDefinition'; + readonly computed: boolean; + readonly key: AstNode; + readonly kind: 'constructor' | 'get' | 'method' | 'set'; + readonly static: boolean; + readonly value: FunctionExpression; +} + +export interface BlockStatement extends RangedNode { + readonly type: 'BlockStatement'; + readonly body: AstNode[]; +} + +export interface ReturnStatement extends RangedNode { + readonly type: 'ReturnStatement'; + readonly argument: AstNode | null; +} + +export interface ObjectPattern extends RangedNode { + readonly type: 'ObjectPattern'; + readonly properties: AstNode[]; + readonly typeAnnotation?: TSTypeAnnotation; +} + +export interface Property extends RangedNode { + readonly type: 'Property'; + readonly computed?: boolean; + readonly key: AstNode; + readonly value: AstNode; +} + +export interface ObjectExpression extends RangedNode { + readonly type: 'ObjectExpression'; + readonly properties: AstNode[]; +} + +export interface SpreadElement extends RangedNode { + readonly type: 'SpreadElement'; + readonly argument: AstNode; +} + +export interface AssignmentPattern extends RangedNode { + readonly type: 'AssignmentPattern'; + readonly left: AstNode; + readonly right: AstNode; +} + +export interface Literal extends RangedNode { + readonly type: 'Literal'; + readonly raw?: string; + readonly value: boolean | number | string | null; +} + +export interface TSTypeAliasDeclaration extends RangedNode { + readonly type: 'TSTypeAliasDeclaration'; + readonly id: Identifier; + readonly typeAnnotation: AstNode; +} + +export interface TSInterfaceBody extends RangedNode { + readonly type: 'TSInterfaceBody'; + readonly body: AstNode[]; +} + +export interface TSInterfaceDeclaration extends RangedNode { + readonly type: 'TSInterfaceDeclaration'; + readonly body: TSInterfaceBody; + readonly id: Identifier; +} + +export interface TSTypeParameterInstantiation extends RangedNode { + readonly type: 'TSTypeParameterInstantiation'; + readonly params: AstNode[]; +} + +export interface TSTypeAnnotation extends RangedNode { + readonly type: 'TSTypeAnnotation'; + readonly typeAnnotation: AstNode; +} + +export interface TSTypeReference extends RangedNode { + readonly type: 'TSTypeReference'; + readonly typeName: AstNode; +} + +export interface TSTypeLiteral extends RangedNode { + readonly type: 'TSTypeLiteral'; + readonly members: AstNode[]; +} + +export interface TSPropertySignature extends RangedNode { + readonly type: 'TSPropertySignature'; + readonly key: AstNode; + readonly optional: boolean; + readonly typeAnnotation?: TSTypeAnnotation; +} + +export interface TSBooleanKeyword extends RangedNode { + readonly type: 'TSBooleanKeyword'; +} + +export interface TSStringKeyword extends RangedNode { + readonly type: 'TSStringKeyword'; +} diff --git a/packages/core/src/reactHandlers.ts b/packages/core/src/reactHandlers.ts new file mode 100644 index 00000000000..1cbf789f5db --- /dev/null +++ b/packages/core/src/reactHandlers.ts @@ -0,0 +1,15 @@ +import componentHandler from './handlers/componentHandler.js'; +import contextHandler from './handlers/contextHandler.js'; +import defaultPropsHandler from './handlers/defaultPropsHandler.js'; +import createMethodHandler from './handlers/methodHandler.js'; +import propTypesHandler from './handlers/propTypesHandler.js'; + +const reactHandlers = [ + componentHandler, + propTypesHandler, + defaultPropsHandler, + contextHandler, + createMethodHandler(), +]; + +export default reactHandlers; diff --git a/packages/core/src/resolver/findExportedDefinitions.ts b/packages/core/src/resolver/findExportedDefinitions.ts new file mode 100644 index 00000000000..e186318d780 --- /dev/null +++ b/packages/core/src/resolver/findExportedDefinitions.ts @@ -0,0 +1,137 @@ +import { + isAssignmentExpression, + isClassDeclaration, + isExportDefaultDeclaration, + isExportNamedDeclaration, + isFunctionDeclaration, + isExpressionStatement, + isIdentifier, + isMemberExpression, + isVariableDeclaration, + isVariableDeclarator, + type AstPath, + type Resolver, +} from '../internal.js'; +import getBody from '../utils/getBody.js'; +import findTopLevelDefinition from '../utils/findTopLevelDefinition.js'; +import resolveComponentDefinition from '../utils/resolveComponentDefinition.js'; +import hasComponentAnnotation from '../utils/hasComponentAnnotation.js'; + +const findExportedDefinitions: Resolver = (file) => { + const definitions = new Set(); + + for (const path of getBody(file)) { + if ( + isVariableDeclaration(path.node) && + hasComponentAnnotation(file, path.node) + ) { + const declarations = path.get('declarations'); + + if (Array.isArray(declarations)) { + for (const declaration of declarations) { + if (!isVariableDeclarator(declaration.node)) continue; + const init = declaration.get('init'); + + if (!init || Array.isArray(init)) continue; + const definition = resolveComponentDefinition(file, init); + + if (definition) definitions.add(definition); + } + } + } + + if ( + (isExportNamedDeclaration(path.node) || + isExportDefaultDeclaration(path.node)) && + path.node.declaration + ) { + const declaration = path.get('declaration'); + + if ( + declaration && + !Array.isArray(declaration) && + (isFunctionDeclaration(declaration.node) || + isClassDeclaration(declaration.node)) + ) { + if ( + !isFunctionDeclaration(declaration.node) || + !declaration.node.id || + /^[A-Z]/.test(declaration.node.id.name) + ) { + definitions.add(declaration); + } + } else if ( + declaration && + !Array.isArray(declaration) && + isVariableDeclaration(declaration.node) + ) { + const variables = declaration.get('declarations'); + + if (Array.isArray(variables)) { + for (const variable of variables) { + if (!isVariableDeclarator(variable.node)) continue; + const init = variable.get('init'); + + if (!init || Array.isArray(init)) continue; + const definition = resolveComponentDefinition(file, init); + + if (definition) definitions.add(definition); + } + } + } else if (declaration && !Array.isArray(declaration)) { + const definition = resolveComponentDefinition(file, declaration); + + if (definition) { + definitions.add(definition); + } + } + + continue; + } + + if (!isExpressionStatement(path.node)) { + continue; + } + + const assignment = path.node.expression; + + if ( + !isAssignmentExpression(assignment) || + assignment.operator !== '=' || + !isMemberExpression(assignment.left) || + assignment.left.computed || + (!isIdentifier(assignment.right) && + assignment.right.type !== 'CallExpression') + ) { + continue; + } + + const object = assignment.left.object; + const property = assignment.left.property; + const isModuleExport = + isIdentifier(object, { name: 'module' }) && + isIdentifier(property, { name: 'exports' }); + const isNamedExport = isIdentifier(object, { name: 'exports' }); + + if (!isModuleExport && !isNamedExport) { + continue; + } + + const expression = path.get('expression'); + const right = + expression && !Array.isArray(expression) ? expression.get('right') : null; + const definition = isIdentifier(assignment.right) + ? findTopLevelDefinition(file, assignment.right.name) + : right && !Array.isArray(right) + ? resolveComponentDefinition(file, right) + : null; + + if (definition) { + definitions.add(definition); + } + } + + return [...definitions]; +}; + +export default findExportedDefinitions; diff --git a/packages/core/src/resolver/resolveComponentDefinitions.ts b/packages/core/src/resolver/resolveComponentDefinitions.ts new file mode 100644 index 00000000000..b7c7d82761b --- /dev/null +++ b/packages/core/src/resolver/resolveComponentDefinitions.ts @@ -0,0 +1,24 @@ +import type { Resolver } from '../extract.js'; +import findExportedDefinitions from './findExportedDefinitions.js'; + +const resolveComponentDefinitions: Resolver = (file) => { + const definitions = findExportedDefinitions(file); + + if (definitions.length === 1) return definitions; + + throw Object.assign( + new Error( + definitions.length === 0 + ? 'No component definition found.' + : 'Multiple component definitions found.', + ), + { + code: + definitions.length === 0 + ? 'ERR_REACTDOCGEN_MISSING_DEFINITION' + : 'ERR_REACTDOCGEN_MULTIPLE_DEFINITIONS', + }, + ); +}; + +export default resolveComponentDefinitions; diff --git a/packages/core/src/traverse.ts b/packages/core/src/traverse.ts new file mode 100644 index 00000000000..10d3e246ef9 --- /dev/null +++ b/packages/core/src/traverse.ts @@ -0,0 +1,84 @@ +import AstPath from './AstPath.js'; +import type { AstNode, VisitorKeys } from './AstNode.js'; +import type Scope from './Scope.js'; + +export type Visit = (path: AstPath, state: State) => void; + +export interface VisitorHandler { + enter?: Visit; + exit?: Visit; +} + +export type VisitorEntry = Visit | VisitorHandler; + +export type Visitor = Record | undefined> & { + enter?: Visit; + exit?: Visit; +}; + +function callVisitor( + entry: VisitorEntry | undefined, + phase: keyof VisitorHandler, + path: AstPath, + state: State, +): void { + if (typeof entry === 'function') { + if (phase === 'enter') { + entry(path, state); + } + } else { + entry?.[phase]?.(path, state); + } +} + +export default function traverse( + node: AstNode, + visitorKeys: VisitorKeys, + visitor: Visitor, + state: State, + scope?: Scope, +): void { + let stopped = false; + + function visit(path: AstPath): void { + visitor.enter?.(path, state); + callVisitor(visitor[path.node.type], 'enter', path, state); + + if (path.shouldStop) { + stopped = true; + } + + if (stopped || path.shouldSkip) { + return; + } + + for (const name of visitorKeys[path.node.type] ?? []) { + const childPaths = path.get(name); + + if (Array.isArray(childPaths)) { + for (const childPath of childPaths) { + visit(childPath); + + if (stopped) { + return; + } + } + } else if (childPaths) { + visit(childPaths); + + if (stopped) { + return; + } + } + } + + callVisitor(visitor[path.node.type], 'exit', path, state); + visitor.exit?.(path, state); + + if (path.shouldStop) { + stopped = true; + } + } + + visit(new AstPath({ node, scope })); +} diff --git a/packages/core/src/utils/findImperativeHandleMethods.ts b/packages/core/src/utils/findImperativeHandleMethods.ts new file mode 100644 index 00000000000..f5c0bc038f5 --- /dev/null +++ b/packages/core/src/utils/findImperativeHandleMethods.ts @@ -0,0 +1,257 @@ +import { + isArrowFunctionExpression, + isCallExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isProperty, + type AstNode, + type AstPath, + type FileState, + type Property, +} from '../internal.js'; + +function child(path: AstPath, key: string): AstPath | null { + const value = path.get(key); + + return Array.isArray(value) ? null : value; +} + +function children(path: AstPath, key: string): AstPath[] { + const value = path.get(key); + + return Array.isArray(value) ? value : []; +} + +function isFunction(node: AstNode): boolean { + return ( + isArrowFunctionExpression(node) || + isFunctionExpression(node) || + isFunctionDeclaration(node) + ); +} + +function binds(path: AstPath, name: string): boolean { + if (isIdentifier(path.node)) return path.node.name === name; + if (path.node.type === 'AssignmentPattern') { + const left = child(path, 'left'); + + return Boolean(left && binds(left, name)); + } + if (path.node.type === 'RestElement') { + const argument = child(path, 'argument'); + + return Boolean(argument && binds(argument, name)); + } + if (path.node.type === 'ObjectPattern') { + return children(path, 'properties').some((property) => { + const value = child(property, 'value') ?? child(property, 'argument'); + + return Boolean(value && binds(value, name)); + }); + } + + return children(path, 'elements').some((element) => binds(element, name)); +} + +function binding(path: AstPath, name: string): AstPath | null { + for (let scope = path.parentPath; scope; scope = scope.parentPath) { + if (isFunction(scope.node)) { + const id = child(scope, 'id'); + + if (id && binds(id, name)) return scope; + const parameter = children(scope, 'params').find((param) => + binds(param, name), + ); + + if (parameter) return parameter; + } + if (scope.node.type === 'CatchClause') { + const parameter = child(scope, 'param'); + + if (parameter && binds(parameter, name)) return parameter; + } + if (scope.node.type !== 'Program' && scope.node.type !== 'BlockStatement') + continue; + + for (const statement of children(scope, 'body')) { + const declaration = child(statement, 'declaration') ?? statement; + const id = child(declaration, 'id'); + + if (id && binds(id, name)) return declaration; + for (const variable of children(declaration, 'declarations')) { + const variableId = child(variable, 'id'); + + if (variableId && binds(variableId, name)) { + return isIdentifier(variableId.node) + ? (child(variable, 'init') ?? variableId) + : variableId; + } + } + for (const specifier of children(declaration, 'specifiers')) { + const local = child(specifier, 'local'); + + if (local && binds(local, name)) return specifier; + } + } + } + + return null; +} + +function resolve(path: AstPath, seen = new Set()): AstPath { + if (!isIdentifier(path.node) || seen.has(path.node)) return path; + seen.add(path.node); + const value = binding(path, path.node.name); + + return value ? resolve(value, seen) : path; +} + +function isReactImport(path: AstPath): boolean { + const source = path.parentPath && child(path.parentPath, 'source'); + + return Boolean( + source && + isLiteral(source.node) && + ['react', 'react/addons', 'react-native'].includes( + String(source.node.value), + ), + ); +} + +function isReactHook(path: AstPath, name: string): boolean { + const value = resolve(path); + + if (isMemberExpression(value.node) && !value.node.computed) { + if (!isIdentifier(value.node.property, { name })) return false; + const object = child(value, 'object'); + + if (!object) return false; + const imported = resolve(object); + + return ( + ['ImportDefaultSpecifier', 'ImportNamespaceSpecifier'].includes( + imported.node.type, + ) && isReactImport(imported) + ); + } + const imported = child(value, 'imported'); + + return Boolean( + value.node.type === 'ImportSpecifier' && + imported && + isIdentifier(imported.node, { name }) && + isReactImport(value), + ); +} + +export interface ImperativeHandleMethod { + property: Property; + fn: AstNode; +} + +interface MethodState { + file: FileState; + methods: ImperativeHandleMethod[]; +} + +interface ReturnState { + file: FileState; + object: AstPath; +} + +function visit( + path: AstPath, + visitor: (path: AstPath, state: State) => boolean, + state: State, +): void { + if ( + visitor(path, state) || + isFunction(path.node) || + path.node.type === 'ClassDeclaration' || + path.node.type === 'ClassExpression' + ) + return; + for (const key of state.file.visitorKeys[path.node.type] ?? []) { + const value = path.get(key); + + for (const nested of Array.isArray(value) ? value : value ? [value] : []) { + visit(nested, visitor, state); + } + } +} + +function returnVisitor(path: AstPath, state: ReturnState): boolean { + if (path.node.type !== 'ReturnStatement') return false; + const argument = child(path, 'argument'); + + if (argument) { + const object = resolve(argument); + + if (isObjectExpression(object.node)) state.object = object; + } + + return true; +} + +function methodVisitor(path: AstPath, state: MethodState): boolean { + if (!isCallExpression(path.node)) return false; + const callee = child(path, 'callee'); + const factory = children(path, 'arguments')[1]; + + if ( + !callee || + !isReactHook(callee, 'useImperativeHandle') || + !factory || + !isFunction(factory.node) + ) + return true; + const factoryBody = child(factory, 'body'); + + if (!factoryBody) return true; + let object = resolve(factoryBody); + + if (!isObjectExpression(object.node)) { + const returnState: ReturnState = { file: state.file, object }; + + visit(factoryBody, returnVisitor, returnState); + object = returnState.object; + } + if (!isObjectExpression(object.node)) return true; + + for (const property of children(object, 'properties')) { + if (!isProperty(property.node)) continue; + const value = child(property, 'value'); + + if (!value) continue; + let fn = resolve(value); + + if (isCallExpression(fn.node)) { + const hook = child(fn, 'callee'); + const callback = children(fn, 'arguments')[0]; + + if (!hook || !isReactHook(hook, 'useCallback') || !callback) continue; + fn = resolve(callback); + } + if (isFunction(fn.node)) { + state.methods.push({ property: property.node, fn: fn.node }); + } + } + + return true; +} + +export default function findImperativeHandleMethods( + file: FileState, + component: AstPath, +): ImperativeHandleMethod[] { + const state: MethodState = { file, methods: [] }; + const body = child(component, 'body'); + + if (body) visit(body, methodVisitor, state); + + return state.methods; +} diff --git a/packages/core/src/utils/findTopLevelDefinition.ts b/packages/core/src/utils/findTopLevelDefinition.ts new file mode 100644 index 00000000000..232a89673db --- /dev/null +++ b/packages/core/src/utils/findTopLevelDefinition.ts @@ -0,0 +1,76 @@ +import { + isAssignmentExpression, + isClassDeclaration, + isFunctionDeclaration, + isExpressionStatement, + isIdentifier, + isVariableDeclaration, + isVariableDeclarator, + type AstPath, + type FileState, +} from '../internal.js'; +import getBody from './getBody.js'; + +export default function findTopLevelDefinition( + file: FileState, + name: string, +): AstPath | null { + for (const path of getBody(file)) { + if ( + (isFunctionDeclaration(path.node) || isClassDeclaration(path.node)) && + path.node.id?.name === name + ) { + return path; + } + + if (!isVariableDeclaration(path.node)) { + if (!isExpressionStatement(path.node)) { + continue; + } + + const expression = path.node.expression; + + if ( + !isAssignmentExpression(expression) || + !isIdentifier(expression.left, { name }) + ) { + continue; + } + + const expressionPath = path.get('expression'); + const rightPath = + expressionPath && !Array.isArray(expressionPath) + ? expressionPath.get('right') + : null; + + if (rightPath && !Array.isArray(rightPath)) { + return rightPath; + } + + continue; + } + + const declarations = path.get('declarations'); + + if (!Array.isArray(declarations)) { + continue; + } + + for (const declaration of declarations) { + if ( + !isVariableDeclarator(declaration.node) || + !isIdentifier(declaration.node.id, { name }) + ) { + continue; + } + + const init = declaration.get('init'); + + if (init && !Array.isArray(init)) { + return init; + } + } + } + + return null; +} diff --git a/packages/core/src/utils/getBody.ts b/packages/core/src/utils/getBody.ts new file mode 100644 index 00000000000..f903de6d9dd --- /dev/null +++ b/packages/core/src/utils/getBody.ts @@ -0,0 +1,7 @@ +import type { AstPath, FileState } from '../internal.js'; + +export default function getBody(file: FileState): AstPath[] { + const body = file.path.get('body'); + + return Array.isArray(body) ? body : []; +} diff --git a/packages/core/src/utils/getClassStaticValue.ts b/packages/core/src/utils/getClassStaticValue.ts new file mode 100644 index 00000000000..e49c0f4cc8e --- /dev/null +++ b/packages/core/src/utils/getClassStaticValue.ts @@ -0,0 +1,49 @@ +import { + isClassDeclaration, + isClassExpression, + isIdentifier, + isBlockStatement, + isMethodDefinition, + isPropertyDefinition, + isReturnStatement, + type AstNode, + type AstPath, + type FileState, +} from '../internal.js'; +import resolveValue from './resolveValue.js'; + +export default function getClassStaticValue( + file: FileState, + path: AstPath, + name: string, +): AstNode | null { + if (!isClassDeclaration(path.node) && !isClassExpression(path.node)) { + return null; + } + + for (const member of path.node.body.body) { + if ( + isPropertyDefinition(member) && + member.static && + !member.computed && + isIdentifier(member.key, { name }) + ) { + return member.value; + } + + if ( + isMethodDefinition(member) && + member.static && + member.kind === 'get' && + !member.computed && + isIdentifier(member.key, { name }) && + isBlockStatement(member.value.body) + ) { + const returned = member.value.body.body.find(isReturnStatement)?.argument; + + return returned ? resolveValue(file, returned) : null; + } + } + + return null; +} diff --git a/packages/core/src/utils/getComponentDescription.ts b/packages/core/src/utils/getComponentDescription.ts new file mode 100644 index 00000000000..a31021371e0 --- /dev/null +++ b/packages/core/src/utils/getComponentDescription.ts @@ -0,0 +1,29 @@ +import { + isProgram, + isVariableDeclaration, + type AstPath, + type FileState, +} from '../internal.js'; +import getDescription from './getDescription.js'; + +export default function getComponentDescription( + file: FileState, + path: AstPath, +): string { + for ( + let current: AstPath | null = path; + current; + current = current.parentPath + ) { + if (isVariableDeclaration(current.node)) { + return getDescription(file, current.node); + } + } + + return getDescription( + file, + path.parentPath && !isProgram(path.parentPath.node) + ? path.parentPath.node + : path.node, + ); +} diff --git a/packages/core/src/utils/getComponentName.ts b/packages/core/src/utils/getComponentName.ts new file mode 100644 index 00000000000..9359c727994 --- /dev/null +++ b/packages/core/src/utils/getComponentName.ts @@ -0,0 +1,43 @@ +import { + isAssignmentExpression, + isClassDeclaration, + isClassExpression, + isCallExpression, + isArrowFunctionExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isVariableDeclarator, + type AstPath, +} from '../internal.js'; + +export default function getComponentName(path: AstPath): string | null { + if ( + (isFunctionDeclaration(path.node) || isClassDeclaration(path.node)) && + path.node.id + ) { + return path.node.id.name; + } + + if ( + isArrowFunctionExpression(path.node) || + isFunctionExpression(path.node) || + isClassExpression(path.node) || + isCallExpression(path.node) + ) { + for (let parent = path.parentPath; parent; parent = parent.parentPath) { + if (isVariableDeclarator(parent.node) && isIdentifier(parent.node.id)) { + return parent.node.id.name; + } + + if ( + isAssignmentExpression(parent.node) && + isIdentifier(parent.node.left) + ) { + return parent.node.left.name; + } + } + } + + return null; +} diff --git a/packages/core/src/utils/getDefaultValue.ts b/packages/core/src/utils/getDefaultValue.ts new file mode 100644 index 00000000000..faadb1938a1 --- /dev/null +++ b/packages/core/src/utils/getDefaultValue.ts @@ -0,0 +1,55 @@ +import type { + AstNode, + DefaultValueDescriptor, + FileState, +} from '../internal.js'; +import { isIdentifier, isMemberExpression } from '../internal.js'; +import resolveValue, { getValueFile } from './resolveValue.js'; +import unwrapExpression from './unwrapExpression.js'; + +export default function getDefaultValue( + file: FileState, + node: AstNode, +): DefaultValueDescriptor { + const wasTypeCast = node.type === 'TypeCastExpression'; + + node = unwrapExpression(node); + if (isIdentifier(node) || isMemberExpression(node)) { + const resolved = resolveValue(file, node); + const resolvedFile = getValueFile(file, resolved); + + if ( + resolved !== node && + (wasTypeCast || resolvedFile.source.filename !== file.source.filename) + ) { + node = resolved; + file = resolvedFile; + } + } + file = getValueFile(file, node); + const range = node.range; + + if ( + !Array.isArray(range) || + typeof range[0] !== 'number' || + typeof range[1] !== 'number' + ) { + return { computed: true, value: '' }; + } + + let value = file.source.code.slice(range[0], range[1]); + + if (wasTypeCast && node.type === 'ObjectExpression') { + const closingIndent = value.match(/\n([ \t]*)}$/)?.[1]; + + if (closingIndent) { + value = value.replaceAll(`\n${closingIndent}`, '\n'); + } + } + + return { + computed: + node.type === 'CallExpression' || node.type === 'MemberExpression', + value, + }; +} diff --git a/packages/core/src/utils/getDescription.ts b/packages/core/src/utils/getDescription.ts new file mode 100644 index 00000000000..0e16440d5b9 --- /dev/null +++ b/packages/core/src/utils/getDescription.ts @@ -0,0 +1,30 @@ +import { + isProgram, + type AstNode, + type Comment, + type FileState, +} from '../internal.js'; + +export default function getDescription(file: FileState, node: AstNode): string { + if (!isProgram(file.ast) || !('range' in node)) { + return ''; + } + + const start = (node.range as readonly [number, number])[0]; + const comments = (file.ast.comments ?? []).filter( + (comment): comment is Comment => + comment.type === 'Block' && + comment.value.startsWith('*') && + comment.range[1] <= start && + /^[\s,;]*$/.test(file.source.code.slice(comment.range[1], start)), + ); + const comment = comments.at(-1); + + return comment + ? comment.value + .split('\n') + .map((line) => line.replace(/^\s*\* ?/, '')) + .join('\n') + .trim() + : ''; +} diff --git a/packages/core/src/utils/getExplicitDisplayName.ts b/packages/core/src/utils/getExplicitDisplayName.ts new file mode 100644 index 00000000000..ef0e5853cec --- /dev/null +++ b/packages/core/src/utils/getExplicitDisplayName.ts @@ -0,0 +1,41 @@ +import { + isAssignmentExpression, + isExpressionStatement, + isIdentifier, + isLiteral, + isMemberExpression, + type FileState, +} from '../internal.js'; +import getBody from './getBody.js'; + +export default function getExplicitDisplayName( + file: FileState, + componentName: string, +): number | string | null | undefined { + for (const path of getBody(file)) { + if (!isExpressionStatement(path.node)) { + continue; + } + + const assignment = path.node.expression; + + if ( + !isAssignmentExpression(assignment) || + assignment.operator !== '=' || + !isMemberExpression(assignment.left) || + assignment.left.computed || + !isIdentifier(assignment.left.object, { name: componentName }) || + !isIdentifier(assignment.left.property, { name: 'displayName' }) + ) { + continue; + } + + return isLiteral(assignment.right) && + (typeof assignment.right.value === 'string' || + typeof assignment.right.value === 'number') + ? assignment.right.value + : null; + } + + return undefined; +} diff --git a/packages/core/src/utils/getMemberName.ts b/packages/core/src/utils/getMemberName.ts new file mode 100644 index 00000000000..0a71b31d4a5 --- /dev/null +++ b/packages/core/src/utils/getMemberName.ts @@ -0,0 +1,17 @@ +import { isIdentifier, isMemberExpression, type AstNode } from '../internal.js'; + +export default function getMemberName(node: AstNode): string | null { + if (isIdentifier(node)) return node.name; + + if (!isMemberExpression(node) || node.computed) { + return null; + } + + const objectName = isIdentifier(node.object) + ? node.object.name + : getMemberName(node.object); + + return objectName && isIdentifier(node.property) + ? `${objectName}.${node.property.name}` + : null; +} diff --git a/packages/core/src/utils/getObjectProperties.ts b/packages/core/src/utils/getObjectProperties.ts new file mode 100644 index 00000000000..ff985242ae0 --- /dev/null +++ b/packages/core/src/utils/getObjectProperties.ts @@ -0,0 +1,27 @@ +import { + isObjectExpression, + isProperty, + isSpreadElement, + type FileState, + type AstNode, + type Property, +} from '../internal.js'; +import resolveValue from './resolveValue.js'; + +export default function getObjectProperties( + file: FileState, + node: AstNode, +): Property[] { + const object = resolveValue(file, node); + + if (!object || !isObjectExpression(object)) return []; + + return object.properties.flatMap((property) => { + if (isProperty(property)) return [property]; + if (isSpreadElement(property)) { + return getObjectProperties(file, property.argument); + } + + return []; + }); +} diff --git a/packages/core/src/utils/getParameterDefaults.ts b/packages/core/src/utils/getParameterDefaults.ts new file mode 100644 index 00000000000..c556bc50ed7 --- /dev/null +++ b/packages/core/src/utils/getParameterDefaults.ts @@ -0,0 +1,25 @@ +import { + isAssignmentPattern, + isIdentifier, + isProperty, + type AstNode, + type ObjectPattern, +} from '../internal.js'; + +export default function getParameterDefaults( + pattern: ObjectPattern | null, +): Map { + const defaults = new Map(); + + for (const property of pattern?.properties ?? []) { + if ( + isProperty(property) && + isIdentifier(property.key) && + isAssignmentPattern(property.value) + ) { + defaults.set(property.key.name, property.value.right); + } + } + + return defaults; +} diff --git a/packages/core/src/utils/getPropType.ts b/packages/core/src/utils/getPropType.ts new file mode 100644 index 00000000000..62d22f251f0 --- /dev/null +++ b/packages/core/src/utils/getPropType.ts @@ -0,0 +1,165 @@ +import { + isArrayExpression, + isCallExpression, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isProperty, + type AstNode, + type TypeDescriptor, +} from '../internal.js'; +import getMemberName from './getMemberName.js'; + +export interface PropTypeResult { + required: boolean; + type: TypeDescriptor; +} + +type GetDescription = (node: AstNode) => string; +type GetSource = (node: AstNode) => string; + +function getCalledPropType( + node: AstNode, + getDescription?: GetDescription, + getSource?: GetSource, +): TypeDescriptor | null { + if (!isCallExpression(node)) { + return null; + } + + const calleeName = getMemberName(node.callee); + const [argument] = node.arguments; + + if (!calleeName || !argument) { + return null; + } + + const name = calleeName.split('.').at(-1); + + if (name === 'arrayOf' || name === 'objectOf') { + const result = getPropType(argument, getDescription, getSource); + + return result ? { name, value: result.type } : null; + } + + if (name === 'instanceOf') { + return isIdentifier(argument) ? { name, value: argument.name } : null; + } + + if (name === 'oneOf' && isArrayExpression(argument)) { + return { + name: 'enum', + value: argument.elements.flatMap((element) => + element && isLiteral(element) + ? [ + { + computed: false, + value: element.raw ?? JSON.stringify(element.value), + }, + ] + : [], + ), + }; + } + + if (name === 'oneOf') { + return { + name: 'enum', + computed: true, + value: getSource?.(argument) ?? '', + }; + } + + if (name === 'oneOfType' && isArrayExpression(argument)) { + return { + name: 'union', + value: argument.elements.flatMap((element) => { + const result = element + ? getPropType(element, getDescription, getSource) + : null; + + if (!result || !element) { + return []; + } + + const description = getDescription?.(element); + + return [ + { + ...result.type, + ...(description ? { description } : {}), + }, + ]; + }), + }; + } + + if ((name === 'shape' || name === 'exact') && isObjectExpression(argument)) { + const value: Record = {}; + + for (const property of argument.properties) { + if (!isProperty(property) || !isIdentifier(property.key)) { + continue; + } + + const result = getPropType(property.value, getDescription, getSource); + + if (result) { + const description = getDescription?.(property); + + value[property.key.name] = { + ...result.type, + ...(description ? { description } : {}), + required: result.required, + }; + } + } + + return { name, value }; + } + + if (name === 'shape' || name === 'exact') { + return { + name, + computed: true, + value: getSource?.(argument) ?? '', + }; + } + + return null; +} + +export default function getPropType( + node: AstNode, + getDescription?: GetDescription, + getSource?: GetSource, +): PropTypeResult | null { + let required = false; + + if ( + isMemberExpression(node) && + !node.computed && + isIdentifier(node.property, { name: 'isRequired' }) + ) { + required = true; + node = node.object; + } + + const calledType = getCalledPropType(node, getDescription, getSource); + + if (calledType) { + return { required, type: calledType }; + } + + const name = getMemberName(node); + + if (!name?.includes('.')) { + return null; + } + + return { + required, + type: { name: name.split('.').at(-1) ?? name }, + }; +} diff --git a/packages/core/src/utils/getPropertyName.ts b/packages/core/src/utils/getPropertyName.ts new file mode 100644 index 00000000000..ec356b2bd8f --- /dev/null +++ b/packages/core/src/utils/getPropertyName.ts @@ -0,0 +1,13 @@ +import { isIdentifier, isLiteral, type AstNode } from '../internal.js'; + +export default function getPropertyName(node: AstNode): string | null { + if (isIdentifier(node)) return node.name; + if ( + isLiteral(node) && + (typeof node.value === 'string' || typeof node.value === 'number') + ) { + return String(node.value); + } + + return null; +} diff --git a/packages/core/src/utils/getResolvedEnumValues.ts b/packages/core/src/utils/getResolvedEnumValues.ts new file mode 100644 index 00000000000..657eac58f04 --- /dev/null +++ b/packages/core/src/utils/getResolvedEnumValues.ts @@ -0,0 +1,64 @@ +import { + isCallExpression, + isIdentifier, + isLiteral, + isMemberExpression, + type AstNode, + type FileState, +} from '../internal.js'; +import getMemberName from './getMemberName.js'; +import getObjectProperties from './getObjectProperties.js'; +import getPropertyName from './getPropertyName.js'; + +export default function getResolvedEnumValues( + file: FileState, + node: AstNode, +): Array<{ computed: false; value: string }> | null { + if ( + isMemberExpression(node) && + !node.computed && + isIdentifier(node.property, { name: 'isRequired' }) + ) { + return getResolvedEnumValues(file, node.object); + } + if ( + !isCallExpression(node) || + getMemberName(node.callee)?.endsWith('.oneOf') !== true + ) { + return null; + } + const [argument] = node.arguments; + + if (!argument || !isCallExpression(argument)) return null; + const operation = getMemberName(argument.callee); + const [object] = argument.arguments; + + if ( + !object || + (operation !== 'Object.keys' && operation !== 'Object.values') + ) { + return null; + } + const properties = getObjectProperties(file, object); + + if (properties.length === 0) return null; + if (operation === 'Object.keys') { + return properties.flatMap((property) => { + const name = getPropertyName(property.key); + + return name + ? [{ computed: false as const, value: JSON.stringify(name) }] + : []; + }); + } + + return properties.map((property) => ({ + computed: false, + value: + isLiteral(property.value) && + (typeof property.value.value === 'string' || + typeof property.value.value === 'number') + ? JSON.stringify(property.value.value) + : 'null', + })); +} diff --git a/packages/core/src/utils/hasComponentAnnotation.ts b/packages/core/src/utils/hasComponentAnnotation.ts new file mode 100644 index 00000000000..75525eef8f6 --- /dev/null +++ b/packages/core/src/utils/hasComponentAnnotation.ts @@ -0,0 +1,17 @@ +import { isProgram, type AstNode, type FileState } from '../internal.js'; + +export default function hasComponentAnnotation( + file: FileState, + node: AstNode, +): boolean { + if (!isProgram(file.ast) || !Array.isArray(node.range)) return false; + + const start = node.range[0]; + + return (file.ast.comments ?? []).some( + (comment) => + /(?:^|\s)@component(?:\s|$)/.test(comment.value) && + comment.range[1] <= start && + /^\s*$/.test(file.source.code.slice(comment.range[1], start)), + ); +} diff --git a/packages/core/src/utils/parseMethodDocblock.ts b/packages/core/src/utils/parseMethodDocblock.ts new file mode 100644 index 00000000000..971956c3e58 --- /dev/null +++ b/packages/core/src/utils/parseMethodDocblock.ts @@ -0,0 +1,94 @@ +import { parse } from 'comment-parser'; +import { stringify, tryParse, type RootResult } from 'jsdoc-type-pratt-parser'; +import type { TypeDescriptor } from '../internal.js'; + +export interface DocblockParam { + description?: string; + name: string; + optional: boolean; + type?: TypeDescriptor; +} + +export interface ParsedMethodDocblock { + description: string; + params: Map; + returns: { description?: string; type?: TypeDescriptor } | null; +} + +function typeDescriptor(type: RootResult): TypeDescriptor { + switch (type.type) { + case 'JsdocTypeAny': + return { name: 'mixed' }; + case 'JsdocTypeName': + return { name: type.value }; + case 'JsdocTypeGeneric': + return { + name: typeDescriptor(type.left).name, + elements: type.elements.map(typeDescriptor), + }; + case 'JsdocTypeTuple': + return { + name: 'tuple', + elements: type.elements.map((element) => + element.type === 'JsdocTypeKeyValue' + ? element.right + ? typeDescriptor(element.right) + : { name: element.key } + : typeDescriptor(element), + ), + }; + case 'JsdocTypeUnion': + return { name: 'union', elements: type.elements.map(typeDescriptor) }; + case 'JsdocTypeNotNullable': + case 'JsdocTypeNullable': + case 'JsdocTypeOptional': + case 'JsdocTypeParenthesis': + return typeDescriptor(type.element); + case 'JsdocTypeVariadic': + return type.element + ? typeDescriptor(type.element) + : { name: stringify(type) }; + default: + return { name: stringify(type) }; + } +} + +function parseType(raw: string): TypeDescriptor { + const parsed = tryParse(raw, ['typescript', 'jsdoc']); + + return parsed ? typeDescriptor(parsed) : { name: raw }; +} + +export default function parseMethodDocblock( + docblock: string, +): ParsedMethodDocblock { + const source = `/**\n${docblock + .split('\n') + .map((line) => ` * ${line}`) + .join('\n')}\n */`; + const block = parse(source)[0]; + const params = new Map(); + let returns: ParsedMethodDocblock['returns'] = null; + + for (const tag of block?.tags ?? []) { + if (tag.tag === 'param') { + const name = tag.name.replace(/^\.\.\./, ''); + + params.set(name, { + name, + optional: tag.optional || tag.type.endsWith('='), + ...(tag.type ? { type: parseType(tag.type) } : {}), + ...(tag.description ? { description: tag.description } : {}), + }); + } else if ((tag.tag === 'return' || tag.tag === 'returns') && !returns) { + const description = [tag.name, tag.description].filter(Boolean).join(' '); + + returns = { + ...(tag.type ? { type: parseType(tag.type) } : {}), + ...(description ? { description } : {}), + }; + } + } + + return { description: block?.description ?? '', params, returns }; +} diff --git a/packages/core/src/utils/resolveComponentDefinition.ts b/packages/core/src/utils/resolveComponentDefinition.ts new file mode 100644 index 00000000000..3c9c91e826c --- /dev/null +++ b/packages/core/src/utils/resolveComponentDefinition.ts @@ -0,0 +1,84 @@ +import { + isArrayExpression, + isArrowFunctionExpression, + isCallExpression, + isClassDeclaration, + isClassExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isObjectExpression, + type AstPath, + type FileState, +} from '../internal.js'; +import findTopLevelDefinition from './findTopLevelDefinition.js'; +import getMemberName from './getMemberName.js'; + +export default function resolveComponentDefinition( + file: FileState, + path: AstPath, +): AstPath | null { + if ( + path.node.type === 'ChainExpression' || + path.node.type === 'TypeCastExpression' || + path.node.type === 'TSAsExpression' || + path.node.type === 'TSNonNullExpression' || + path.node.type === 'TSSatisfiesExpression' || + path.node.type === 'TSTypeAssertion' + ) { + const expression = path.get('expression'); + + return expression && !Array.isArray(expression) + ? resolveComponentDefinition(file, expression) + : null; + } + if (isIdentifier(path.node)) { + const definition = findTopLevelDefinition(file, path.node.name); + + return definition ? resolveComponentDefinition(file, definition) : null; + } + + if ( + isFunctionDeclaration(path.node) || + isFunctionExpression(path.node) || + isArrowFunctionExpression(path.node) || + isClassDeclaration(path.node) || + isClassExpression(path.node) + ) { + return path; + } + + if (!isCallExpression(path.node)) { + return null; + } + + if ( + getMemberName(path.node.callee) === 'React.createClass' || + getMemberName(path.node.callee) === 'createReactClass' + ) { + return path; + } + + const argumentsPaths = path.get('arguments'); + + if (!Array.isArray(argumentsPaths) || argumentsPaths.length === 0) { + return null; + } + + const [first] = argumentsPaths; + + if (!first) { + return null; + } + + const useLast = + argumentsPaths.length > 1 && + (isLiteral(first.node) || + isObjectExpression(first.node) || + isArrayExpression(first.node) || + first.node.type === 'SpreadElement'); + const candidate = useLast ? argumentsPaths.at(-1) : first; + + return candidate ? resolveComponentDefinition(file, candidate) : null; +} diff --git a/packages/core/src/utils/resolveValue.ts b/packages/core/src/utils/resolveValue.ts new file mode 100644 index 00000000000..283611771a1 --- /dev/null +++ b/packages/core/src/utils/resolveValue.ts @@ -0,0 +1,419 @@ +import { + isAssignmentExpression, + isExportDefaultDeclaration, + isExportNamedDeclaration, + isExpressionStatement, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isProperty, + isVariableDeclaration, + isVariableDeclarator, + type AstNode, + type FileState, +} from '../internal.js'; +import getBody from './getBody.js'; +import getPropertyName from './getPropertyName.js'; + +const valueFiles = new WeakMap(); + +function markTree(file: FileState, node: AstNode): void { + valueFiles.set(node, file); + for (const value of Object.values(node)) { + if (Array.isArray(value)) { + for (const child of value) { + if (child && typeof child === 'object' && 'type' in child) { + markTree(file, child as AstNode); + } + } + } else if (value && typeof value === 'object' && 'type' in value) { + markTree(file, value as AstNode); + } + } +} + +function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function importSource(node: AstNode): string | null { + const source = node.source; + + return source && + typeof source === 'object' && + 'type' in source && + isLiteral(source as AstNode) && + typeof (source as AstNode & { value: unknown }).value === 'string' + ? String((source as AstNode & { value: unknown }).value) + : null; +} + +function importedBinding( + file: FileState, + localName: string, +): { file: FileState; importedName: string } | null { + for (const path of getBody(file)) { + if (path.node.type !== 'ImportDeclaration') continue; + const source = importSource(path.node); + + if (!source || (!source.startsWith('.') && !source.startsWith('/'))) + continue; + for (const specifier of nodes(path.node, 'specifiers')) { + const local = specifier.local; + + if ( + !local || + typeof local !== 'object' || + !('type' in local) || + !isIdentifier(local as AstNode, { name: localName }) + ) + continue; + const imported = specifier.imported; + const importedName = + specifier.type === 'ImportDefaultSpecifier' + ? 'default' + : specifier.type === 'ImportNamespaceSpecifier' + ? '*' + : imported && + typeof imported === 'object' && + 'type' in imported && + isIdentifier(imported as AstNode) + ? (imported as AstNode & { name: string }).name + : localName; + + try { + return { file: file.import(source), importedName }; + } catch { + return null; + } + } + } + + return null; +} + +function localValue(file: FileState, name: string): AstNode | null { + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + + if (isVariableDeclaration(declaration)) { + for (const variable of declaration.declarations) { + if ( + isVariableDeclarator(variable) && + isIdentifier(variable.id, { name }) && + variable.init + ) + return variable.init; + if ( + isVariableDeclarator(variable) && + variable.id.type === 'ObjectPattern' && + variable.init + ) { + for (const property of nodes(variable.id, 'properties')) { + if ( + !isProperty(property) || + !isIdentifier(property.value, { name }) + ) + continue; + const object = resolveValue(file, variable.init); + + if (!isObjectExpression(object)) continue; + const value = object.properties.find( + (item) => + isProperty(item) && + getPropertyName(item.key) === getPropertyName(property.key), + ); + + if (value && isProperty(value)) return value.value; + } + } + } + } + if ( + (declaration.type === 'FunctionDeclaration' || + declaration.type === 'ClassDeclaration') && + declaration.id && + typeof declaration.id === 'object' && + 'type' in declaration.id && + isIdentifier(declaration.id as AstNode, { name }) + ) + return declaration; + if ( + !isExpressionStatement(path.node) || + !isAssignmentExpression(path.node.expression) + ) + continue; + if (isIdentifier(path.node.expression.left, { name })) + return path.node.expression.right; + } + + return null; +} + +function memberValue( + file: FileState, + objectName: string, + name: string, +): AstNode | null { + for (const path of getBody(file)) { + if ( + !isExpressionStatement(path.node) || + !isAssignmentExpression(path.node.expression) + ) + continue; + const left = path.node.expression.left; + + if ( + isMemberExpression(left) && + isIdentifier(left.object, { name: objectName }) && + getPropertyName(left.property) === name + ) + return path.node.expression.right; + } + + return null; +} + +function exportedValue( + file: FileState, + name: string, + seen: Set, +): AstNode | null { + const key = `${file.source.filename}:${name}`; + + if (seen.has(key)) return null; + seen.add(key); + + for (const path of getBody(file)) { + if (isExportDefaultDeclaration(path.node) && name === 'default') { + return resolve(file, path.node.declaration, seen); + } + if (path.node.type === 'ExportAllDeclaration') { + const source = importSource(path.node); + + if (source) { + const value = exportedValue(file.import(source), name, seen); + + if (value) return value; + } + } + if (!isExportNamedDeclaration(path.node)) continue; + if (path.node.declaration) { + const declaration = path.node.declaration; + + if (isVariableDeclaration(declaration)) { + for (const variable of declaration.declarations) { + if ( + isVariableDeclarator(variable) && + isIdentifier(variable.id, { name }) && + variable.init + ) { + return resolve(file, variable.init, seen); + } + if ( + isVariableDeclarator(variable) && + variable.id.type === 'ObjectPattern' + ) { + const value = localValue(file, name); + + if (value) return resolve(file, value, seen); + } + } + } + if ( + declaration.id && + typeof declaration.id === 'object' && + 'type' in declaration.id && + isIdentifier(declaration.id as AstNode, { name }) + ) { + return declaration; + } + } + for (const specifier of nodes(path.node, 'specifiers')) { + const exported = specifier.exported; + + if ( + !exported || + typeof exported !== 'object' || + !('type' in exported) || + !isIdentifier(exported as AstNode, { name }) + ) + continue; + const local = specifier.local; + const localName = + local && + typeof local === 'object' && + 'type' in local && + isIdentifier(local as AstNode) + ? (local as AstNode & { name: string }).name + : name; + const source = importSource(path.node); + + return source + ? exportedValue(file.import(source), localName, seen) + : resolve( + file, + { type: 'Identifier', name: localName } as AstNode, + seen, + ); + } + } + + return null; +} + +function exportedMember( + file: FileState, + exportName: string, + memberName: string, + seen: Set, +): AstNode | null { + const key = `${file.source.filename}:${exportName}.${memberName}`; + + if (seen.has(key)) return null; + seen.add(key); + for (const path of getBody(file)) { + if (path.node.type === 'ExportAllDeclaration') { + const source = importSource(path.node); + + if (source) { + const value = exportedMember( + file.import(source), + exportName, + memberName, + seen, + ); + + if (value) return value; + } + } + if (!isExportNamedDeclaration(path.node)) continue; + for (const specifier of nodes(path.node, 'specifiers')) { + const exported = specifier.exported; + + if ( + !exported || + typeof exported !== 'object' || + !('type' in exported) || + !isIdentifier(exported as AstNode, { name: exportName }) + ) + continue; + const local = specifier.local; + const localName = + local && + typeof local === 'object' && + 'type' in local && + isIdentifier(local as AstNode) + ? (local as AstNode & { name: string }).name + : exportName; + const source = importSource(path.node); + + if (source) + return exportedMember(file.import(source), localName, memberName, seen); + const value = memberValue(file, localName, memberName); + + if (value) return resolve(file, value, seen); + } + } + const value = memberValue(file, exportName, memberName); + + if (value) return resolve(file, value, seen); + const exported = exportedValue(file, exportName, seen); + + if (exported && isObjectExpression(exported)) { + const property = exported.properties.find( + (item) => isProperty(item) && getPropertyName(item.key) === memberName, + ); + + if (property && isProperty(property)) + return resolve(file, property.value, seen); + } + + return null; +} + +function resolve(file: FileState, node: AstNode, seen: Set): AstNode { + markTree(file, node); + if (isIdentifier(node)) { + const imported = importedBinding(file, node.name); + + if (imported) + return exportedValue(imported.file, imported.importedName, seen) ?? node; + const value = localValue(file, node.name); + + return value ? resolve(file, value, seen) : node; + } + if ( + isMemberExpression(node) && + !node.computed && + isIdentifier(node.property) + ) { + if (isIdentifier(node.object)) { + const imported = importedBinding(file, node.object.name); + + if (imported) { + if (imported.importedName === '*') { + return exportedValue(imported.file, node.property.name, seen) ?? node; + } + const localName = + imported.importedName === 'default' + ? (() => { + for (const path of getBody(imported.file)) { + if ( + isExportDefaultDeclaration(path.node) && + isIdentifier(path.node.declaration) + ) + return path.node.declaration.name; + } + + return imported.importedName; + })() + : imported.importedName; + const value = exportedMember( + imported.file, + imported.importedName === 'default' + ? localName + : imported.importedName, + node.property.name, + seen, + ); + + return value ? resolve(imported.file, value, seen) : node; + } + const value = memberValue(file, node.object.name, node.property.name); + + if (value) return resolve(file, value, seen); + } + const object = resolve(file, node.object, seen); + + if (isObjectExpression(object)) { + const property = object.properties.find( + (item) => + isProperty(item) && getPropertyName(item.key) === node.property.name, + ); + + if (property && isProperty(property)) + return resolve(file, property.value, seen); + } + } + + return node; +} + +export default function resolveValue(file: FileState, node: AstNode): AstNode { + return resolve(file, node, new Set()); +} + +export function getValueFile(fallback: FileState, node: AstNode): FileState { + return valueFiles.get(node) ?? fallback; +} diff --git a/packages/core/src/utils/unwrapExpression.ts b/packages/core/src/utils/unwrapExpression.ts new file mode 100644 index 00000000000..b8d2b13193a --- /dev/null +++ b/packages/core/src/utils/unwrapExpression.ts @@ -0,0 +1,29 @@ +import type { AstNode } from '../internal.js'; + +const wrappers = new Set([ + 'ChainExpression', + 'TypeCastExpression', + 'TSAsExpression', + 'TSNonNullExpression', + 'TSSatisfiesExpression', + 'TSTypeAssertion', +]); + +export default function unwrapExpression(node: AstNode): AstNode { + let current = node; + + while (wrappers.has(current.type)) { + const expression = current.expression; + + if ( + !expression || + typeof expression !== 'object' || + !('type' in expression) + ) { + break; + } + current = expression as AstNode; + } + + return current; +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 00000000000..a1f3d920bb4 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "exclude": ["**/__tests__/**/*"], + "include": ["src/**/*"] +} diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts new file mode 100644 index 00000000000..af1231c7ceb --- /dev/null +++ b/packages/core/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'core', + include: ['**/__tests__/**/*-test.ts'], + coverage: { + include: ['src/**'], + provider: 'v8', + reporter: ['text', 'lcov'], + }, + }, +}); diff --git a/packages/hermes/package.json b/packages/hermes/package.json new file mode 100644 index 00000000000..36b7c1f3930 --- /dev/null +++ b/packages/hermes/package.json @@ -0,0 +1,36 @@ +{ + "name": "@react-docgen/hermes", + "version": "0.0.0", + "description": "Hermes and Flow parser adapter for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/hermes" + }, + "type": "module", + "files": [ + "dist" + ], + "engines": { + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "dependencies": { + "@react-docgen/core": "workspace:*", + "hermes-parser": "0.25.1" + }, + "devDependencies": { + "@react-docgen/babel": "workspace:*", + "@react-docgen-internal/integration-tests": "workspace:*" + }, + "license": "MIT" +} diff --git a/packages/hermes/src/__tests__/parser-test.ts b/packages/hermes/src/__tests__/parser-test.ts new file mode 100644 index 00000000000..012a9b3ed2a --- /dev/null +++ b/packages/hermes/src/__tests__/parser-test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from 'vitest'; +import parser from '../parser.js'; + +describe('parser', () => { + test('parses JavaScript and Flow syntax', () => { + const program = parser.parse({ + code: 'type Props = { label: string }; const View = (props: Props) =>
;', + filename: 'component.js', + }); + + expect(program.type).toBe('Program'); + expect(program.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: 'TypeAlias' }), + expect.objectContaining({ type: 'VariableDeclaration' }), + ]), + ); + }); + + test('reports unsupported TypeScript files', () => { + expect(() => + parser.parse({ code: 'const value: string = "x";', filename: 'file.ts' }), + ).toThrow( + expect.objectContaining({ + code: 'ERR_REACTDOCGEN_PARSER_CAPABILITY', + }), + ); + }); +}); diff --git a/packages/hermes/src/handlers/flowPropsHandler.ts b/packages/hermes/src/handlers/flowPropsHandler.ts new file mode 100644 index 00000000000..b84998021d6 --- /dev/null +++ b/packages/hermes/src/handlers/flowPropsHandler.ts @@ -0,0 +1,97 @@ +import { + getDescription, + getParameterDefaults, + isArrowFunctionExpression, + isClassDeclaration, + isClassExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isObjectPattern, + resolveComponentDefinition, + type AstNode, + type Handler, +} from '@react-docgen/core'; +import getFlowType from '../utils/getFlowType.js'; +import getPropsMembers from '../utils/getPropsMembers.js'; +import { child, nodes } from '../utils/ast.js'; + +function annotationFor(node: AstNode): AstNode | null { + const parameter = + isFunctionDeclaration(node) || + isFunctionExpression(node) || + isArrowFunctionExpression(node) + ? node.params[0] + : null; + + if (parameter) { + return child( + child(parameter, 'typeAnnotation') ?? parameter, + 'typeAnnotation', + ); + } + + if (isClassDeclaration(node) || isClassExpression(node)) { + const superTypes = child(node, 'superTypeParameters'); + const params = superTypes ? nodes(superTypes, 'params') : []; + + return params[params.length === 3 ? 1 : 0] ?? null; + } + + return null; +} + +const flowPropsHandler: Handler = (documentation, path, file) => { + const component = resolveComponentDefinition(file, path) ?? path; + const parameter = + isFunctionDeclaration(component.node) || + isFunctionExpression(component.node) || + isArrowFunctionExpression(component.node) + ? component.node.params[0] + : null; + const annotation = annotationFor(component.node); + const { composes, members, parameters } = getPropsMembers(file, annotation); + const defaults = getParameterDefaults( + parameter && isObjectPattern(parameter) ? parameter : null, + ); + + if (composes.length > 0) documentation.composes = [...new Set(composes)]; + if (members.length === 0) return; + + documentation.props ??= {}; + + for (const member of members) { + if (member.type !== 'ObjectTypeProperty') continue; + const key = child(member, 'key'); + const value = child(member, 'value'); + + if (!key || !isIdentifier(key) || !value) continue; + const flowType = getFlowType(file, value, parameters); + + if (!flowType) continue; + const defaultNode = defaults.get(key.name); + + documentation.props[key.name] = { + ...documentation.props[key.name], + description: getDescription(file, member), + flowType, + required: member.optional !== true, + ...(defaultNode && isLiteral(defaultNode) + ? { + defaultValue: { + computed: false, + value: + defaultNode.raw ?? + file.source.code.slice( + defaultNode.range[0], + defaultNode.range[1], + ), + }, + } + : {}), + }; + } +}; + +export default flowPropsHandler; diff --git a/packages/hermes/src/hermes-parser.d.ts b/packages/hermes/src/hermes-parser.d.ts new file mode 100644 index 00000000000..fe75ca8c84e --- /dev/null +++ b/packages/hermes/src/hermes-parser.d.ts @@ -0,0 +1,10 @@ +declare module 'hermes-parser' { + export interface ParserOptions { + flow: 'all' | 'detect'; + sourceType: 'module' | 'script' | 'unambiguous'; + tokens?: boolean; + } + + export const FlowVisitorKeys: Record; + export function parse(code: string, options: ParserOptions): unknown; +} diff --git a/packages/hermes/src/index.ts b/packages/hermes/src/index.ts new file mode 100644 index 00000000000..806159a0244 --- /dev/null +++ b/packages/hermes/src/index.ts @@ -0,0 +1,63 @@ +import { + componentHandler, + contextHandler, + createDocgen, + createMethodHandler, + defaultPropsHandler, + propTypesHandler, + resolveComponentDefinitions, + type ComponentDocumentation, + type Importer, + type AstNode, + type FileState, + isIdentifier, +} from '@react-docgen/core'; +import flowPropsHandler from './handlers/flowPropsHandler.js'; +import parser from './parser.js'; +import getFlowType from './utils/getFlowType.js'; +import { child, typeName } from './utils/ast.js'; + +export { + default as parser, + visitorKeys, + type ParserOptions, +} from './parser.js'; + +export interface ParseOptions { + filename?: string; + importer?: Importer; +} + +const docgen = createDocgen({ + handlers: [ + componentHandler, + propTypesHandler, + flowPropsHandler, + defaultPropsHandler, + contextHandler, + createMethodHandler((file: FileState, annotation: AstNode) => { + const type = getFlowType(file, annotation); + const unwrapped = + annotation.type === 'TypeAnnotation' + ? child(annotation, 'typeAnnotation') + : annotation; + const id = + unwrapped?.type === 'GenericTypeAnnotation' + ? child(unwrapped, 'id') + : null; + + return type?.name === 'signature' && id && isIdentifier(id) + ? { ...type, alias: typeName(id) } + : type; + }), + ], + parser, + resolver: resolveComponentDefinitions, +}); + +export function parse( + code: string, + { filename = 'component.js', importer }: ParseOptions = {}, +): ComponentDocumentation[] { + return docgen(code, { filename, importer }); +} diff --git a/packages/hermes/src/normalize.ts b/packages/hermes/src/normalize.ts new file mode 100644 index 00000000000..7c8eb4e72e8 --- /dev/null +++ b/packages/hermes/src/normalize.ts @@ -0,0 +1,43 @@ +import { isAstNode, type AstNode } from '@react-docgen/core'; + +const typeNames: Record = { + BigIntLiteral: 'Literal', + BooleanLiteral: 'Literal', + ClassProperty: 'PropertyDefinition', + NullLiteral: 'Literal', + NumericLiteral: 'Literal', + RegExpLiteral: 'Literal', + StringLiteral: 'Literal', +}; + +function normalizeValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(normalizeValue); + if (!value || typeof value !== 'object') return value; + + const input = value as Record; + const output: Record = {}; + + for (const [key, child] of Object.entries(input)) { + output[key] = normalizeValue(child); + } + + const originalType = typeof input.type === 'string' ? input.type : ''; + + output.type = typeNames[originalType] ?? originalType; + + if (output.type === 'Literal' && output.raw === undefined) { + output.raw = originalType === 'NullLiteral' ? 'null' : input.value; + } + + return output; +} + +export default function normalize(node: unknown): AstNode { + const normalized = normalizeValue(node); + + if (!isAstNode(normalized)) { + throw new TypeError('Hermes did not return an AST node.'); + } + + return normalized; +} diff --git a/packages/hermes/src/parser.ts b/packages/hermes/src/parser.ts new file mode 100644 index 00000000000..bcc60133f75 --- /dev/null +++ b/packages/hermes/src/parser.ts @@ -0,0 +1,28 @@ +import { FlowVisitorKeys, parse, type ParserOptions } from 'hermes-parser'; +import type { Parser, VisitorKeys } from '@react-docgen/core'; +import normalize from './normalize.js'; + +export const visitorKeys: VisitorKeys = FlowVisitorKeys; +export type { ParserOptions }; + +const parser: Parser = { + parse(source, options) { + if (/\.(?:cts|mts|ts|tsx)$/.test(source.filename)) { + throw Object.assign( + new Error('The Hermes adapter does not support TypeScript syntax.'), + { code: 'ERR_REACTDOCGEN_PARSER_CAPABILITY' }, + ); + } + + return normalize( + parse(source.code, { + flow: 'all', + sourceType: 'unambiguous', + ...(options as Partial | undefined), + }), + ); + }, + visitorKeys, +}; + +export default parser; diff --git a/packages/hermes/src/utils/ast.ts b/packages/hermes/src/utils/ast.ts new file mode 100644 index 00000000000..11fe1c6de48 --- /dev/null +++ b/packages/hermes/src/utils/ast.ts @@ -0,0 +1,108 @@ +import { + isExportNamedDeclaration, + isIdentifier, + isLiteral, + type AstNode, + type FileState, + getBody, +} from '@react-docgen/core'; + +export function child(node: AstNode, key: string): AstNode | null { + const value = node[key]; + + return value && typeof value === 'object' && 'type' in value + ? (value as AstNode) + : null; +} + +export function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function source(node: AstNode): string | null { + const value = child(node, 'source'); + + return value && isLiteral(value) && typeof value.value === 'string' + ? value.value + : null; +} + +export function resolveType( + file: FileState, + name: string, + seen = new Set(), +): { declaration: AstNode; file: FileState } | null { + const key = `${file.source.filename}:${name}`; + + if (seen.has(key)) return null; + seen.add(key); + + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + const id = child(declaration, 'id'); + + if ( + (declaration.type === 'TypeAlias' || + declaration.type === 'InterfaceDeclaration') && + id && + isIdentifier(id, { name }) + ) { + return { declaration, file }; + } + + if (path.node.type === 'ImportDeclaration') { + for (const specifier of nodes(path.node, 'specifiers')) { + const local = child(specifier, 'local'); + + if (!local || !isIdentifier(local, { name })) continue; + const imported = child(specifier, 'imported'); + const importedName = + specifier.type === 'ImportDefaultSpecifier' + ? 'default' + : imported && isIdentifier(imported) + ? imported.name + : name; + const specifierSource = source(path.node); + + if (!specifierSource) return null; + + try { + return resolveType(file.import(specifierSource), importedName, seen); + } catch { + return null; + } + } + } + } + + return null; +} + +export function raw(file: FileState, node: AstNode): string { + return Array.isArray(node.range) + ? file.source.code.slice(node.range[0], node.range[1]) + : ''; +} + +export function typeName(node: AstNode): string { + if (isIdentifier(node)) return node.name; + if (node.type === 'QualifiedTypeIdentifier') { + const qualification = child(node, 'qualification'); + const id = child(node, 'id'); + + return `${qualification ? typeName(qualification) : ''}${ + id && isIdentifier(id) ? id.name : '' + }`; + } + + return ''; +} diff --git a/packages/hermes/src/utils/getFlowType.ts b/packages/hermes/src/utils/getFlowType.ts new file mode 100644 index 00000000000..ade13c1f7d1 --- /dev/null +++ b/packages/hermes/src/utils/getFlowType.ts @@ -0,0 +1,387 @@ +import { + getDescription, + isIdentifier, + type AstNode, + type FileState, + type TypeDescriptor, + resolveValue, +} from '@react-docgen/core'; +import { child, nodes, raw, resolveType, typeName } from './ast.js'; + +type Parameters = Map; + +const primitiveTypes: Record = { + AnyTypeAnnotation: 'any', + BooleanTypeAnnotation: 'boolean', + EmptyTypeAnnotation: 'empty', + MixedTypeAnnotation: 'mixed', + NullLiteralTypeAnnotation: 'null', + NumberTypeAnnotation: 'number', + StringTypeAnnotation: 'string', + VoidTypeAnnotation: 'void', +}; + +function literal(file: FileState, node: AstNode): TypeDescriptor { + return { + name: 'literal', + value: raw(file, node), + }; +} + +function withRequired(type: TypeDescriptor, node: AstNode): TypeDescriptor { + return { ...type, required: node.optional !== true }; +} + +function parametersFor( + declaration: AstNode, + reference: AstNode, + inherited: Parameters, +): Parameters { + const result = new Map(inherited); + const declared = child(declaration, 'typeParameters'); + const provided = child(reference, 'typeParameters'); + const values = provided ? nodes(provided, 'params') : []; + + for (const [index, parameter] of (declared + ? nodes(declared, 'params') + : [] + ).entries()) { + const value = values[index]; + + const name = isIdentifier(parameter) + ? parameter.name + : typeof parameter.name === 'string' + ? parameter.name + : null; + + if (name && value) result.set(name, value); + } + + return result; +} + +function objectType( + file: FileState, + node: AstNode, + parameters: Parameters, + seen: WeakSet, +): TypeDescriptor { + const properties: Array> = []; + + for (const indexer of nodes(node, 'indexers')) { + const key = child(indexer, 'key'); + const value = child(indexer, 'value'); + + if (key && value) { + properties.push({ + key: resolve(file, key, parameters, seen), + value: withRequired(resolve(file, value, parameters, seen), indexer), + ...(getDescription(file, indexer) + ? { description: getDescription(file, indexer) } + : {}), + }); + } + } + + for (const property of nodes(node, 'properties')) { + if (property.type === 'ObjectTypeSpreadProperty') { + const argument = child(property, 'argument'); + const spread = argument + ? resolve(file, argument, parameters, seen) + : null; + + if ( + spread && + spread.signature && + typeof spread.signature === 'object' && + 'properties' in spread.signature && + Array.isArray(spread.signature.properties) + ) { + properties.push(...spread.signature.properties); + } + continue; + } + if (property.type !== 'ObjectTypeProperty') continue; + const key = child(property, 'key'); + const value = child(property, 'value'); + + if (!key || !value) continue; + properties.push({ + key: isIdentifier(key) ? key.name : String(key.value ?? ''), + value: withRequired(resolve(file, value, parameters, seen), property), + ...(getDescription(file, property) + ? { description: getDescription(file, property) } + : {}), + }); + } + + const descriptor: TypeDescriptor = { + name: 'signature', + type: 'object', + raw: raw(file, node), + signature: { properties }, + }; + const callProperty = nodes(node, 'callProperties')[0]; + const callValue = callProperty ? child(callProperty, 'value') : null; + + if (callValue) { + (descriptor.signature as Record)['constructor'] = resolve( + file, + callValue, + parameters, + seen, + ); + } + + return descriptor; +} + +function genericType( + file: FileState, + node: AstNode, + parameters: Parameters, + seen: WeakSet, +): TypeDescriptor { + const id = child(node, 'id'); + const name = id ? typeName(id) : 'unknown'; + const parameter = parameters.get(name); + + if (parameter) { + const parameterId = child(parameter, 'id'); + + return parameter.type === 'GenericTypeAnnotation' && + parameterId && + typeName(parameterId) === name + ? { name } + : resolve(file, parameter, parameters, seen); + } + + const resolved = name ? resolveType(file, name) : null; + + if (resolved?.declaration.type === 'TypeAlias') { + if (seen.has(resolved.declaration)) { + const [first] = nodes(child(node, 'typeParameters') ?? node, 'params'); + const firstId = + first?.type === 'GenericTypeAnnotation' ? child(first, 'id') : null; + + return firstId + ? { name: typeName(firstId) } + : first + ? resolve(file, first, new Map(), seen) + : { name }; + } + seen.add(resolved.declaration); + const type = resolve( + resolved.file, + child(resolved.declaration, 'right') ?? node, + parametersFor(resolved.declaration, node, parameters), + seen, + ); + + seen.delete(resolved.declaration); + + return type; + } + + const params = nodes(child(node, 'typeParameters') ?? node, 'params'); + + if (name === '$Keys' && params[0]?.type === 'TypeofTypeAnnotation') { + const argument = child(params[0], 'argument'); + const typeId = + argument?.type === 'GenericTypeAnnotation' + ? child(argument, 'id') + : argument; + const object = typeId ? resolveValue(file, typeId) : null; + const keys = + object?.type === 'ObjectExpression' + ? nodes(object, 'properties').flatMap((property) => { + const key = child(property, 'key'); + + return key && isIdentifier(key) ? [key.name] : []; + }) + : []; + + if (keys.length > 0) { + return { + name: 'union', + raw: raw(file, node), + elements: keys.map((value) => ({ name: 'literal', value })), + }; + } + } + + return { + name, + ...(id?.type === 'QualifiedTypeIdentifier' ? { raw: raw(file, id) } : {}), + ...(params.length > 0 + ? { + elements: params.map((item) => resolve(file, item, parameters, seen)), + raw: raw(file, node), + } + : {}), + }; +} + +function resolve( + file: FileState, + node: AstNode, + parameters: Parameters, + seen: WeakSet, +): TypeDescriptor { + if (node.type === 'TypeAnnotation') { + const annotation = child(node, 'typeAnnotation'); + + return annotation + ? resolve(file, annotation, parameters, seen) + : { name: 'unknown' }; + } + const primitive = primitiveTypes[node.type]; + + if (primitive) return { name: primitive }; + if ( + node.type === 'BooleanLiteralTypeAnnotation' || + node.type === 'NumberLiteralTypeAnnotation' || + node.type === 'StringLiteralTypeAnnotation' || + node.type === 'BigIntLiteralTypeAnnotation' + ) { + return literal(file, node); + } + + if (node.type === 'GenericTypeAnnotation') { + return genericType(file, node, parameters, seen); + } + if (node.type === 'ArrayTypeAnnotation') { + const element = child(node, 'elementType'); + + return { + name: 'Array', + elements: element ? [resolve(file, element, parameters, seen)] : [], + raw: raw(file, node), + }; + } + if ( + node.type === 'UnionTypeAnnotation' || + node.type === 'IntersectionTypeAnnotation' + ) { + return { + name: node.type === 'UnionTypeAnnotation' ? 'union' : 'intersection', + raw: raw(file, node), + elements: nodes(node, 'types').map((item) => + resolve(file, item, parameters, seen), + ), + }; + } + if (node.type === 'TupleTypeAnnotation') { + return { + name: 'tuple', + raw: raw(file, node), + elements: nodes(node, 'types').map((item) => + resolve(file, item, parameters, seen), + ), + }; + } + if (node.type === 'NullableTypeAnnotation') { + const annotation = child(node, 'typeAnnotation'); + + return { + ...(annotation + ? resolve(file, annotation, parameters, seen) + : { name: 'unknown' }), + nullable: true, + }; + } + if (node.type === 'ObjectTypeAnnotation') { + return objectType(file, node, parameters, seen); + } + if (node.type === 'FunctionTypeAnnotation') { + const returnType = child(node, 'returnType'); + const args: Array> = nodes(node, 'params').map( + (parameter) => { + const name = child(parameter, 'name'); + const annotation = child(parameter, 'typeAnnotation'); + + return { + name: name && isIdentifier(name) ? name.name : '', + ...(annotation + ? { type: resolve(file, annotation, parameters, seen) } + : {}), + }; + }, + ); + const rest = child(node, 'rest'); + + if (rest) { + const name = child(rest, 'name'); + const annotation = child(rest, 'typeAnnotation'); + + args.push({ + name: name && isIdentifier(name) ? name.name : '', + ...(annotation + ? { type: resolve(file, annotation, parameters, seen) } + : {}), + rest: true, + }); + } + + return { + name: 'signature', + type: 'function', + raw: raw(file, node), + signature: { + arguments: args, + return: returnType + ? resolve(file, returnType, parameters, seen) + : { name: 'unknown' }, + }, + }; + } + if (node.type === 'TypeofTypeAnnotation') { + const argument = child(node, 'argument'); + + if (argument && isIdentifier(argument)) return { name: argument.name }; + + return argument + ? resolve(file, argument, parameters, seen) + : { name: 'unknown' }; + } + if (node.type === 'IndexedAccessType') { + const object = child(node, 'objectType'); + const index = child(node, 'indexType'); + const objectDescriptor = object + ? resolve(file, object, parameters, seen) + : { name: 'unknown' }; + const indexType = index + ? resolve(file, index, parameters, seen) + : { name: 'unknown' }; + const properties = + objectDescriptor.signature && + typeof objectDescriptor.signature === 'object' && + 'properties' in objectDescriptor.signature && + Array.isArray(objectDescriptor.signature.properties) + ? objectDescriptor.signature.properties + : []; + const key = + typeof indexType.value === 'string' + ? indexType.value.replace(/['"]/g, '') + : indexType.name; + const property = properties.find( + (item) => item && typeof item === 'object' && item.key === key, + ) as { value?: TypeDescriptor } | undefined; + + return property?.value + ? { name: property.value.name, raw: raw(file, node) } + : { name: 'unknown' }; + } + + return { name: 'unknown' }; +} + +export default function getFlowType( + file: FileState, + annotation: AstNode | null | undefined, + parameters: Parameters = new Map(), +): TypeDescriptor | null { + return annotation + ? resolve(file, annotation, parameters, new WeakSet()) + : null; +} diff --git a/packages/hermes/src/utils/getPropsMembers.ts b/packages/hermes/src/utils/getPropsMembers.ts new file mode 100644 index 00000000000..c1cf9bb9752 --- /dev/null +++ b/packages/hermes/src/utils/getPropsMembers.ts @@ -0,0 +1,184 @@ +import { isIdentifier, type AstNode, type FileState } from '@react-docgen/core'; +import { child, nodes, resolveType, typeName } from './ast.js'; + +type Parameters = Map; + +function parametersFor( + declaration: AstNode, + reference: AstNode, + inherited: Parameters, +): Parameters { + const parameters = new Map(inherited); + const declared = child(declaration, 'typeParameters'); + const provided = child(reference, 'typeParameters'); + const values = provided ? nodes(provided, 'params') : []; + + for (const [index, parameter] of (declared + ? nodes(declared, 'params') + : [] + ).entries()) { + const value = values[index]; + + const name = isIdentifier(parameter) + ? parameter.name + : typeof parameter.name === 'string' + ? parameter.name + : null; + + if (name && value) parameters.set(name, value); + } + + return parameters; +} + +function substitute(node: AstNode, parameters: Parameters): AstNode { + if (node.type === 'GenericTypeAnnotation') { + const id = child(node, 'id'); + + if (id && isIdentifier(id) && parameters.has(id.name)) { + return parameters.get(id.name) ?? node; + } + } + + const result: Record = { ...node }; + + for (const [key, value] of Object.entries(result)) { + if (Array.isArray(value)) { + result[key] = value.map((item) => + item && typeof item === 'object' && 'type' in item + ? substitute(item as AstNode, parameters) + : item, + ); + } else if (value && typeof value === 'object' && 'type' in value) { + result[key] = substitute(value as AstNode, parameters); + } + } + + return result as AstNode; +} + +export interface PropsMembers { + composes: string[]; + members: AstNode[]; + parameters: Parameters; +} + +export default function getPropsMembers( + file: FileState, + annotation: AstNode | null, + parameters: Parameters = new Map(), + seen = new WeakSet(), +): PropsMembers { + if (!annotation) return { composes: [], members: [], parameters }; + + if (annotation.type === 'ObjectTypeAnnotation') { + const members: AstNode[] = []; + const composes: string[] = []; + + for (const property of nodes(annotation, 'properties')) { + if (property.type !== 'ObjectTypeSpreadProperty') { + members.push(substitute(property, parameters)); + continue; + } + const spread = getPropsMembers( + file, + child(property, 'argument'), + parameters, + seen, + ); + + members.push(...spread.members); + composes.push(...spread.composes); + } + + return { composes, members, parameters }; + } + + if (annotation.type === 'IntersectionTypeAnnotation') { + const results = nodes(annotation, 'types').map((type) => + getPropsMembers(file, type, parameters, seen), + ); + + return { + composes: results.flatMap(({ composes }) => composes), + members: results.flatMap(({ members }) => members), + parameters, + }; + } + + if (annotation.type !== 'GenericTypeAnnotation') { + return { composes: [], members: [], parameters }; + } + + const id = child(annotation, 'id'); + const name = id ? typeName(id) : ''; + + if (['$Exact', '$ReadOnly'].includes(name)) { + const wrapped = nodes( + child(annotation, 'typeParameters') ?? annotation, + 'params', + )[0]; + + return getPropsMembers(file, wrapped ?? null, parameters, seen); + } + + const resolved = name ? resolveType(file, name) : null; + + if (!resolved) { + return { + composes: name && !name.startsWith('React') ? [name] : [], + members: [], + parameters, + }; + } + if (seen.has(resolved.declaration)) { + return { composes: [], members: [], parameters }; + } + + seen.add(resolved.declaration); + const nextParameters = parametersFor( + resolved.declaration, + annotation, + parameters, + ); + + if (resolved.declaration.type === 'TypeAlias') { + const result = getPropsMembers( + resolved.file, + child(resolved.declaration, 'right'), + nextParameters, + seen, + ); + + seen.delete(resolved.declaration); + + return result; + } + + const inherited = nodes(resolved.declaration, 'extends').map((heritage) => { + const heritageId = child(heritage, 'id'); + + return getPropsMembers( + resolved.file, + heritageId + ? ({ + ...heritage, + type: 'GenericTypeAnnotation', + id: heritageId, + } as AstNode) + : null, + nextParameters, + seen, + ); + }); + const body = child(resolved.declaration, 'body'); + const members = [ + ...inherited.flatMap((result) => result.members), + ...(body ? nodes(body, 'properties') : []), + ].map((member) => substitute(member, nextParameters)); + const composes = inherited.flatMap((result) => result.composes); + + seen.delete(resolved.declaration); + + return { composes, members, parameters: nextParameters }; +} diff --git a/packages/hermes/tests/integration/babel-differential-test.ts b/packages/hermes/tests/integration/babel-differential-test.ts new file mode 100644 index 00000000000..d770489a0f5 --- /dev/null +++ b/packages/hermes/tests/integration/babel-differential-test.ts @@ -0,0 +1,27 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { parse as parseBabel } from '@react-docgen/babel'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { describe, expect, test } from 'vitest'; +import { parse as parseHermes } from '../../src/index.js'; + +describe('Babel differential', () => { + for (const integrationCase of loadIntegrationCases({ languages: ['js'] })) { + if (integrationCase.error) continue; + + test(integrationCase.id, () => { + const options = { + filename: integrationCase.filename, + importer(specifier: string, fromFilename: string) { + const filename = path.resolve(path.dirname(fromFilename), specifier); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; + }, + }; + + expect(parseHermes(integrationCase.source, options)).toEqual( + parseBabel(integrationCase.source, options), + ); + }); + } +}); diff --git a/packages/hermes/tests/integration/integration-test.ts b/packages/hermes/tests/integration/integration-test.ts new file mode 100644 index 00000000000..5941ad68bf4 --- /dev/null +++ b/packages/hermes/tests/integration/integration-test.ts @@ -0,0 +1,39 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { describe, expect, test } from 'vitest'; +import { parse } from '../../src/index.js'; + +describe('integration', () => { + for (const integrationCase of loadIntegrationCases({ + languages: ['flow', 'js'], + })) { + test(integrationCase.id, () => { + const run = () => + parse(integrationCase.source, { + filename: integrationCase.filename, + importer(specifier, fromFilename) { + const base = path.resolve(path.dirname(fromFilename), specifier); + const extensionless = base.replace(/\.[^./]+$/, ''); + const filename = [ + base, + `${extensionless}.js`, + `${extensionless}.jsx`, + ].find((candidate) => fs.existsSync(candidate)); + + if (!filename) throw new Error(`Cannot resolve ${specifier}.`); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; + }, + }); + + if (integrationCase.error) { + expect(run).toThrow( + expect.objectContaining({ code: integrationCase.error.code }), + ); + } else { + expect(run()).toEqual(integrationCase.output); + } + }); + } +}); diff --git a/packages/hermes/tsconfig.json b/packages/hermes/tsconfig.json new file mode 100644 index 00000000000..5a24989cd30 --- /dev/null +++ b/packages/hermes/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/packages/hermes/vitest.config.ts b/packages/hermes/vitest.config.ts new file mode 100644 index 00000000000..46f4209c233 --- /dev/null +++ b/packages/hermes/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'hermes', + include: ['**/__tests__/**/*-test.ts', '**/tests/integration/**/*-test.ts'], + }, +}); diff --git a/packages/integration-tests/AUDIT.md b/packages/integration-tests/AUDIT.md new file mode 100644 index 00000000000..a69451be0c9 --- /dev/null +++ b/packages/integration-tests/AUDIT.md @@ -0,0 +1,128 @@ +# Disabled unit-test behavior audit + +This audit maps each disabled legacy unit-test suite to its portable integration +disposition. Parameterized cases are grouped when one readable fixture exposes +the same public JSON. Invalid `NodePath` inputs and helper-only intermediate +values are internal implementation details, not public `parse()` behavior. + +Disposition vocabulary: + +- **existing integration case**: represented by a migrated golden case. +- **new integration case**: represented by a case added during this audit. +- **duplicate observable behavior**: another named case already asserts the same + public JSON or error. +- **internal-only implementation detail**: no distinct public output exists. +- **excluded custom configuration**: requires a non-default resolver, handler, + importer, or parser option. + +## Public facade and resolvers + +| Disabled suite | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `main-test.ts`, `parse-test.ts` | new integration case | `js/definitions/function-declaration`, `js/errors/missing-definition`, and `js/errors/multiple-definitions` cover default parse output and stable public errors. Parser/options validation is excluded custom configuration. | +| `FindExportedDefinitionsResolver-test.ts` | existing integration case | Definition, default/named/CommonJS export, re-export, HOC, and error cases. | +| `FindAnnotatedDefinitionsResolver-test.ts` | new integration case | `js/definitions/annotated-function`. | +| `FindAllDefinitionsResolver-test.ts` | excluded custom configuration | Public only when callers replace the default resolver. | +| `ChainResolver-test.ts` | internal-only implementation detail | Resolver composition has no independent documentation output. | +| `runResolver-test.ts` | internal-only implementation detail | Adapter for resolver return shapes; covered transitively by every case. | + +## Handlers + +| Disabled suite | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `codeTypeHandler-test.ts` | new integration case | `typescript/types/comprehensive-props`, `typescript/types/advanced-props`, and `flow/types/comprehensive-props`. | +| `componentDocblockHandler-test.ts` | existing integration case | Component descriptions across JS, Flow, TypeScript, HOCs, and imported definitions. | +| `componentMethodsHandler-test.ts` | existing integration case | JS/TypeScript class and imperative-handle method cases. | +| `componentMethodsJsDocHandler-test.ts` | new integration case | `js/methods/parameter-shapes` plus migrated `js/methods/class-method-documentation`. | +| `defaultPropsHandler-test.ts` | new integration case | Migrated static/function/default cases plus `js/defaults/spreads-and-parameters` and `typescript/defaults/function-default-parameters`. | +| `displayNameHandler-test.ts` | existing integration case | Function/class/CreateClass/forwardRef/HOC display names. Unresolvable artificial expressions are duplicate observable behavior: absent `displayName`. | +| `propDocblockHandler-test.ts` | duplicate observable behavior | Descriptions are asserted throughout JS PropTypes and typed prop cases. | +| `propTypeCompositionHandler-test.ts` | existing integration case | Flow/TypeScript intersections, interface extension, spreads, and imported types. | +| `propTypeHandler-test.ts` | new integration case | `js/props/all-proptypes`, `js/props/object-key-and-value-enums`, and migrated shape/context cases cover public validators and requiredness. Custom PropTypes aliases are excluded custom configuration. | + +## Utility suites with distinct public output + +| Disabled suite(s) | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `docblock-test.ts`, `parseJsDoc-test.ts`, `setPropDescription-test.ts` | new integration case | Documentation, prop descriptions, method descriptions, parameters, returns, and nested return docs are asserted by documentation/method/type cases. Malformed raw doctrine input is internal-only. | +| `getParameterName-test.ts`, `getMethodDocumentation-test.ts` | new integration case | `js/methods/parameter-shapes` asserts identifiers, defaults, object/array patterns, rest parameters, and JSDoc association. TypeScript parameter properties are constructor-only and do not produce public method docs. | +| `getPropType-test.ts`, `isRequiredPropType-test.ts` | new integration case | Full validator families, nested shapes, unions, enums from object keys/values, and required validators. Invalid direct helper arguments are internal-only. | +| `getFlowType-test.ts`, `flowUtilityTypes-test.ts`, `isUnreachableFlowType-test.ts`, `resolveGenericTypeAnnotations-test.ts` | existing integration case | Comprehensive props, utility types, React/DOM types, generics, intersections, spreads, interfaces, imports, and historical regressions. Unsupported/unreachable annotations have no distinct public field. | +| `getTSType-test.ts`, `unwrapBuiltinTSPropTypes-test.ts` | new integration case | Comprehensive and advanced TypeScript props cover primitives, literals, arrays, tuples, unions, intersections, objects, functions, `typeof`, `keyof`, indexed access, mapped types, qualified React types, call/index/method signatures, and built-ins. | +| `resolveObjectKeysToArray-test.ts`, `resolveObjectValuesToArray-test.ts` | new integration case | `js/props/object-key-and-value-enums`; unresolved expressions are already represented by unresolved enum behavior. | +| `printValue-test.ts`, `expressionTo-test.ts`, `getNameOrValue-test.ts` | existing integration case | Defaults, literals, enum values, computed properties, and imported/re-exported constants assert their reachable serialized forms. Invalid isolated AST kinds are internal-only. | +| `resolveToValue-test.ts`, `resolveFunctionDefinitionToReturnValue-test.ts`, `findFunctionReturn-test.ts` | existing integration case | Function components, HOCs, forwardRef/memo, default values, and imported values cover successful public resolution. Ambiguous helper states have no separate output. | +| `resolveHOC-test.ts`, `normalizeClassDefinition-test.ts`, `getTypeFromReactComponent-test.ts` | existing integration case | HOC-wrapped, custom base, PureComponent, forwardRef, memo, generic class, and polymorphic forwardRef cases. | +| `getMemberValuePath-test.ts`, `getClassMemberValuePath-test.ts`, `getMemberExpressionValuePath-test.ts`, `getPropertyValuePath-test.ts`, `getMembers-test.ts`, `getPropertyName-test.ts` | existing integration case | Static/member/default/PropTypes/computed/spread cases cover all publicly observable successful lookups. Invalid or missing members yield the already-covered absent field. | +| `resolveExportDeclaration-test.ts`, `resolveToModule-test.ts` | existing integration case | ESM, CommonJS, namespace, star, member, imported-type, and re-export chains. Importer failures beyond default filesystem behavior are excluded custom configuration. | +| `resolveObjectPatternPropertyToValue-test.ts` | new integration case | Function parameter defaults and destructured defaults. Missing properties produce the same absent default output. | + +## Predicate and structural utility suites + +These suites decide which already-covered component/export path is selected. +Their false branches do not create distinct public output, so isolated predicate +matrices would only reproduce implementation tests. + +| Disabled suites | Disposition | Corpus coverage or reason | +| --- | --- | --- | +| `isReactChildrenElementCall-test.ts`, `isReactCreateElementCall-test.ts`, `isReactCloneElementCall-test.ts` | duplicate observable behavior | React node/element PropTypes and JSX component cases. | +| `isReactForwardRefCall-test.ts`, `isReactCreateClassCall-test.ts`, `isStatelessComponent-test.ts`, `isReactComponentClass-test.ts`, `isReactComponentMethod-test.ts` | duplicate observable behavior | Existing definitions, defaults, methods, Flow, TypeScript, forwardRef, memo, and class cases. | +| `isReactBuiltinReference-test.ts`, `isReactModuleName-test.ts` | duplicate observable behavior | `React.PropTypes`, package `prop-types`, React classes, and namespace/import cases. Custom module aliases are excluded custom configuration. | +| `isDestructuringAssignment-test.ts`, `isExportsOrModuleAssignment-test.ts`, `getMemberExpressionRoot-test.ts` | duplicate observable behavior | Destructured defaults, CommonJS exports, and member/re-export cases. | +| `getTypeAnnotation-test.ts`, `getTypeParameters-test.ts` | duplicate observable behavior | Generic Flow/TypeScript, function, array, React, and imported type cases. | + +## Coverage batches + +| Batch | Cases added | Statements | Branches | Functions | Lines | +| --- | ---: | ---: | ---: | ---: | ---: | +| Migrated legacy baseline | 49 | 71.33% | 61.78% | 79.43% | 71.99% | +| First expansion: definitions, exports, errors, props, defaults, methods, TypeScript, Flow | 12 | 74.81% | 63.38% | 85.44% | 75.47% | +| Object enums, method parameter shapes, advanced TypeScript | 3 | 79.28% | 68.18% | 89.55% | 79.86% | +| Advanced Flow, value serialization, display-name resolution | 3 | 81.47% | 70.38% | 93.35% | 82.08% | +| Typed method modifiers and signatures | 1 | 81.81% | 71.21% | 93.35% | 82.44% | +| React prop wrappers, class normalization, computed keys/exports, display names | 6 | 83.35% | 73.05% | 93.35% | 83.90% | +| JSDoc variants, composed validators, imported defaults/enums | 3 | 83.85% | 73.70% | 94.62% | 84.40% | +| Nested configured HOCs and destructured bindings | 2 | 84.05% | 74.06% | 94.62% | 84.61% | + +The final default-configuration plateau is 84.05% statements, 74.06% branches, +94.62% functions, and 84.61% lines. Enforced integer floors are 84%, 74%, 94%, +and 84%, respectively. The former unit-and-integration suite reached about 92% +statements because it directly exercised custom resolvers, public helper APIs, +and synthetic invalid AST paths outside default `parse()`. + +After unit-test discovery was restored, the complete suite established the +following baseline: + +| Suite | Statements | Branches | Functions | Lines | +| --- | ---: | ---: | ---: | ---: | +| Portable integration corpus | 84.05% | 74.06% | 94.62% | 84.61% | +| Complete unit and integration suite | 95.03% | 88.78% | 98.41% | 95.45% | + +These are separate contracts. Integration coverage measures parser-portable +observable behavior through default `parse()`. Complete-suite coverage also +measures Babel-specific internals, extension helpers, custom resolvers, and +synthetic invalid AST states. The integration thresholds therefore remain based +on the portable corpus rather than the complete-suite percentages. + +## Remaining audit + +Remaining uncovered regions were checked against default `parse()` reachability. +Valid final exclusions are: + +1. False/error branches of internal AST helpers whose public result duplicates + an absent documentation field. +2. Custom resolver, handler, importer, and parser-option paths excluded from the + default parse corpus. +3. Parser-version-specific syntax/error behavior excluded from parser-neutral + goldens. +4. Defensive branches requiring invalid or manually constructed Babel paths, + unreachable through public parsing. + +The largest excluded regions are `FindAllDefinitionsResolver`, which requires a +custom resolver; `expressionTo` object/array serialization, exposed as a direct +helper API; invalid-input branches in `getNameOrValue`; and internal resolution +states that only unit tests can construct. The final HOC/destructuring batch +added only 0.20 statement points, and the destructuring helper remained +unchanged, confirming diminishing default-flow coverage. + +No production source or coverage-directive comment was added. diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_18.js b/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_18.js rename to packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/index.js diff --git a/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json b/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json new file mode 100644 index 00000000000..c4240f01f9b --- /dev/null +++ b/packages/integration-tests/cases/flow/defaults/forward-ref-proptypes/output.json @@ -0,0 +1,31 @@ +[ + { + "description": "", + "displayName": "UncoloredView", + "methods": [], + "props": { + "color": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "flowType": { + "name": "string", + "nullable": true + } + }, + "id": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'test-forward-ref-default'", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_14.js b/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_14.js rename to packages/integration-tests/cases/flow/definitions/forward-ref-display-name/index.js diff --git a/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json b/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json new file mode 100644 index 00000000000..1e04e72a3cc --- /dev/null +++ b/packages/integration-tests/cases/flow/definitions/forward-ref-display-name/output.json @@ -0,0 +1,17 @@ +[ + { + "description": "", + "displayName": "UncoloredView", + "methods": [], + "props": { + "color": { + "required": false, + "flowType": { + "name": "string", + "nullable": true + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_19.js b/packages/integration-tests/cases/flow/definitions/pure-component/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_19.js rename to packages/integration-tests/cases/flow/definitions/pure-component/index.js diff --git a/packages/integration-tests/cases/flow/definitions/pure-component/output.json b/packages/integration-tests/cases/flow/definitions/pure-component/output.json new file mode 100644 index 00000000000..73bd29e3f85 --- /dev/null +++ b/packages/integration-tests/cases/flow/definitions/pure-component/output.json @@ -0,0 +1,22 @@ +[ + { + "description": "", + "displayName": "Component", + "methods": [], + "props": { + "data": { + "required": false, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "mixed" + } + ], + "raw": "Array" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/flow-export-type.js b/packages/integration-tests/cases/flow/exports/exported-type/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/flow-export-type.js rename to packages/integration-tests/cases/flow/exports/exported-type/index.js diff --git a/packages/integration-tests/cases/flow/exports/exported-type/output.json b/packages/integration-tests/cases/flow/exports/exported-type/output.json new file mode 100644 index 00000000000..f9ded0fe001 --- /dev/null +++ b/packages/integration-tests/cases/flow/exports/exported-type/output.json @@ -0,0 +1,55 @@ +[ + { + "description": "This is a Flow class component", + "displayName": "FlowComponent", + "methods": [ + { + "name": "foo", + "docblock": null, + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + } + }, + { + "name": "bar", + "docblock": null, + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + } + } + ], + "props": { + "foo": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js b/packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js new file mode 100644 index 00000000000..ad227ba6897 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/imported-type/flow-export-type.js @@ -0,0 +1,26 @@ +/** + * @flow + */ + +import React, { Component } from 'react'; + +export type Props = { + foo: string +} + +/** + * This is a Flow class component + */ +export default class FlowComponent extends Component { + render() { + return

Hello world

; + } + + foo(a: string): string { + return a; + } + + bar(a: string): string { + return a; + } +} diff --git a/packages/react-docgen/tests/integration/__fixtures__/flow-import-type.js b/packages/integration-tests/cases/flow/imports/imported-type/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/flow-import-type.js rename to packages/integration-tests/cases/flow/imports/imported-type/index.js diff --git a/packages/integration-tests/cases/flow/imports/imported-type/output.json b/packages/integration-tests/cases/flow/imports/imported-type/output.json new file mode 100644 index 00000000000..db120def951 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/imported-type/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "This is a Flow component with imported prop types", + "displayName": "ImportedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js new file mode 100644 index 00000000000..ad227ba6897 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-export-type.js @@ -0,0 +1,26 @@ +/** + * @flow + */ + +import React, { Component } from 'react'; + +export type Props = { + foo: string +} + +/** + * This is a Flow class component + */ +export default class FlowComponent extends Component { + render() { + return

Hello world

; + } + + foo(a: string): string { + return a; + } + + bar(a: string): string { + return a; + } +} diff --git a/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js new file mode 100644 index 00000000000..c5a4dfec45e --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/spread-imported-type/flow-import-type.js @@ -0,0 +1,18 @@ +/** + * @flow + */ + +import React, { Component } from 'react'; +import type { Props as ImportedProps } from './flow-export-type.js'; + +export type ExtendedProps = { + ...ImportedProps, + bar: number +} + +/** + * This is a Flow component with imported prop types + */ +export function ImportedComponent(props: ImportedProps) { + return

Hello world

; +} diff --git a/packages/react-docgen/tests/integration/__fixtures__/flow-spread-import-type.js b/packages/integration-tests/cases/flow/imports/spread-imported-type/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/flow-spread-import-type.js rename to packages/integration-tests/cases/flow/imports/spread-imported-type/index.js diff --git a/packages/integration-tests/cases/flow/imports/spread-imported-type/output.json b/packages/integration-tests/cases/flow/imports/spread-imported-type/output.json new file mode 100644 index 00000000000..71a7b67c365 --- /dev/null +++ b/packages/integration-tests/cases/flow/imports/spread-imported-type/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "This is a Flow component with imported prop types", + "displayName": "ImportedExtendedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + }, + "bar": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_32.js b/packages/integration-tests/cases/flow/methods/generic-class/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_32.js rename to packages/integration-tests/cases/flow/methods/generic-class/index.js diff --git a/packages/integration-tests/cases/flow/methods/generic-class/output.json b/packages/integration-tests/cases/flow/methods/generic-class/output.json new file mode 100644 index 00000000000..dea2d495bd1 --- /dev/null +++ b/packages/integration-tests/cases/flow/methods/generic-class/output.json @@ -0,0 +1,58 @@ +[ + { + "description": "", + "displayName": "Segments", + "methods": [ + { + "name": "foo", + "docblock": null, + "modifiers": [], + "params": [ + { + "name": "props", + "optional": false, + "type": { + "name": "signature", + "type": "object", + "raw": "{\n segments: Array,\n}", + "signature": { + "properties": [ + { + "key": "segments", + "value": { + "name": "Array", + "elements": [ + { + "name": "T" + } + ], + "raw": "Array", + "required": true + } + } + ] + }, + "alias": "Props" + } + } + ], + "returns": null + } + ], + "props": { + "segments": { + "required": true, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "T" + } + ], + "raw": "Array" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js new file mode 100644 index 00000000000..b84833215be --- /dev/null +++ b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/index.js @@ -0,0 +1,10 @@ +import * as React from 'react'; + +export const Input = React.forwardRef((_, ref) => { + const focus = React.useCallback((value: string): number => 1, []); + React.useImperativeHandle(ref, () => ({ + /** Focus the input. */ + focus, + })); + return ; +}); diff --git a/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json new file mode 100644 index 00000000000..3c179d48ab4 --- /dev/null +++ b/packages/integration-tests/cases/flow/methods/imperative-handle-callbacks/output.json @@ -0,0 +1,28 @@ +[ + { + "description": "", + "displayName": "Input", + "methods": [ + { + "name": "focus", + "docblock": "Focus the input.", + "modifiers": [], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "number" + } + }, + "description": "Focus the input." + } + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_12.js b/packages/integration-tests/cases/flow/regressions/material-ui-paper/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_12.js rename to packages/integration-tests/cases/flow/regressions/material-ui-paper/index.js diff --git a/packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json b/packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json new file mode 100644 index 00000000000..9cfbc990998 --- /dev/null +++ b/packages/integration-tests/cases/flow/regressions/material-ui-paper/output.json @@ -0,0 +1,180 @@ +[ + { + "description": "", + "displayName": "Paper", + "methods": [], + "props": { + "classes": { + "required": false, + "flowType": { + "name": "Object" + }, + "description": "Useful to extend the style applied to components." + }, + "anchorOrigin": { + "required": false, + "flowType": { + "name": "signature", + "type": "object", + "raw": "{\n horizontal: 'left' | 'center' | 'right' | number,\n vertical: 'top' | 'center' | 'bottom' | number,\n}", + "signature": { + "properties": [ + { + "key": "horizontal", + "value": { + "name": "union", + "raw": "'left' | 'center' | 'right' | number", + "elements": [ + { + "name": "literal", + "value": "'left'" + }, + { + "name": "literal", + "value": "'center'" + }, + { + "name": "literal", + "value": "'right'" + }, + { + "name": "number" + } + ], + "required": true + } + }, + { + "key": "vertical", + "value": { + "name": "union", + "raw": "'top' | 'center' | 'bottom' | number", + "elements": [ + { + "name": "literal", + "value": "'top'" + }, + { + "name": "literal", + "value": "'center'" + }, + { + "name": "literal", + "value": "'bottom'" + }, + { + "name": "number" + } + ], + "required": true + } + } + ] + } + }, + "description": "This is the point on the anchor where the popover's\n`anchorEl` will attach to. This is not used when the\nanchorReference is 'anchorPosition'.\n\nOptions:\nvertical: [top, center, bottom];\nhorizontal: [left, center, right].", + "defaultValue": { + "value": "{\n vertical: 'top',\n horizontal: 'left',\n}", + "computed": false + } + }, + "children": { + "required": false, + "flowType": { + "name": "Node" + }, + "description": "@ignore" + }, + "component": { + "required": false, + "flowType": { + "name": "ElementType" + }, + "description": "The component used for the root node.\nThis currently has to be flow cast in defaultProps as of flow 0.59.0", + "defaultValue": { + "value": "'div'", + "computed": false + } + }, + "elevation": { + "required": false, + "flowType": { + "name": "number" + }, + "description": "Shadow depth, corresponds to `dp` in the spec.\nIt's accepting values between 0 and 24 inclusive.", + "defaultValue": { + "value": "2", + "computed": false + } + }, + "labelRowsPerPage": { + "required": false, + "flowType": { + "name": "Node" + }, + "description": "Useful to customize the rows per page label. Invoked with a `{ from, to, count, page }`\nobject.", + "defaultValue": { + "value": "'Rows per page:'", + "computed": false + } + }, + "transition": { + "required": true, + "flowType": { + "name": "ComponentType", + "elements": [ + { + "name": "unknown" + } + ], + "raw": "ComponentType<*>" + }, + "description": "Transition component." + }, + "timeout": { + "required": false, + "flowType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "The duration for the transition, in milliseconds.\nYou may specify a single timeout for all transitions, or individually with an object.\n\nSet to 'auto' to automatically calculate transition time based on height.", + "defaultValue": { + "value": "300", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/flow/types/advanced-props/index.js b/packages/integration-tests/cases/flow/types/advanced-props/index.js new file mode 100644 index 00000000000..a9dd058288f --- /dev/null +++ b/packages/integration-tests/cases/flow/types/advanced-props/index.js @@ -0,0 +1,38 @@ +// @flow + +type NamedFunction = ( + count: number, + label: ?string, + ...rest: Array +) => boolean; + +type Callable = { + (value: string): number, + /** Values stored by key. */ + [key: string]: number, + token: 'a' | 'b', +}; + +const sizes = { small: 's', large: 'l' }; +type Shape = { left: string, right: number }; + +type Props = { + namedFunction: NamedFunction, + unnamedFunction: (number, ?string) => boolean, + singleFunction: string => boolean, + callable: Callable, + tupleUnion: [string, number] | [number, string], + intersection: { left: string } & { right: number }, + classType: Class, + optionalArray?: string[], + keys: $Keys, + qualified: React.Node, + objectType: typeof sizes, + indexed: Shape['left'], + missingIndex: Shape['missing'], +}; + +/** Exercises advanced Flow prop type extraction. */ +export function AdvancedFlowTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/flow/types/advanced-props/output.json b/packages/integration-tests/cases/flow/types/advanced-props/output.json new file mode 100644 index 00000000000..a76c8d9d0d6 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/advanced-props/output.json @@ -0,0 +1,311 @@ +[ + { + "description": "Exercises advanced Flow prop type extraction.", + "displayName": "AdvancedFlowTypes", + "methods": [], + "props": { + "namedFunction": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "(\n count: number,\n label: ?string,\n ...rest: Array\n) => boolean", + "signature": { + "arguments": [ + { + "name": "count", + "type": { + "name": "number" + } + }, + { + "name": "label", + "type": { + "name": "string", + "nullable": true + } + }, + { + "name": "rest", + "type": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "Array" + }, + "rest": true + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "unnamedFunction": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "(number, ?string) => boolean", + "signature": { + "arguments": [ + { + "name": "", + "type": { + "name": "number" + } + }, + { + "name": "", + "type": { + "name": "string", + "nullable": true + } + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "singleFunction": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "string => boolean", + "signature": { + "arguments": [ + { + "name": "", + "type": { + "name": "string" + } + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "callable": { + "required": true, + "flowType": { + "name": "signature", + "type": "object", + "raw": "{\n (value: string): number,\n /** Values stored by key. */\n [key: string]: number,\n token: 'a' | 'b',\n}", + "signature": { + "properties": [ + { + "key": { + "name": "string" + }, + "value": { + "name": "number", + "required": true + }, + "description": "Values stored by key." + }, + { + "key": "token", + "value": { + "name": "union", + "raw": "'a' | 'b'", + "elements": [ + { + "name": "literal", + "value": "'a'" + }, + { + "name": "literal", + "value": "'b'" + } + ], + "required": true + } + } + ], + "constructor": { + "name": "signature", + "type": "function", + "raw": "(value: string): number", + "signature": { + "arguments": [ + { + "name": "value", + "type": { + "name": "string" + } + } + ], + "return": { + "name": "number" + } + } + } + } + }, + "description": "" + }, + "tupleUnion": { + "required": true, + "flowType": { + "name": "union", + "raw": "[string, number] | [number, string]", + "elements": [ + { + "name": "tuple", + "raw": "[string, number]", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + { + "name": "tuple", + "raw": "[number, string]", + "elements": [ + { + "name": "number" + }, + { + "name": "string" + } + ] + } + ] + }, + "description": "" + }, + "intersection": { + "required": true, + "flowType": { + "name": "intersection", + "raw": "{ left: string } & { right: number }", + "elements": [ + { + "name": "signature", + "type": "object", + "raw": "{ left: string }", + "signature": { + "properties": [ + { + "key": "left", + "value": { + "name": "string", + "required": true + } + } + ] + } + }, + { + "name": "signature", + "type": "object", + "raw": "{ right: number }", + "signature": { + "properties": [ + { + "key": "right", + "value": { + "name": "number", + "required": true + } + } + ] + } + } + ] + }, + "description": "" + }, + "classType": { + "required": true, + "flowType": { + "name": "Class", + "elements": [ + { + "name": "boolean" + } + ], + "raw": "Class" + }, + "description": "" + }, + "optionalArray": { + "required": false, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "string[]" + }, + "description": "" + }, + "keys": { + "required": true, + "flowType": { + "name": "union", + "raw": "$Keys", + "elements": [ + { + "name": "literal", + "value": "small" + }, + { + "name": "literal", + "value": "large" + } + ] + }, + "description": "" + }, + "qualified": { + "required": true, + "flowType": { + "name": "ReactNode", + "raw": "React.Node" + }, + "description": "" + }, + "objectType": { + "required": true, + "flowType": { + "name": "sizes" + }, + "description": "" + }, + "indexed": { + "required": true, + "flowType": { + "name": "string", + "raw": "Shape['left']" + }, + "description": "" + }, + "missingIndex": { + "required": true, + "flowType": { + "name": "unknown" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/flow/types/comprehensive-props/index.js b/packages/integration-tests/cases/flow/types/comprehensive-props/index.js new file mode 100644 index 00000000000..57962999404 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/comprehensive-props/index.js @@ -0,0 +1,22 @@ +// @flow + +type Props = { + anything: any, + mixedValue: mixed, + text: string, + count: number, + enabled: boolean, + literal: 'small', + union: string | number, + maybe: ?string, + list: Array, + pair: [string, number], + callback: (value: string) => boolean, + nested: { value?: string }, + optional?: string, +}; + +/** Exercises Flow prop type extraction. */ +export function FlowTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/flow/types/comprehensive-props/output.json b/packages/integration-tests/cases/flow/types/comprehensive-props/output.json new file mode 100644 index 00000000000..2e6967075ef --- /dev/null +++ b/packages/integration-tests/cases/flow/types/comprehensive-props/output.json @@ -0,0 +1,154 @@ +[ + { + "description": "Exercises Flow prop type extraction.", + "displayName": "FlowTypes", + "methods": [], + "props": { + "anything": { + "required": true, + "flowType": { + "name": "any" + }, + "description": "" + }, + "mixedValue": { + "required": true, + "flowType": { + "name": "mixed" + }, + "description": "" + }, + "text": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + }, + "count": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "" + }, + "enabled": { + "required": true, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "literal": { + "required": true, + "flowType": { + "name": "literal", + "value": "'small'" + }, + "description": "" + }, + "union": { + "required": true, + "flowType": { + "name": "union", + "raw": "string | number", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "maybe": { + "required": true, + "flowType": { + "name": "string", + "nullable": true + }, + "description": "" + }, + "list": { + "required": true, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "Array" + }, + "description": "" + }, + "pair": { + "required": true, + "flowType": { + "name": "tuple", + "raw": "[string, number]", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "callback": { + "required": true, + "flowType": { + "name": "signature", + "type": "function", + "raw": "(value: string) => boolean", + "signature": { + "arguments": [ + { + "name": "value", + "type": { + "name": "string" + } + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "nested": { + "required": true, + "flowType": { + "name": "signature", + "type": "object", + "raw": "{ value?: string }", + "signature": { + "properties": [ + { + "key": "value", + "value": { + "name": "string", + "required": false + } + } + ] + } + }, + "description": "" + }, + "optional": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_30.js b/packages/integration-tests/cases/flow/types/concrete-identity/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_30.js rename to packages/integration-tests/cases/flow/types/concrete-identity/index.js diff --git a/packages/integration-tests/cases/flow/types/concrete-identity/output.json b/packages/integration-tests/cases/flow/types/concrete-identity/output.json new file mode 100644 index 00000000000..b92b17a999f --- /dev/null +++ b/packages/integration-tests/cases/flow/types/concrete-identity/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "prop": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_29.js b/packages/integration-tests/cases/flow/types/generic-identity/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_29.js rename to packages/integration-tests/cases/flow/types/generic-identity/index.js diff --git a/packages/integration-tests/cases/flow/types/generic-identity/output.json b/packages/integration-tests/cases/flow/types/generic-identity/output.json new file mode 100644 index 00000000000..c7bcd68f975 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/generic-identity/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "prop": { + "required": true, + "flowType": { + "name": "T" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_26.js b/packages/integration-tests/cases/flow/types/generic-interface-extension/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_26.js rename to packages/integration-tests/cases/flow/types/generic-interface-extension/index.js diff --git a/packages/integration-tests/cases/flow/types/generic-interface-extension/output.json b/packages/integration-tests/cases/flow/types/generic-interface-extension/output.json new file mode 100644 index 00000000000..dc0f311c387 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/generic-interface-extension/output.json @@ -0,0 +1,36 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "FlowComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "flowType": { + "name": "Child" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "flowType": { + "name": "Array", + "elements": [ + { + "name": "Child" + } + ], + "raw": "Array" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "Complex union prop" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_24.js b/packages/integration-tests/cases/flow/types/interface-composition/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_24.js rename to packages/integration-tests/cases/flow/types/interface-composition/index.js diff --git a/packages/integration-tests/cases/flow/types/interface-composition/output.json b/packages/integration-tests/cases/flow/types/interface-composition/output.json new file mode 100644 index 00000000000..efbabd70045 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/interface-composition/output.json @@ -0,0 +1,66 @@ +[ + { + "description": "This is a flow class component with an interface as props", + "displayName": "FlowComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "flowType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "Complex union prop" + } + }, + "composes": [ + "OtherProps" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_11.js b/packages/integration-tests/cases/flow/types/intersection-composition/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_11.js rename to packages/integration-tests/cases/flow/types/intersection-composition/index.js diff --git a/packages/integration-tests/cases/flow/types/intersection-composition/output.json b/packages/integration-tests/cases/flow/types/intersection-composition/output.json new file mode 100644 index 00000000000..97919102046 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/intersection-composition/output.json @@ -0,0 +1,33 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "fooProp": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "fooProp is spread in from a locally resolved type" + }, + "prop1": { + "required": true, + "flowType": { + "name": "string" + }, + "description": "The first prop" + }, + "prop2": { + "required": true, + "flowType": { + "name": "number" + }, + "description": "The second, covariant prop" + } + }, + "composes": [ + "OtherProps" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_31.js b/packages/integration-tests/cases/flow/types/nested-generic-identity/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_31.js rename to packages/integration-tests/cases/flow/types/nested-generic-identity/index.js diff --git a/packages/integration-tests/cases/flow/types/nested-generic-identity/output.json b/packages/integration-tests/cases/flow/types/nested-generic-identity/output.json new file mode 100644 index 00000000000..c7bcd68f975 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/nested-generic-identity/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "prop": { + "required": true, + "flowType": { + "name": "T" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_13.js b/packages/integration-tests/cases/flow/types/react-and-dom-types/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_13.js rename to packages/integration-tests/cases/flow/types/react-and-dom-types/index.js diff --git a/packages/integration-tests/cases/flow/types/react-and-dom-types/output.json b/packages/integration-tests/cases/flow/types/react-and-dom-types/output.json new file mode 100644 index 00000000000..6e0869ec511 --- /dev/null +++ b/packages/integration-tests/cases/flow/types/react-and-dom-types/output.json @@ -0,0 +1,254 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "align": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"left\" | \"center\" | \"right\" | \"justify\"", + "elements": [ + { + "name": "literal", + "value": "\"left\"" + }, + { + "name": "literal", + "value": "\"center\"" + }, + { + "name": "literal", + "value": "\"right\"" + }, + { + "name": "literal", + "value": "\"justify\"" + } + ] + }, + "description": "" + }, + "left": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "center": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "right": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "justify": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "transform": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"lowercase\" | \"uppercase\" | \"capitalize\"", + "elements": [ + { + "name": "literal", + "value": "\"lowercase\"" + }, + { + "name": "literal", + "value": "\"uppercase\"" + }, + { + "name": "literal", + "value": "\"capitalize\"" + } + ] + }, + "description": "" + }, + "lowercase": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "uppercase": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "capitalize": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "tracking": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"tight\" | \"normal\" | \"wide\"", + "elements": [ + { + "name": "literal", + "value": "\"tight\"" + }, + { + "name": "literal", + "value": "\"normal\"" + }, + { + "name": "literal", + "value": "\"wide\"" + } + ] + }, + "description": "" + }, + "trackingTight": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "trackingNormal": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "trackingWide": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leading": { + "required": false, + "flowType": { + "name": "union", + "raw": "\"none\" | \"tight\" | \"normal\" | \"loose\"", + "elements": [ + { + "name": "literal", + "value": "\"none\"" + }, + { + "name": "literal", + "value": "\"tight\"" + }, + { + "name": "literal", + "value": "\"normal\"" + }, + { + "name": "literal", + "value": "\"loose\"" + } + ] + }, + "description": "" + }, + "leadingNone": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leadingTight": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leadingNormal": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "leadingLoose": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "children": { + "required": false, + "flowType": { + "name": "ReactNode", + "raw": "React.Node" + }, + "description": "" + }, + "className": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + }, + "RootComponent": { + "required": false, + "flowType": { + "name": "ReactElementType", + "raw": "React.ElementType" + }, + "description": "" + }, + "color": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + }, + "size": { + "required": false, + "flowType": { + "name": "string" + }, + "description": "" + }, + "wrap": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + }, + "muted": { + "required": false, + "flowType": { + "name": "boolean" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_15.js b/packages/integration-tests/cases/flow/types/spread-composition/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_15.js rename to packages/integration-tests/cases/flow/types/spread-composition/index.js diff --git a/packages/integration-tests/cases/flow/types/spread-composition/output.json b/packages/integration-tests/cases/flow/types/spread-composition/output.json new file mode 100644 index 00000000000..47f379e543d --- /dev/null +++ b/packages/integration-tests/cases/flow/types/spread-composition/output.json @@ -0,0 +1,62 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "other": { + "required": true, + "flowType": { + "name": "literal", + "value": "'a'" + }, + "description": "" + }, + "other2": { + "required": true, + "flowType": { + "name": "literal", + "value": "'b'" + }, + "description": "" + }, + "other3": { + "required": true, + "flowType": { + "name": "literal", + "value": "'c'" + }, + "description": "" + }, + "other4": { + "required": true, + "flowType": { + "name": "literal", + "value": "'g'" + }, + "description": "" + }, + "other5": { + "required": true, + "flowType": { + "name": "literal", + "value": "'f'" + }, + "description": "" + }, + "somePropOverride": { + "required": true, + "flowType": { + "name": "literal", + "value": "'baz'" + }, + "description": "" + } + }, + "composes": [ + "BarProps", + "BarProps2", + "BarProps3" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_20.js b/packages/integration-tests/cases/js/defaults/computed-property/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_20.js rename to packages/integration-tests/cases/js/defaults/computed-property/index.js diff --git a/packages/integration-tests/cases/js/defaults/computed-property/output.json b/packages/integration-tests/cases/js/defaults/computed-property/output.json new file mode 100644 index 00000000000..24a099af70c --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/computed-property/output.json @@ -0,0 +1,20 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "@computed#children": { + "type": { + "name": "string" + }, + "required": false, + "description": "This is a test", + "defaultValue": { + "value": "\"default\"", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx b/packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx new file mode 100644 index 00000000000..1ddd851740c --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/destructured-bindings/index.jsx @@ -0,0 +1,24 @@ +import PropTypes from 'prop-types'; + +const source = { + label: 'from-variable-pattern', + count: 7, +}; +const { label } = source; +let count; + +({ count } = source); + +export default function DestructuredBindings() { + return
; +} + +DestructuredBindings.propTypes = { + label: PropTypes.string, + count: PropTypes.number, +}; + +DestructuredBindings.defaultProps = { + label, + count, +}; diff --git a/packages/integration-tests/cases/js/defaults/destructured-bindings/output.json b/packages/integration-tests/cases/js/defaults/destructured-bindings/output.json new file mode 100644 index 00000000000..1a825c14026 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/destructured-bindings/output.json @@ -0,0 +1,31 @@ +[ + { + "description": "", + "displayName": "DestructuredBindings", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "label", + "computed": false + } + }, + "count": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "count", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_16.js b/packages/integration-tests/cases/js/defaults/function-default-props/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_16.js rename to packages/integration-tests/cases/js/defaults/function-default-props/index.js diff --git a/packages/integration-tests/cases/js/defaults/function-default-props/output.json b/packages/integration-tests/cases/js/defaults/function-default-props/output.json new file mode 100644 index 00000000000..2d02536f9f5 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/function-default-props/output.json @@ -0,0 +1,21 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "bar": { + "type": { + "name": "custom", + "raw": "PropTypes.node" + }, + "required": false, + "description": "This does something.", + "defaultValue": { + "value": "null", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_42.js b/packages/integration-tests/cases/js/defaults/memo-forward-ref/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_42.js rename to packages/integration-tests/cases/js/defaults/memo-forward-ref/index.js diff --git a/packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json b/packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json new file mode 100644 index 00000000000..f38f6d016a3 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/memo-forward-ref/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "foo": { + "defaultValue": { + "value": "'bar'", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx new file mode 100644 index 00000000000..29494fb2cac --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/index.jsx @@ -0,0 +1,20 @@ +import PropTypes from 'prop-types'; + +const sharedDefaults = { + theme: 'light', +}; + +export function Button({ label = 'Fallback', size = 1 }) { + return ; +} + +Button.propTypes = { + label: PropTypes.string, + size: PropTypes.number, + theme: PropTypes.string, +}; + +Button.defaultProps = { + ...sharedDefaults, + label: 'Save', +}; diff --git a/packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json new file mode 100644 index 00000000000..01311d49c9c --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/spreads-and-parameters/output.json @@ -0,0 +1,42 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'Save'", + "computed": false + } + }, + "size": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "1", + "computed": false + } + }, + "theme": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'light'", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_40.js b/packages/integration-tests/cases/js/defaults/unresolved-enum/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_40.js rename to packages/integration-tests/cases/js/defaults/unresolved-enum/index.js diff --git a/packages/integration-tests/cases/js/defaults/unresolved-enum/output.json b/packages/integration-tests/cases/js/defaults/unresolved-enum/output.json new file mode 100644 index 00000000000..3500b1a1fa4 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/unresolved-enum/output.json @@ -0,0 +1,22 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "size": { + "type": { + "name": "enum", + "computed": true, + "value": "Object.values(Sizes)" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "Sizes.EXTRA_LARGE", + "computed": true + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/defaults/value-serialization/index.jsx b/packages/integration-tests/cases/js/defaults/value-serialization/index.jsx new file mode 100644 index 00000000000..c277442ebe7 --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/value-serialization/index.jsx @@ -0,0 +1,37 @@ +import PropTypes from 'prop-types'; + +const shared = { + spreadValue: 'shared', +}; + +export default function ValueSerialization() { + return
; +} + +ValueSerialization.propTypes = { + text: PropTypes.string, + count: PropTypes.number, + disabled: PropTypes.bool, + empty: PropTypes.any, + pattern: PropTypes.instanceOf(RegExp), + big: PropTypes.any, + list: PropTypes.array, + object: PropTypes.object, + member: PropTypes.any, + called: PropTypes.any, + spreadValue: PropTypes.string, +}; + +ValueSerialization.defaultProps = { + text: 'value', + count: -2, + disabled: false, + empty: null, + pattern: /value/gi, + big: 2n, + list: ['one', 2, null], + object: { nested: true, method() {} }, + member: globalThis.location, + called: String(42), + ...shared, +}; diff --git a/packages/integration-tests/cases/js/defaults/value-serialization/output.json b/packages/integration-tests/cases/js/defaults/value-serialization/output.json new file mode 100644 index 00000000000..85c287c974e --- /dev/null +++ b/packages/integration-tests/cases/js/defaults/value-serialization/output.json @@ -0,0 +1,131 @@ +[ + { + "description": "", + "displayName": "ValueSerialization", + "methods": [], + "props": { + "text": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'value'", + "computed": false + } + }, + "count": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "-2", + "computed": false + } + }, + "disabled": { + "type": { + "name": "bool" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "false", + "computed": false + } + }, + "empty": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "null", + "computed": false + } + }, + "pattern": { + "type": { + "name": "instanceOf", + "value": "RegExp" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "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/value/gi", + "computed": false + } + }, + "big": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "2n", + "computed": false + } + }, + "list": { + "type": { + "name": "array" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "['one', 2, null]", + "computed": false + } + }, + "object": { + "type": { + "name": "object" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "{ nested: true, method() {} }", + "computed": false + } + }, + "member": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "globalThis.location", + "computed": true + } + }, + "called": { + "type": { + "name": "any" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "String(42)", + "computed": true + } + }, + "spreadValue": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'shared'", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/annotated-function/index.jsx b/packages/integration-tests/cases/js/definitions/annotated-function/index.jsx new file mode 100644 index 00000000000..a5c569972bf --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/annotated-function/index.jsx @@ -0,0 +1,4 @@ +// @component +const AnnotatedButton = ({ children }) => ; + +AnnotatedButton.displayName = 'AnnotatedButton'; diff --git a/packages/integration-tests/cases/js/definitions/annotated-function/output.json b/packages/integration-tests/cases/js/definitions/annotated-function/output.json new file mode 100644 index 00000000000..9542f41d02a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/annotated-function/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": "AnnotatedButton", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx new file mode 100644 index 00000000000..192277f1dbe --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/index.jsx @@ -0,0 +1,17 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +let Assigned; + +Assigned = class extends React.Component { + render() { + return
; + } +}; + +Assigned.propTypes = { + value: PropTypes.number, +}; +Assigned.displayName = true; + +export default Assigned; diff --git a/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json new file mode 100644 index 00000000000..d7f3431966a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/assigned-class-invalid-display-name/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "value": { + "type": { + "name": "number" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx new file mode 100644 index 00000000000..f684e9497c8 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/index.jsx @@ -0,0 +1,17 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +const AssignedClass = class extends React.Component { + render() { + return
; + } +}; + +AssignedClass.propTypes = { + /** Visible text. */ + label: PropTypes.string.isRequired, +}; +AssignedClass.defaultProps = { label: 'default' }; +AssignedClass.displayName = 'AssignedClassDisplayName'; + +export default AssignedClass; diff --git a/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json new file mode 100644 index 00000000000..b46eaf8f09e --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/class-expression-static-assignments/output.json @@ -0,0 +1,20 @@ +[ + { + "description": "", + "displayName": "AssignedClassDisplayName", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "Visible text.", + "defaultValue": { + "value": "'default'", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx new file mode 100644 index 00000000000..2a67226448a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/index.jsx @@ -0,0 +1,18 @@ +import PropTypes from 'prop-types'; + +const withOuterConfiguration = (..._arguments) => null; +const withInnerConfiguration = (..._arguments) => null; + +function NestedHocBase() { + return
; +} + +NestedHocBase.propTypes = { + /** Base value. */ + value: PropTypes.string.isRequired, +}; + +export default withOuterConfiguration( + { enabled: true }, + withInnerConfiguration('configured', NestedHocBase), +); diff --git a/packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json new file mode 100644 index 00000000000..0f8d9019219 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/configured-nested-hoc/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "NestedHocBase", + "methods": [], + "props": { + "value": { + "type": { + "name": "string" + }, + "required": true, + "description": "Base value." + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_9.js b/packages/integration-tests/cases/js/definitions/custom-base-class-render/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_9.js rename to packages/integration-tests/cases/js/definitions/custom-base-class-render/index.js diff --git a/packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json b/packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json new file mode 100644 index 00000000000..227412b3fae --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/custom-base-class-render/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "Should be recognized as component.", + "displayName": "ExampleComponent", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx b/packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx new file mode 100644 index 00000000000..1c6b28ddebd --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/display-name-resolution/index.jsx @@ -0,0 +1,14 @@ +import React from 'react'; + +const resolvedName = 'ResolvedDisplayName'; + +/** Component with a resolved static display name. */ +export default class OriginalName extends React.Component { + static get displayName() { + return resolvedName; + } + + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/js/definitions/display-name-resolution/output.json b/packages/integration-tests/cases/js/definitions/display-name-resolution/output.json new file mode 100644 index 00000000000..414f765822a --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/display-name-resolution/output.json @@ -0,0 +1,18 @@ +[ + { + "description": "Component with a resolved static display name.", + "displayName": "ResolvedDisplayName", + "methods": [ + { + "name": "displayName", + "docblock": null, + "modifiers": [ + "static", + "get" + ], + "params": [], + "returns": null + } + ] + } +] diff --git a/packages/integration-tests/cases/js/definitions/function-declaration/index.jsx b/packages/integration-tests/cases/js/definitions/function-declaration/index.jsx new file mode 100644 index 00000000000..c8b87d78986 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/function-declaration/index.jsx @@ -0,0 +1,4 @@ +/** Greets the user. */ +export function Greeting() { + return
; +} diff --git a/packages/integration-tests/cases/js/definitions/function-declaration/output.json b/packages/integration-tests/cases/js/definitions/function-declaration/output.json new file mode 100644 index 00000000000..6365c73cc66 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/function-declaration/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "Greets the user.", + "displayName": "Greeting", + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_3.js b/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_3.js rename to packages/integration-tests/cases/js/definitions/hoc-wrapped-component/index.js diff --git a/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json b/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json new file mode 100644 index 00000000000..b7f9bc461d2 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/hoc-wrapped-component/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "Test", + "methods": [], + "props": { + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx b/packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx new file mode 100644 index 00000000000..3ae9106da15 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/numeric-display-name/index.jsx @@ -0,0 +1,5 @@ +export default function NumericDisplayName() { + return
; +} + +NumericDisplayName.displayName = 42; diff --git a/packages/integration-tests/cases/js/definitions/numeric-display-name/output.json b/packages/integration-tests/cases/js/definitions/numeric-display-name/output.json new file mode 100644 index 00000000000..640ca210225 --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/numeric-display-name/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": 42, + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_1.js b/packages/integration-tests/cases/js/definitions/react-create-class-assignment/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_1.js rename to packages/integration-tests/cases/js/definitions/react-create-class-assignment/index.js diff --git a/packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json b/packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json new file mode 100644 index 00000000000..353b2b3a8de --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/react-create-class-assignment/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "The is a component to test the document generation", + "displayName": "Component", + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_7.js b/packages/integration-tests/cases/js/definitions/react-create-class-variable/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_7.js rename to packages/integration-tests/cases/js/definitions/react-create-class-variable/index.js diff --git a/packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json b/packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json new file mode 100644 index 00000000000..353b2b3a8de --- /dev/null +++ b/packages/integration-tests/cases/js/definitions/react-create-class-variable/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "The is a component to test the document generation", + "displayName": "Component", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/errors/missing-definition/error.json b/packages/integration-tests/cases/js/errors/missing-definition/error.json new file mode 100644 index 00000000000..ade7875a31f --- /dev/null +++ b/packages/integration-tests/cases/js/errors/missing-definition/error.json @@ -0,0 +1,3 @@ +{ + "code": "ERR_REACTDOCGEN_MISSING_DEFINITION" +} diff --git a/packages/integration-tests/cases/js/errors/missing-definition/index.jsx b/packages/integration-tests/cases/js/errors/missing-definition/index.jsx new file mode 100644 index 00000000000..64a32fd291e --- /dev/null +++ b/packages/integration-tests/cases/js/errors/missing-definition/index.jsx @@ -0,0 +1 @@ +export const answer = 42; diff --git a/packages/integration-tests/cases/js/errors/multiple-definitions/error.json b/packages/integration-tests/cases/js/errors/multiple-definitions/error.json new file mode 100644 index 00000000000..8a4d08b0f60 --- /dev/null +++ b/packages/integration-tests/cases/js/errors/multiple-definitions/error.json @@ -0,0 +1,3 @@ +{ + "code": "ERR_REACTDOCGEN_MULTIPLE_DEFINITIONS" +} diff --git a/packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx b/packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx new file mode 100644 index 00000000000..b7adebe5322 --- /dev/null +++ b/packages/integration-tests/cases/js/errors/multiple-definitions/index.jsx @@ -0,0 +1,7 @@ +export function First() { + return
; +} + +export function Second() { + return ; +} diff --git a/packages/integration-tests/cases/js/exports/commonjs-module/index.jsx b/packages/integration-tests/cases/js/exports/commonjs-module/index.jsx new file mode 100644 index 00000000000..5fc2fd63a87 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-module/index.jsx @@ -0,0 +1,11 @@ +const PropTypes = require('prop-types'); + +function CommonJsButton({ label }) { + return ; +} + +CommonJsButton.propTypes = { + label: PropTypes.string.isRequired, +}; + +module.exports = CommonJsButton; diff --git a/packages/integration-tests/cases/js/exports/commonjs-module/output.json b/packages/integration-tests/cases/js/exports/commonjs-module/output.json new file mode 100644 index 00000000000..324fe5f5c25 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-module/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "CommonJsButton", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/exports/commonjs-named/index.jsx b/packages/integration-tests/cases/js/exports/commonjs-named/index.jsx new file mode 100644 index 00000000000..3fcaf36dd31 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-named/index.jsx @@ -0,0 +1,9 @@ +const React = require('react'); + +class CommonJsClass extends React.Component { + render() { + return
; + } +} + +exports.CommonJsClass = CommonJsClass; diff --git a/packages/integration-tests/cases/js/exports/commonjs-named/output.json b/packages/integration-tests/cases/js/exports/commonjs-named/output.json new file mode 100644 index 00000000000..5a5f831830a --- /dev/null +++ b/packages/integration-tests/cases/js/exports/commonjs-named/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": "CommonJsClass", + "methods": [] + } +] diff --git a/packages/integration-tests/cases/js/exports/computed-commonjs/error.json b/packages/integration-tests/cases/js/exports/computed-commonjs/error.json new file mode 100644 index 00000000000..ade7875a31f --- /dev/null +++ b/packages/integration-tests/cases/js/exports/computed-commonjs/error.json @@ -0,0 +1,3 @@ +{ + "code": "ERR_REACTDOCGEN_MISSING_DEFINITION" +} diff --git a/packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx b/packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx new file mode 100644 index 00000000000..44a9e3ac7a0 --- /dev/null +++ b/packages/integration-tests/cases/js/exports/computed-commonjs/index.jsx @@ -0,0 +1,7 @@ +const EXPORT_NAME = 'exports'; + +function ComputedCommonJs() { + return
; +} + +module[EXPORT_NAME] = ComputedCommonJs; diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_34.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_34.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_34.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_34.js diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_35.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_35.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_35.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_35.js diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_36.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_36.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_36.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_36.js diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_6.js b/packages/integration-tests/cases/js/imports/export-star-chain/component_6.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_6.js rename to packages/integration-tests/cases/js/imports/export-star-chain/component_6.js diff --git a/packages/integration-tests/cases/js/imports/export-star-chain/index.js b/packages/integration-tests/cases/js/imports/export-star-chain/index.js new file mode 100644 index 00000000000..ae76d448c9f --- /dev/null +++ b/packages/integration-tests/cases/js/imports/export-star-chain/index.js @@ -0,0 +1,9 @@ +import {SuperCustomButton, sharedProps} from './component_35.js'; +import PropTypes from 'prop-types'; + +export function SuperDuperCustomButton({color, ...otherProps}) { + return ; +} + +SuperDuperCustomButton.propTypes = sharedProps; +export * from './component_35.js'; diff --git a/packages/integration-tests/cases/js/imports/export-star-chain/output.json b/packages/integration-tests/cases/js/imports/export-star-chain/output.json new file mode 100644 index 00000000000..0b23a1fefc7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/export-star-chain/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx new file mode 100644 index 00000000000..543df50cc2b --- /dev/null +++ b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/index.jsx @@ -0,0 +1,17 @@ +import PropTypes from 'prop-types'; +import defaults, { choices } from './values.js'; + +export default function ImportedDefaultsAndEnums() { + return
; +} + +ImportedDefaultsAndEnums.propTypes = { + label: PropTypes.string, + count: PropTypes.number, + choice: PropTypes.oneOf(Object.values(choices)), +}; + +ImportedDefaultsAndEnums.defaultProps = { + ...defaults, + choice: choices.primary, +}; diff --git a/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json new file mode 100644 index 00000000000..5a6986ee900 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/output.json @@ -0,0 +1,52 @@ +[ + { + "description": "", + "displayName": "ImportedDefaultsAndEnums", + "methods": [], + "props": { + "label": { + "type": { + "name": "string" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'imported'", + "computed": false + } + }, + "count": { + "type": { + "name": "number" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "3", + "computed": false + } + }, + "choice": { + "type": { + "name": "enum", + "value": [ + { + "value": "\"primary\"", + "computed": false + }, + { + "value": "\"secondary\"", + "computed": false + } + ] + }, + "required": false, + "description": "", + "defaultValue": { + "value": "'primary'", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js new file mode 100644 index 00000000000..08b93a8b088 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/imported-defaults-and-enums/values.js @@ -0,0 +1,9 @@ +export const choices = { + primary: 'primary', + secondary: 'secondary', +}; + +export default { + label: 'imported', + count: 3, +}; diff --git a/packages/integration-tests/cases/js/imports/member-proptypes/component_34.js b/packages/integration-tests/cases/js/imports/member-proptypes/component_34.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/member-proptypes/component_34.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_38.js b/packages/integration-tests/cases/js/imports/member-proptypes/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_38.js rename to packages/integration-tests/cases/js/imports/member-proptypes/index.js diff --git a/packages/integration-tests/cases/js/imports/member-proptypes/output.json b/packages/integration-tests/cases/js/imports/member-proptypes/output.json new file mode 100644 index 00000000000..0b23a1fefc7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/member-proptypes/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js b/packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/namespace-reexport/component_34.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/imports/namespace-reexport/index.js b/packages/integration-tests/cases/js/imports/namespace-reexport/index.js new file mode 100644 index 00000000000..2c92127a749 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/namespace-reexport/index.js @@ -0,0 +1,9 @@ +import * as C36 from './component_36.js'; +import PropTypes from 'prop-types'; + +export function SuperDuperCustomButton({color, ...otherProps}) { + return ; +} + +SuperDuperCustomButton.propTypes = C36.sharedProps; +export {SuperCustomButton} from './component_36.js'; diff --git a/packages/integration-tests/cases/js/imports/namespace-reexport/output.json b/packages/integration-tests/cases/js/imports/namespace-reexport/output.json new file mode 100644 index 00000000000..0b23a1fefc7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/namespace-reexport/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperDuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js b/packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/reexported-proptypes/component_34.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/imports/reexported-proptypes/index.js b/packages/integration-tests/cases/js/imports/reexported-proptypes/index.js new file mode 100644 index 00000000000..35aa85afaf7 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/reexported-proptypes/index.js @@ -0,0 +1,10 @@ +import {CustomButton, sharedProps} from './component_34.js'; +import PropTypes from 'prop-types'; + +export function SuperCustomButton({color, ...otherProps}) { + return ; +} + +SuperCustomButton.propTypes = sharedProps; +export {sharedProps}; +export * from './component_36.js'; diff --git a/packages/integration-tests/cases/js/imports/reexported-proptypes/output.json b/packages/integration-tests/cases/js/imports/reexported-proptypes/output.json new file mode 100644 index 00000000000..f01edcd3b3e --- /dev/null +++ b/packages/integration-tests/cases/js/imports/reexported-proptypes/output.json @@ -0,0 +1,30 @@ +[ + { + "description": "", + "displayName": "SuperCustomButton", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js b/packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js new file mode 100644 index 00000000000..89355ab5f45 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/spread-proptypes/component_6.js @@ -0,0 +1,26 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +const Button = ({ children, onClick, style = {} }) => ( + +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/imports/spread-proptypes/index.js b/packages/integration-tests/cases/js/imports/spread-proptypes/index.js new file mode 100644 index 00000000000..0001bf8c641 --- /dev/null +++ b/packages/integration-tests/cases/js/imports/spread-proptypes/index.js @@ -0,0 +1,13 @@ +import Button from './component_6.js'; +import PropTypes from 'prop-types'; + +export function CustomButton({color, ...otherProps}) { + return +); + +Button.propTypes = { + children: PropTypes.string.isRequired, + onClick: PropTypes.func, + style: PropTypes.object, +}; + +Button.childContextTypes = { + color: PropTypes.string, +}; + +Button.contextTypes = { + config: PropTypes.object, +}; +export default Button; diff --git a/packages/integration-tests/cases/js/props/package-proptypes-context/output.json b/packages/integration-tests/cases/js/props/package-proptypes-context/output.json new file mode 100644 index 00000000000..dc56f9d9334 --- /dev/null +++ b/packages/integration-tests/cases/js/props/package-proptypes-context/output.json @@ -0,0 +1,50 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "{}", + "computed": false + } + } + }, + "context": { + "config": { + "type": { + "name": "object" + }, + "required": false + } + }, + "childContext": { + "color": { + "type": { + "name": "string" + }, + "required": false + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_5.js b/packages/integration-tests/cases/js/props/react-proptypes-context/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_5.js rename to packages/integration-tests/cases/js/props/react-proptypes-context/index.js diff --git a/packages/integration-tests/cases/js/props/react-proptypes-context/output.json b/packages/integration-tests/cases/js/props/react-proptypes-context/output.json new file mode 100644 index 00000000000..dc56f9d9334 --- /dev/null +++ b/packages/integration-tests/cases/js/props/react-proptypes-context/output.json @@ -0,0 +1,50 @@ +[ + { + "description": "", + "displayName": "Button", + "methods": [], + "props": { + "children": { + "type": { + "name": "string" + }, + "required": true, + "description": "" + }, + "onClick": { + "type": { + "name": "func" + }, + "required": false, + "description": "" + }, + "style": { + "type": { + "name": "object" + }, + "required": false, + "description": "", + "defaultValue": { + "value": "{}", + "computed": false + } + } + }, + "context": { + "config": { + "type": { + "name": "object" + }, + "required": false + } + }, + "childContext": { + "color": { + "type": { + "name": "string" + }, + "required": false + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_17.js b/packages/integration-tests/cases/js/props/shape-exact-and-union/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_17.js rename to packages/integration-tests/cases/js/props/shape-exact-and-union/index.js diff --git a/packages/integration-tests/cases/js/props/shape-exact-and-union/output.json b/packages/integration-tests/cases/js/props/shape-exact-and-union/output.json new file mode 100644 index 00000000000..80a21cd55d5 --- /dev/null +++ b/packages/integration-tests/cases/js/props/shape-exact-and-union/output.json @@ -0,0 +1,61 @@ +[ + { + "description": "", + "displayName": "Foo", + "methods": [], + "props": { + "shapeProp": { + "type": { + "name": "shape", + "value": { + "a": { + "name": "string", + "description": "Comment for property a", + "required": false + }, + "b": { + "name": "number", + "required": false + } + } + }, + "required": false, + "description": "" + }, + "exactProp": { + "type": { + "name": "exact", + "value": { + "c": { + "name": "string", + "description": "Comment for property c", + "required": false + }, + "d": { + "name": "number", + "required": false + } + } + }, + "required": false, + "description": "" + }, + "oneOfTypeProp": { + "type": { + "name": "union", + "value": [ + { + "name": "string", + "description": "Comment for type string" + }, + { + "name": "number" + } + ] + }, + "required": false, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_2.js b/packages/integration-tests/cases/js/regressions/class-static-getters/index.js similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_2.js rename to packages/integration-tests/cases/js/regressions/class-static-getters/index.js diff --git a/packages/integration-tests/cases/js/regressions/class-static-getters/output.json b/packages/integration-tests/cases/js/regressions/class-static-getters/output.json new file mode 100644 index 00000000000..2a033e80871 --- /dev/null +++ b/packages/integration-tests/cases/js/regressions/class-static-getters/output.json @@ -0,0 +1,37 @@ +[ + { + "description": "", + "displayName": "button", + "methods": [ + { + "name": "displayName", + "docblock": null, + "modifiers": [ + "static", + "get" + ], + "params": [], + "returns": null + }, + { + "name": "defaultProps", + "docblock": null, + "modifiers": [ + "static", + "get" + ], + "params": [], + "returns": null + } + ], + "props": { + "type": { + "defaultValue": { + "value": "\"primary\"", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_28.tsx b/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_28.tsx rename to packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/index.tsx diff --git a/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json b/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json new file mode 100644 index 00000000000..3f988b09614 --- /dev/null +++ b/packages/integration-tests/cases/typescript/defaults/forward-ref-parameter-default/output.json @@ -0,0 +1,20 @@ +[ + { + "description": "Example component description", + "displayName": "ABC", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "Example prop description", + "defaultValue": { + "value": "true", + "computed": false + } + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/defaults/function-default-parameters/index.tsx b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/index.tsx new file mode 100644 index 00000000000..c2f1897677b --- /dev/null +++ b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/index.tsx @@ -0,0 +1,11 @@ +type Props = { + /** Text shown inside the button. */ + label: string; + /** Prevents interaction. */ + disabled?: boolean; +}; + +/** Renders a button. */ +export function Button({ label, disabled = false }: Props) { + return ; +} diff --git a/packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json new file mode 100644 index 00000000000..07f2a5e79be --- /dev/null +++ b/packages/integration-tests/cases/typescript/defaults/function-default-parameters/output.json @@ -0,0 +1,27 @@ +[ + { + "description": "Renders a button.", + "displayName": "Button", + "methods": [], + "props": { + "label": { + "description": "Text shown inside the button.", + "required": true, + "tsType": { + "name": "string" + } + }, + "disabled": { + "description": "Prevents interaction.", + "required": false, + "tsType": { + "name": "boolean" + }, + "defaultValue": { + "value": "false", + "computed": false + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/class-without-id.tsx b/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/class-without-id.tsx rename to packages/integration-tests/cases/typescript/definitions/anonymous-default-class/index.tsx diff --git a/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json b/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json new file mode 100644 index 00000000000..f303d0fbc07 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/anonymous-default-class/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx new file mode 100644 index 00000000000..27665394034 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/index.tsx @@ -0,0 +1,12 @@ +import { Component as Base } from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +export default class MyComponent extends withFoo(Base) { + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component-alias/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx new file mode 100644 index 00000000000..b526beb4e46 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component/index.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +interface Props { + /** + * description of value + */ + value: string; +} + +function withFoo React.Component>( + Base: T, +) { + return class extends Base {}; +} + +export default class MyComponent extends withFoo(React.Component) { + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-component/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-component/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-component/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx new file mode 100644 index 00000000000..06c7929eb7b --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/index.tsx @@ -0,0 +1,13 @@ +import React from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +export default class MyComponent extends withFoo(React.Component) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-declared-props/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx new file mode 100644 index 00000000000..d7cf4e81851 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/index.tsx @@ -0,0 +1,13 @@ +import { PureComponent as Base } from 'react'; + +interface Props { + /** description of value */ + value: string; + enabled?: boolean; +} + +export default class MyComponent extends withFoo(Base) { + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json new file mode 100644 index 00000000000..e48b3c08c69 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-pure-component-alias/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + }, + "enabled": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx new file mode 100644 index 00000000000..623dc1e76f7 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/index.tsx @@ -0,0 +1,19 @@ +import Other from 'other'; + +interface Props { + /** description of value */ + value: string; +} + +interface Options { + unrelated: number; +} + +export default class MyComponent extends makeComponent( + Other.Component, +) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-component/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx new file mode 100644 index 00000000000..dabe2b661d3 --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/index.tsx @@ -0,0 +1,23 @@ +import React from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +interface Options { + unrelated: number; +} +function configure() { + return {}; +} +function makeComponent(_configuration: unknown) { + return React.Component; +} + +export default class MyComponent extends makeComponent(configure) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-unrelated-generic/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx new file mode 100644 index 00000000000..ceef9c4a54f --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/index.tsx @@ -0,0 +1,17 @@ +import React from 'react'; + +interface Props { + /** description of value */ + value: string; +} + +export default class MyComponent extends withFoo( + React.Component< + React.PropsWithChildren>> + >, +) { + props: Props; + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json new file mode 100644 index 00000000000..3462c2d46bd --- /dev/null +++ b/packages/integration-tests/cases/typescript/definitions/mixin-wrapped-props/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "description of value" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/namespace-export.tsx b/packages/integration-tests/cases/typescript/exports/namespace-reexport/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/namespace-export.tsx rename to packages/integration-tests/cases/typescript/exports/namespace-reexport/index.tsx diff --git a/packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json b/packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json new file mode 100644 index 00000000000..f303d0fbc07 --- /dev/null +++ b/packages/integration-tests/cases/typescript/exports/namespace-reexport/output.json @@ -0,0 +1,15 @@ +[ + { + "description": "", + "methods": [], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/support/other-exports.ts b/packages/integration-tests/cases/typescript/exports/namespace-reexport/support/other-exports.ts similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/support/other-exports.ts rename to packages/integration-tests/cases/typescript/exports/namespace-reexport/support/other-exports.ts diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_27.tsx b/packages/integration-tests/cases/typescript/imports/extended-props/component_27.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_27.tsx rename to packages/integration-tests/cases/typescript/imports/extended-props/component_27.tsx diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_39.tsx b/packages/integration-tests/cases/typescript/imports/extended-props/component_39.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_39.tsx rename to packages/integration-tests/cases/typescript/imports/extended-props/component_39.tsx diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_33.tsx b/packages/integration-tests/cases/typescript/imports/extended-props/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_33.tsx rename to packages/integration-tests/cases/typescript/imports/extended-props/index.tsx diff --git a/packages/integration-tests/cases/typescript/imports/extended-props/output.json b/packages/integration-tests/cases/typescript/imports/extended-props/output.json new file mode 100644 index 00000000000..085b2a81e74 --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/extended-props/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "This is a typescript component with imported prop types", + "displayName": "ImportedExtendedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + }, + "bar": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx b/packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx new file mode 100644 index 00000000000..2b7ad0e8d30 --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/imported-props/component_27.tsx @@ -0,0 +1,35 @@ +import React, { Component } from 'react'; + +export interface Props { + foo: string +} + +/** + * This is a typescript class component + */ +export default class TSComponent extends Component { + render() { + return

Hello world

; + } + + /** + * This is a method + */ + foo(a: string): string { + return a; + } + + /** + * This is a public method + */ + public bar(a: string): string { + return a; + } + + /** + * This is a private method + */ + private baz(a: string): string { + return a; + } +} diff --git a/packages/integration-tests/cases/typescript/imports/imported-props/index.tsx b/packages/integration-tests/cases/typescript/imports/imported-props/index.tsx new file mode 100644 index 00000000000..32ca3239943 --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/imported-props/index.tsx @@ -0,0 +1,13 @@ +import React, { Component } from 'react'; +import { Props as ImportedProps } from './component_27.jsx'; + +export default interface ExtendedProps extends ImportedProps { + bar: number +} + +/** + * This is a typescript component with imported prop types + */ +export function ImportedComponent(props: ImportedProps) { + return

Hello world

; +} diff --git a/packages/integration-tests/cases/typescript/imports/imported-props/output.json b/packages/integration-tests/cases/typescript/imports/imported-props/output.json new file mode 100644 index 00000000000..5c8b99c401b --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/imported-props/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "This is a typescript component with imported prop types", + "displayName": "ImportedComponent", + "methods": [], + "props": { + "foo": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/test-all-imports.tsx b/packages/integration-tests/cases/typescript/imports/reexported-default-values/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/test-all-imports.tsx rename to packages/integration-tests/cases/typescript/imports/reexported-default-values/index.tsx diff --git a/packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json b/packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json new file mode 100644 index 00000000000..76bdad981fe --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/reexported-default-values/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "This is a TS component with imported stuff", + "displayName": "ImportedExtendedComponent", + "methods": [], + "props": { + "x": { + "defaultValue": { + "value": "\"string\"", + "computed": false + }, + "required": false + }, + "y": { + "defaultValue": { + "value": "'otherstring'", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts b/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts new file mode 100644 index 00000000000..129c265f93d --- /dev/null +++ b/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/other-exports.ts @@ -0,0 +1 @@ +export default 'otherstring' diff --git a/packages/react-docgen/tests/integration/__fixtures__/support/some-exports.ts b/packages/integration-tests/cases/typescript/imports/reexported-default-values/support/some-exports.ts similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/support/some-exports.ts rename to packages/integration-tests/cases/typescript/imports/reexported-default-values/support/some-exports.ts diff --git a/packages/integration-tests/cases/typescript/methods/class-methods/index.tsx b/packages/integration-tests/cases/typescript/methods/class-methods/index.tsx new file mode 100644 index 00000000000..2b7ad0e8d30 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/class-methods/index.tsx @@ -0,0 +1,35 @@ +import React, { Component } from 'react'; + +export interface Props { + foo: string +} + +/** + * This is a typescript class component + */ +export default class TSComponent extends Component { + render() { + return

Hello world

; + } + + /** + * This is a method + */ + foo(a: string): string { + return a; + } + + /** + * This is a public method + */ + public bar(a: string): string { + return a; + } + + /** + * This is a private method + */ + private baz(a: string): string { + return a; + } +} diff --git a/packages/integration-tests/cases/typescript/methods/class-methods/output.json b/packages/integration-tests/cases/typescript/methods/class-methods/output.json new file mode 100644 index 00000000000..a96a47e1275 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/class-methods/output.json @@ -0,0 +1,57 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [ + { + "name": "foo", + "docblock": "This is a method", + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "This is a method" + }, + { + "name": "bar", + "docblock": "This is a public method", + "modifiers": [], + "params": [ + { + "name": "a", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "This is a public method" + } + ], + "props": { + "foo": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx new file mode 100644 index 00000000000..688a420bd34 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/index.tsx @@ -0,0 +1,18 @@ +import { memo, forwardRef, useCallback, useImperativeHandle } from 'react'; + +export const MyComponent = memo( + forwardRef((_, ref) => { + const _myMethod = useCallback((argument: string): number => 1, []); + + useImperativeHandle( + ref, + () => ({ + /** myMethod description */ + _myMethod, + }), + [], + ); + + return
; + }), +); diff --git a/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json new file mode 100644 index 00000000000..c4ad8df17ed --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/imperative-handle-callbacks/output.json @@ -0,0 +1,28 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [ + { + "name": "_myMethod", + "docblock": "myMethod description", + "modifiers": [], + "params": [ + { + "name": "argument", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "number" + } + }, + "description": "myMethod description" + } + ] + } +] diff --git a/packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx new file mode 100644 index 00000000000..7e6e52fe5a0 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/index.tsx @@ -0,0 +1,34 @@ +import React from 'react'; + +interface Props { + value: string; +} + +export default class TypedMethods extends React.Component { + /** Static helper. */ + static utility(value: number): string { + return String(value); + } + + /** Loads one value. */ + async load(value: string): Promise { + return value; + } + + /** Produces values. */ + *items(count: number): Generator { + yield count; + } + + /** Computed method. */ + ['computed'](enabled?: boolean): boolean { + return enabled ?? false; + } + + /** Arrow property. */ + arrow = (value: number): string => String(value); + + render() { + return
; + } +} diff --git a/packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json new file mode 100644 index 00000000000..bd71645edb3 --- /dev/null +++ b/packages/integration-tests/cases/typescript/methods/modifiers-and-types/output.json @@ -0,0 +1,135 @@ +[ + { + "description": "", + "displayName": "TypedMethods", + "methods": [ + { + "name": "utility", + "docblock": "Static helper.", + "modifiers": [ + "static" + ], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "number" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "Static helper." + }, + { + "name": "load", + "docblock": "Loads one value.", + "modifiers": [ + "async" + ], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "string" + } + } + ], + "returns": { + "type": { + "name": "Promise", + "elements": [ + { + "name": "string" + } + ], + "raw": "Promise" + } + }, + "description": "Loads one value." + }, + { + "name": "items", + "docblock": "Produces values.", + "modifiers": [ + "generator" + ], + "params": [ + { + "name": "count", + "optional": false, + "type": { + "name": "number" + } + } + ], + "returns": { + "type": { + "name": "Generator", + "elements": [ + { + "name": "number" + } + ], + "raw": "Generator" + } + }, + "description": "Produces values." + }, + { + "name": "computed", + "docblock": "Computed method.", + "modifiers": [], + "params": [ + { + "name": "enabled", + "optional": true, + "type": { + "name": "boolean" + } + } + ], + "returns": { + "type": { + "name": "boolean" + } + }, + "description": "Computed method." + }, + { + "name": "arrow", + "docblock": "Arrow property.", + "modifiers": [], + "params": [ + { + "name": "value", + "optional": false, + "type": { + "name": "number" + } + } + ], + "returns": { + "type": { + "name": "string" + } + }, + "description": "Arrow property." + } + ], + "props": { + "value": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx new file mode 100644 index 00000000000..bf4c5bfd061 --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/index.tsx @@ -0,0 +1,11 @@ +interface A extends B { + a: number; +} + +interface B extends A { + b: number; +} + +export function Component(props: A) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json new file mode 100644 index 00000000000..b4cd621ecc7 --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-interface-inheritance/output.json @@ -0,0 +1,23 @@ +[ + { + "description": "", + "displayName": "Component", + "methods": [], + "props": { + "b": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + }, + "a": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx new file mode 100644 index 00000000000..8480b5fb3f3 --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/index.tsx @@ -0,0 +1,6 @@ +type Foo = Bar; +type Bar = Foo; + +export function Component(props: Foo) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json new file mode 100644 index 00000000000..dde063f6a2d --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/circular-type-aliases/output.json @@ -0,0 +1,7 @@ +[ + { + "description": "", + "displayName": "Component", + "methods": [] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_43.tsx b/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_43.tsx rename to packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/index.tsx diff --git a/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json b/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json new file mode 100644 index 00000000000..0cc94b7fa1c --- /dev/null +++ b/packages/integration-tests/cases/typescript/regressions/polymorphic-forward-ref/output.json @@ -0,0 +1,37 @@ +[ + { + "description": "", + "displayName": "MenuItem", + "methods": [], + "props": { + "children": { + "type": { + "name": "node" + }, + "required": false, + "description": "Menu item contents." + }, + "classes": { + "type": { + "name": "object" + }, + "required": false, + "description": "Override or extend the styles applied to the component. See CSS API below for more details." + }, + "component": { + "defaultValue": { + "value": "'li'", + "computed": false + }, + "required": false + }, + "disableGutters": { + "defaultValue": { + "value": "false", + "computed": false + }, + "required": false + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/advanced-props/index.tsx b/packages/integration-tests/cases/typescript/types/advanced-props/index.tsx new file mode 100644 index 00000000000..b453a3bc5f6 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/advanced-props/index.tsx @@ -0,0 +1,41 @@ +import type * as React from 'react'; + +const values = { first: 'one', second: 'two' } as const; +type Values = typeof values; +type Action = { subAction?: Action }; + +interface IndexedInterface { + x: string; +} + +interface Callable { + (value: string): number; + [key: string]: unknown; + method(value: number): void; +} + +interface Props { + keys: keyof Values; + value: Values[keyof Values]; + mapped: { [Key in keyof Values]?: Values[Key] }; + children: React.ReactNode; + component: React.ComponentType<{ enabled: boolean }>; + callable: Callable; + rest: (...values: string[]) => void; + neverValue: never; + nullValue: null; + undefinedValue: undefined; + symbolValue: symbol; + objectValue: object; + action: Action; + interfaceIndex: IndexedInterface['x']; + qualifiedTypeof: typeof values.first; + inlineKeys: keyof { apple: string; banana: string }; + ref: React.Ref; + childrenArray: React.ChildrenArray; +} + +/** Exercises advanced TypeScript prop type extraction. */ +export function AdvancedTypeScriptTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/types/advanced-props/output.json b/packages/integration-tests/cases/typescript/types/advanced-props/output.json new file mode 100644 index 00000000000..2462c800c6b --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/advanced-props/output.json @@ -0,0 +1,231 @@ +[ + { + "description": "Exercises advanced TypeScript prop type extraction.", + "displayName": "AdvancedTypeScriptTypes", + "methods": [], + "props": { + "keys": { + "required": true, + "tsType": { + "name": "values" + }, + "description": "" + }, + "value": { + "required": true, + "tsType": { + "name": "values[values]", + "raw": "Values[keyof Values]" + }, + "description": "" + }, + "mapped": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{ [Key in keyof Values]?: Values[Key] }", + "signature": { + "properties": [ + { + "key": { + "name": "values", + "required": false + }, + "value": { + "name": "values[Key]", + "raw": "Values[Key]" + } + } + ] + } + }, + "description": "" + }, + "children": { + "required": true, + "tsType": { + "name": "ReactReactNode", + "raw": "React.ReactNode" + }, + "description": "" + }, + "component": { + "required": true, + "tsType": { + "name": "ReactComponentType", + "raw": "React.ComponentType<{ enabled: boolean }>", + "elements": [ + { + "name": "signature", + "type": "object", + "raw": "{ enabled: boolean }", + "signature": { + "properties": [ + { + "key": "enabled", + "value": { + "name": "boolean", + "required": true + } + } + ] + } + } + ] + }, + "description": "" + }, + "callable": { + "required": true, + "tsType": { + "name": "Callable" + }, + "description": "" + }, + "rest": { + "required": true, + "tsType": { + "name": "signature", + "type": "function", + "raw": "(...values: string[]) => void", + "signature": { + "arguments": [ + { + "type": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "string[]" + }, + "name": "values", + "rest": true + } + ], + "return": { + "name": "void" + } + } + }, + "description": "" + }, + "neverValue": { + "required": true, + "tsType": { + "name": "never" + }, + "description": "" + }, + "nullValue": { + "required": true, + "tsType": { + "name": "null" + }, + "description": "" + }, + "undefinedValue": { + "required": true, + "tsType": { + "name": "undefined" + }, + "description": "" + }, + "symbolValue": { + "required": true, + "tsType": { + "name": "symbol" + }, + "description": "" + }, + "objectValue": { + "required": true, + "tsType": { + "name": "object" + }, + "description": "" + }, + "action": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{ subAction?: Action }", + "signature": { + "properties": [ + { + "key": "subAction", + "value": { + "name": "Action", + "required": false + } + } + ] + } + }, + "description": "" + }, + "interfaceIndex": { + "required": true, + "tsType": { + "name": "IndexedInterface['x']", + "raw": "IndexedInterface['x']" + }, + "description": "" + }, + "qualifiedTypeof": { + "required": true, + "tsType": { + "name": "values.first" + }, + "description": "" + }, + "inlineKeys": { + "required": true, + "tsType": { + "name": "union", + "raw": "keyof { apple: string; banana: string }", + "elements": [ + { + "name": "literal", + "value": "apple" + }, + { + "name": "literal", + "value": "banana" + } + ] + }, + "description": "" + }, + "ref": { + "required": true, + "tsType": { + "name": "ReactRef", + "raw": "React.Ref", + "elements": [ + { + "name": "AdvancedTypeScriptTypes" + } + ] + }, + "description": "" + }, + "childrenArray": { + "required": true, + "tsType": { + "name": "ReactChildrenArray", + "raw": "React.ChildrenArray", + "elements": [ + { + "name": "string" + } + ] + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx b/packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx new file mode 100644 index 00000000000..f9cbb26f272 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/comprehensive-props/index.tsx @@ -0,0 +1,27 @@ +const status = 'ready' as const; + +type Pair = [string, number]; + +interface Props { + anything: any; + unknownValue: unknown; + text: string; + count: number; + enabled: boolean; + literal: 'small'; + union: string | number; + intersection: { left: string } & { right: number }; + list: string[]; + readonlyList: ReadonlyArray; + pair: Pair; + callback: (value: string) => boolean; + nested: { value?: string }; + record: Record; + status: typeof status; + optional?: string; +} + +/** Exercises TypeScript prop type extraction. */ +export function TypeScriptTypes(_props: Props) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/types/comprehensive-props/output.json b/packages/integration-tests/cases/typescript/types/comprehensive-props/output.json new file mode 100644 index 00000000000..6f3df955808 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/comprehensive-props/output.json @@ -0,0 +1,224 @@ +[ + { + "description": "Exercises TypeScript prop type extraction.", + "displayName": "TypeScriptTypes", + "methods": [], + "props": { + "anything": { + "required": true, + "tsType": { + "name": "any" + }, + "description": "" + }, + "unknownValue": { + "required": true, + "tsType": { + "name": "unknown" + }, + "description": "" + }, + "text": { + "required": true, + "tsType": { + "name": "string" + }, + "description": "" + }, + "count": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "" + }, + "enabled": { + "required": true, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "literal": { + "required": true, + "tsType": { + "name": "literal", + "value": "'small'" + }, + "description": "" + }, + "union": { + "required": true, + "tsType": { + "name": "union", + "raw": "string | number", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "intersection": { + "required": true, + "tsType": { + "name": "intersection", + "raw": "{ left: string } & { right: number }", + "elements": [ + { + "name": "signature", + "type": "object", + "raw": "{ left: string }", + "signature": { + "properties": [ + { + "key": "left", + "value": { + "name": "string", + "required": true + } + } + ] + } + }, + { + "name": "signature", + "type": "object", + "raw": "{ right: number }", + "signature": { + "properties": [ + { + "key": "right", + "value": { + "name": "number", + "required": true + } + } + ] + } + } + ] + }, + "description": "" + }, + "list": { + "required": true, + "tsType": { + "name": "Array", + "elements": [ + { + "name": "string" + } + ], + "raw": "string[]" + }, + "description": "" + }, + "readonlyList": { + "required": true, + "tsType": { + "name": "ReadonlyArray", + "elements": [ + { + "name": "number" + } + ], + "raw": "ReadonlyArray" + }, + "description": "" + }, + "pair": { + "required": true, + "tsType": { + "name": "tuple", + "raw": "[string, number]", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ] + }, + "description": "" + }, + "callback": { + "required": true, + "tsType": { + "name": "signature", + "type": "function", + "raw": "(value: string) => boolean", + "signature": { + "arguments": [ + { + "type": { + "name": "string" + }, + "name": "value" + } + ], + "return": { + "name": "boolean" + } + } + }, + "description": "" + }, + "nested": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{ value?: string }", + "signature": { + "properties": [ + { + "key": "value", + "value": { + "name": "string", + "required": false + } + } + ] + } + }, + "description": "" + }, + "record": { + "required": true, + "tsType": { + "name": "Record", + "elements": [ + { + "name": "string" + }, + { + "name": "number" + } + ], + "raw": "Record" + }, + "description": "" + }, + "status": { + "required": true, + "tsType": { + "name": "status" + }, + "description": "" + }, + "optional": { + "required": false, + "tsType": { + "name": "string" + }, + "description": "" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_25.tsx b/packages/integration-tests/cases/typescript/types/generic-interface-extension/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_25.tsx rename to packages/integration-tests/cases/typescript/types/generic-interface-extension/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json b/packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json new file mode 100644 index 00000000000..6ede61fa6e6 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/generic-interface-extension/output.json @@ -0,0 +1,36 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "Child" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "tsType": { + "name": "Array", + "elements": [ + { + "name": "Child" + } + ], + "raw": "Array" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "Complex union prop" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_41.tsx b/packages/integration-tests/cases/typescript/types/indexed-access-constant/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_41.tsx rename to packages/integration-tests/cases/typescript/types/indexed-access-constant/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json b/packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json new file mode 100644 index 00000000000..7c633606c59 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/indexed-access-constant/output.json @@ -0,0 +1,17 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "value": { + "required": false, + "tsType": { + "name": "STRING_VALS[number]", + "raw": "typeof STRING_VALS[number]" + }, + "description": "String value of a number" + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_23.tsx b/packages/integration-tests/cases/typescript/types/interface-composition/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_23.tsx rename to packages/integration-tests/cases/typescript/types/interface-composition/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/interface-composition/output.json b/packages/integration-tests/cases/typescript/types/interface-composition/output.json new file mode 100644 index 00000000000..de43d447e5a --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/interface-composition/output.json @@ -0,0 +1,66 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "string" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "tsType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "Complex union prop" + } + }, + "composes": [ + "OtherProps" + ] + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_22.tsx b/packages/integration-tests/cases/typescript/types/nested-object-and-union/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_22.tsx rename to packages/integration-tests/cases/typescript/types/nested-object-and-union/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json b/packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json new file mode 100644 index 00000000000..9761e87349a --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/nested-object-and-union/output.json @@ -0,0 +1,92 @@ +[ + { + "description": "This is a TypeScript function component", + "displayName": "TSFunctionComponent", + "methods": [], + "props": { + "align": { + "required": false, + "tsType": { + "name": "union", + "raw": "\"left\" | \"center\" | \"right\" | \"justify\"", + "elements": [ + { + "name": "literal", + "value": "\"left\"" + }, + { + "name": "literal", + "value": "\"center\"" + }, + { + "name": "literal", + "value": "\"right\"" + }, + { + "name": "literal", + "value": "\"justify\"" + } + ] + }, + "description": "" + }, + "left": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "center": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "right": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "justify": { + "required": false, + "tsType": { + "name": "boolean" + }, + "description": "" + }, + "position": { + "required": true, + "tsType": { + "name": "signature", + "type": "object", + "raw": "{\n /**\n * x coordinate doc\n */\n x: number,\n /**\n * y coordinate doc\n */\n y: number\n}", + "signature": { + "properties": [ + { + "key": "x", + "value": { + "name": "number", + "required": true + }, + "description": "x coordinate doc" + }, + { + "key": "y", + "value": { + "name": "number", + "required": true + }, + "description": "y coordinate doc" + } + ] + } + }, + "description": "position doc" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx new file mode 100644 index 00000000000..83059f49adf --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/index.tsx @@ -0,0 +1,5 @@ +interface Props { + name: (() => string) | undefined; +} + +export const MyComponent = ({ name }: Props) =>
; diff --git a/packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json new file mode 100644 index 00000000000..9d4b416a18c --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/parenthesized-function-union/output.json @@ -0,0 +1,33 @@ +[ + { + "description": "", + "displayName": "MyComponent", + "methods": [], + "props": { + "name": { + "required": true, + "tsType": { + "name": "union", + "raw": "(() => string) | undefined", + "elements": [ + { + "name": "signature", + "type": "function", + "raw": "() => string", + "signature": { + "arguments": [], + "return": { + "name": "string" + } + } + }, + { + "name": "undefined" + } + ] + }, + "description": "" + } + } + } +] diff --git a/packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx new file mode 100644 index 00000000000..f5bbe978c28 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/index.tsx @@ -0,0 +1,15 @@ +import type * as React from 'react'; + +interface Props { + /** Required label. */ + label: string; +} + +/** Exercises nested built-in React prop wrappers. */ +export function WrappedPropsComponent( + _props: React.PropsWithChildren< + React.PropsWithRef> + >, +) { + return
; +} diff --git a/packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json new file mode 100644 index 00000000000..a20710f8343 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/react-prop-wrappers/output.json @@ -0,0 +1,16 @@ +[ + { + "description": "Exercises nested built-in React prop wrappers.", + "displayName": "WrappedPropsComponent", + "methods": [], + "props": { + "label": { + "description": "Required label.", + "required": true, + "tsType": { + "name": "string" + } + } + } + } +] diff --git a/packages/react-docgen/tests/integration/__fixtures__/component_21.tsx b/packages/integration-tests/cases/typescript/types/type-alias-intersection/index.tsx similarity index 100% rename from packages/react-docgen/tests/integration/__fixtures__/component_21.tsx rename to packages/integration-tests/cases/typescript/types/type-alias-intersection/index.tsx diff --git a/packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json b/packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json new file mode 100644 index 00000000000..8bb04a69d22 --- /dev/null +++ b/packages/integration-tests/cases/typescript/types/type-alias-intersection/output.json @@ -0,0 +1,63 @@ +[ + { + "description": "This is a typescript class component", + "displayName": "TSComponent", + "methods": [], + "props": { + "foo": { + "required": false, + "tsType": { + "name": "string" + }, + "description": "Optional prop" + }, + "bar": { + "required": true, + "tsType": { + "name": "number" + }, + "description": "Required prop" + }, + "baz": { + "required": true, + "tsType": { + "name": "union", + "raw": "number | { enter?: number, exit?: number } | 'auto'", + "elements": [ + { + "name": "number" + }, + { + "name": "signature", + "type": "object", + "raw": "{ enter?: number, exit?: number }", + "signature": { + "properties": [ + { + "key": "enter", + "value": { + "name": "number", + "required": false + } + }, + { + "key": "exit", + "value": { + "name": "number", + "required": false + } + } + ] + } + }, + { + "name": "literal", + "value": "'auto'" + } + ] + }, + "description": "Complex union prop" + } + } + } +] diff --git a/packages/integration-tests/package.json b/packages/integration-tests/package.json new file mode 100644 index 00000000000..a7fbe1e3de6 --- /dev/null +++ b/packages/integration-tests/package.json @@ -0,0 +1,23 @@ +{ + "name": "@react-docgen-internal/integration-tests", + "version": "0.0.0", + "private": true, + "description": "Shared integration fixtures for react-docgen parsers.", + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "cases", + "dist" + ], + "scripts": { + "build": "rimraf dist/ && tsc" + }, + "license": "MIT" +} diff --git a/packages/integration-tests/src/index.ts b/packages/integration-tests/src/index.ts new file mode 100644 index 00000000000..41773a94182 --- /dev/null +++ b/packages/integration-tests/src/index.ts @@ -0,0 +1,146 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const languages = ['flow', 'js', 'typescript'] as const; +const features = [ + 'defaults', + 'definitions', + 'documentation', + 'errors', + 'exports', + 'imports', + 'methods', + 'props', + 'regressions', + 'types', +] as const; +const entryPattern = /^index\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx)$/; + +export type IntegrationLanguage = (typeof languages)[number]; + +export interface IntegrationError { + code: string; +} + +export interface IntegrationCase { + directory: string; + error?: IntegrationError; + feature: string; + filename: string; + id: string; + language: IntegrationLanguage; + output?: unknown; + source: string; +} + +export interface LoadIntegrationCasesOptions { + ids?: readonly string[]; + languages?: readonly IntegrationLanguage[]; +} + +export const casesRoot = fileURLToPath(new URL('../cases', import.meta.url)); + +function directories(directory: string): string[] { + return fs + .readdirSync(directory, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort(); +} + +function readJson(filename: string): unknown { + return JSON.parse(fs.readFileSync(filename, 'utf8')) as unknown; +} + +function loadCase( + language: IntegrationLanguage, + feature: string, + name: string, +): IntegrationCase { + const directory = path.join(casesRoot, language, feature, name); + const files = fs.readdirSync(directory); + const entries = files.filter((file) => entryPattern.test(file)); + const outcomes = files.filter( + (file) => file === 'error.json' || file === 'output.json', + ); + + if (entries.length !== 1) { + throw new Error( + `Integration case "${language}/${feature}/${name}" must contain exactly one index source file.`, + ); + } + + if (outcomes.length !== 1) { + throw new Error( + `Integration case "${language}/${feature}/${name}" must contain exactly one output.json or error.json.`, + ); + } + + const [entry] = entries; + const [outcome] = outcomes; + + if (entry === undefined || outcome === undefined) { + throw new Error( + `Invalid integration case "${language}/${feature}/${name}".`, + ); + } + + const id = `${language}/${feature}/${name}`; + const filename = path.join(directory, entry); + + return { + directory, + feature, + filename, + id, + language, + source: fs.readFileSync(filename, 'utf8'), + ...(outcome === 'output.json' + ? { output: readJson(path.join(directory, outcome)) } + : { + error: readJson(path.join(directory, outcome)) as IntegrationError, + }), + }; +} + +export function loadIntegrationCases( + options: LoadIntegrationCasesOptions = {}, +): IntegrationCase[] { + const selectedLanguages = options.languages ?? languages; + const selectedIds = options.ids ? new Set(options.ids) : null; + const cases: IntegrationCase[] = []; + + for (const language of selectedLanguages) { + if (!(languages as readonly string[]).includes(language)) { + throw new Error(`Unknown integration language "${language}".`); + } + + for (const feature of directories(path.join(casesRoot, language))) { + if (!(features as readonly string[]).includes(feature)) { + throw new Error( + `Unknown integration feature "${language}/${feature}".`, + ); + } + + for (const name of directories(path.join(casesRoot, language, feature))) { + const integrationCase = loadCase(language, feature, name); + + if (!selectedIds || selectedIds.has(integrationCase.id)) { + cases.push(integrationCase); + } + } + } + } + + if (selectedIds) { + const foundIds = new Set(cases.map(({ id }) => id)); + const missingIds = [...selectedIds].filter((id) => !foundIds.has(id)); + + if (missingIds.length > 0) { + throw new Error(`Unknown integration cases: ${missingIds.join(', ')}.`); + } + } + + return cases; +} diff --git a/packages/integration-tests/tsconfig.json b/packages/integration-tests/tsconfig.json new file mode 100644 index 00000000000..4bf5c24a4f1 --- /dev/null +++ b/packages/integration-tests/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"] +} diff --git a/packages/react-docgen-cli/package.json b/packages/react-docgen-cli/package.json index 4336a14c918..8d6e55067ac 100644 --- a/packages/react-docgen-cli/package.json +++ b/packages/react-docgen-cli/package.json @@ -19,7 +19,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "scripts": { "build": "rimraf dist/ && tsc", diff --git a/packages/react-docgen-cli/src/commands/parse/command.ts b/packages/react-docgen-cli/src/commands/parse/command.ts index 18a1a12c2c4..70699a9098c 100644 --- a/packages/react-docgen-cli/src/commands/parse/command.ts +++ b/packages/react-docgen-cli/src/commands/parse/command.ts @@ -10,6 +10,7 @@ import { resolve } from 'path'; import slash from '../../utils/slash.js'; import type { Documentation } from 'react-docgen'; import { ResolverConfigs } from './options/loadResolvers.js'; +import importFile from '../../utils/importFile.js'; const debug = debugFactory('react-docgen:cli'); @@ -38,6 +39,7 @@ function collect(value: string, previous: string[]): string[] { } interface CLIOptions { + config?: string; defaultIgnores: boolean; failOnWarning: boolean; handler?: string[]; @@ -54,6 +56,10 @@ export default function createParseCommand(): Command { 'Extract meta information from React components.\n' + 'Either specify a paths to files or a glob pattern that matches multiple files.', ) + .option( + '-c, --config ', + 'Trusted module exporting a parse function, or an object with a parse function, for single-parser or mixed-parser projects.', + ) .option( '-o, --out ', 'Store extracted information in the specified file instead of printing to stdout. If the file exists it will be overwritten.', @@ -96,6 +102,7 @@ export default function createParseCommand(): Command { .argument('', 'Can be globs or paths to files') .action(async (globs: string[], input: CLIOptions) => { const { + config, defaultIgnores, failOnWarning, handler, @@ -115,11 +122,24 @@ export default function createParseCommand(): Command { finalIgnores = []; } - const options = await loadOptions({ - handler, - importer, - resolver, - }); + const configured = config + ? await importFile(config) + : undefined; + + if (config && !configured) { + throw new TypeError(`Could not load config '${config}'.`); + } + const configuredParse = + typeof configured === 'function' ? configured : configured?.parse; + + if (configured && typeof configuredParse !== 'function') { + throw new TypeError( + `Config '${config}' must export a parse function or an object with a parse function.`, + ); + } + const options = configuredParse + ? undefined + : await loadOptions({ handler, importer, resolver }); // we use slash to convert windows backslashes to unix format so fast-glob works const files = await glob(globs.map(slash), { ignore: finalIgnores?.map((ignorePath) => { @@ -143,12 +163,14 @@ export default function createParseCommand(): Command { const content = await readFile(path, 'utf-8'); try { - result[path] = parse(content, { - filename: path, - handlers: options.handlers, - importer: options.importer, - resolver: options.resolver, - }); + result[path] = configuredParse + ? configuredParse(content, { filename: path }) + : parse(content, { + filename: path, + handlers: options?.handlers, + importer: options?.importer, + resolver: options?.resolver, + }); } catch (error) { const isError = outputError(error as Error, path, { failOnWarning, diff --git a/packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js b/packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js new file mode 100644 index 00000000000..005f6c6604e --- /dev/null +++ b/packages/react-docgen-cli/tests/integration/__fixtures__/config/Component.js @@ -0,0 +1,3 @@ +export function Component() { + return null; +} diff --git a/packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs b/packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs new file mode 100644 index 00000000000..29feeee4896 --- /dev/null +++ b/packages/react-docgen-cli/tests/integration/__fixtures__/config/react-docgen.config.mjs @@ -0,0 +1,5 @@ +export default { + parse(_code, { filename }) { + return [{ displayName: filename.endsWith('.js') ? 'Configured' : 'Wrong' }]; + }, +}; diff --git a/packages/react-docgen-cli/tests/integration/cli-test.ts b/packages/react-docgen-cli/tests/integration/cli-test.ts index f0beefec846..a587ef8ca45 100644 --- a/packages/react-docgen-cli/tests/integration/cli-test.ts +++ b/packages/react-docgen-cli/tests/integration/cli-test.ts @@ -3,8 +3,24 @@ import { join } from 'path'; import { temporaryFile } from 'tempy'; import { describe, expect, test } from 'vitest'; import withFixture from './utils/withFixture'; +import slash from '../../src/utils/slash.js'; describe('cli', () => { + test('loads a single-parser or mixed-parser config module', async () => { + await withFixture('config', async ({ dir, run }) => { + const { stdout, stderr } = await run([ + '--config', + join(dir, 'react-docgen.config.mjs'), + join(dir, 'Component.js'), + ]); + + expect(stderr).toBe(''); + expect(JSON.parse(stdout)).toEqual({ + [slash(join(dir, 'Component.js'))]: [{ displayName: 'Configured' }], + }); + }); + }); + describe('glob', () => { test('reads files provided as command line arguments', async () => { await withFixture('basic', async ({ dir, run }) => { diff --git a/packages/react-docgen/package.json b/packages/react-docgen/package.json index 7fce579d521..4cb2c051363 100644 --- a/packages/react-docgen/package.json +++ b/packages/react-docgen/package.json @@ -22,7 +22,7 @@ "dist" ], "engines": { - "node": "^22.13.0 || >=24" + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" }, "main": "dist/main.js", "typings": "dist/main.d.ts", @@ -53,5 +53,8 @@ "doctrine": "^3.0.0", "resolve": "^1.22.1", "strip-indent": "^4.0.0" + }, + "devDependencies": { + "@react-docgen-internal/integration-tests": "workspace:*" } } diff --git a/packages/react-docgen/src/utils/getTypeArguments.ts b/packages/react-docgen/src/utils/getTypeArguments.ts new file mode 100644 index 00000000000..07517da57cf --- /dev/null +++ b/packages/react-docgen/src/utils/getTypeArguments.ts @@ -0,0 +1,30 @@ +import type { NodePath } from '@babel/traverse'; +import type { + TSTypeParameterInstantiation, + TypeParameterInstantiation, +} from '@babel/types'; + +/** Reads type arguments from both Babel 7 and Babel 8 ASTs. */ +export default function getTypeArguments( + path: NodePath, +): NodePath< + InstanceType['node'] & + ( + | TSTypeParameterInstantiation + | TypeParameterInstantiation + | null + | undefined + ) +> { + return path.get( + 'typeArguments' in path.node ? 'typeArguments' : 'typeParameters', + ) as NodePath< + InstanceType['node'] & + ( + | TSTypeParameterInstantiation + | TypeParameterInstantiation + | null + | undefined + ) + >; +} diff --git a/packages/react-docgen/src/utils/getTypeFromReactComponent.ts b/packages/react-docgen/src/utils/getTypeFromReactComponent.ts index 028be7e28f7..5874488f9e9 100644 --- a/packages/react-docgen/src/utils/getTypeFromReactComponent.ts +++ b/packages/react-docgen/src/utils/getTypeFromReactComponent.ts @@ -3,6 +3,7 @@ import type Documentation from '../Documentation.js'; import getMemberValuePath from './getMemberValuePath.js'; import getTypeAnnotation from './getTypeAnnotation.js'; import getTypeParameters from './getTypeParameters.js'; +import getTypeArguments from './getTypeArguments.js'; import isReactComponentClass from './isReactComponentClass.js'; import isReactForwardRefCall from './isReactForwardRefCall.js'; import resolveGenericTypeAnnotation from './resolveGenericTypeAnnotation.js'; @@ -18,6 +19,8 @@ import type { TSTypeParameterDeclaration, TSTypeParameterInstantiation, TypeParameterDeclaration, + ClassDeclaration, + ClassExpression, TypeParameterInstantiation, VariableDeclarator, } from '@babel/types'; @@ -82,6 +85,37 @@ function findAssignedVariableType( return null; } +/** + * Finds the props type of a class extending a mixin call, e.g. + * `class X extends withFoo(React.Component) {}`. + */ +function getMixinSuperClassPropsPath( + classDefinition: NodePath, +): NodePath | null { + const superClass = classDefinition.get('superClass'); + + if (!superClass.isCallExpression()) return null; + + const [baseClass] = superClass.get('arguments'); + + if (!baseClass?.isTSInstantiationExpression()) return null; + + const expression = baseClass.get('expression'); + + if ( + !isReactBuiltinReference(expression, 'Component') && + !isReactBuiltinReference(expression, 'PureComponent') + ) { + return null; + } + + const typeParameters = getTypeArguments(baseClass); + + if (!typeParameters.hasNode()) return null; + + return typeParameters.get('params')[0] ?? null; +} + /** * Given an React component (stateless or class) tries to find * flow or TS types for the props. It may find multiple types. @@ -105,16 +139,25 @@ export default (componentDefinition: NodePath): NodePath[] => { } } } else { - const propsMemberPath = getMemberValuePath(componentDefinition, 'props'); + const mixinPropsPath = getMixinSuperClassPropsPath(componentDefinition); - if (!propsMemberPath) { - return []; - } + if (mixinPropsPath) { + typePaths.push(mixinPropsPath); + } else { + const propsMemberPath = getMemberValuePath( + componentDefinition, + 'props', + ); - const typeAnnotation = getTypeAnnotation(propsMemberPath.parentPath); + if (!propsMemberPath) { + return []; + } - if (typeAnnotation) { - typePaths.push(typeAnnotation); + const typeAnnotation = getTypeAnnotation(propsMemberPath.parentPath); + + if (typeAnnotation) { + typePaths.push(typeAnnotation); + } } } } else { diff --git a/packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap b/packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap deleted file mode 100644 index 9e4ece0c25a..00000000000 --- a/packages/react-docgen/tests/integration/__snapshots__/integration-test.ts.snap +++ /dev/null @@ -1,2165 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`integration > fixtures > processes component "class-without-id.tsx" without errors 1`] = ` -[ - { - "description": "", - "methods": [], - "props": { - "value": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_1.js" without errors 1`] = ` -[ - { - "description": "The is a component to test the document generation", - "displayName": "Component", - "methods": [], - }, -] -`; - -exports[`integration > fixtures > processes component "component_2.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "button", - "methods": [ - { - "docblock": null, - "modifiers": [ - "static", - "get", - ], - "name": "displayName", - "params": [], - "returns": null, - }, - { - "docblock": null, - "modifiers": [ - "static", - "get", - ], - "name": "defaultProps", - "params": [], - "returns": null, - }, - ], - "props": { - "type": { - "defaultValue": { - "computed": false, - "value": ""primary"", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_3.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Test", - "methods": [], - "props": { - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_4.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Parent", - "methods": [], - "props": { - "child": { - "description": "", - "required": true, - "type": { - "computed": true, - "name": "shape", - "value": "Child.propTypes", - }, - }, - "childExact": { - "description": "", - "required": true, - "type": { - "computed": true, - "name": "exact", - "value": "Child.propTypes", - }, - }, - "extendedChild": { - "description": "", - "required": true, - "type": { - "name": "shape", - "value": { - "adopted": { - "name": "bool", - "required": true, - }, - }, - }, - }, - "extendedChildExact": { - "description": "", - "required": true, - "type": { - "name": "exact", - "value": { - "adopted": { - "name": "bool", - "required": true, - }, - }, - }, - }, - "something": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_5.js" without errors 1`] = ` -[ - { - "childContext": { - "color": { - "required": false, - "type": { - "name": "string", - }, - }, - }, - "context": { - "config": { - "required": false, - "type": { - "name": "object", - }, - }, - }, - "description": "", - "displayName": "Button", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "defaultValue": { - "computed": false, - "value": "{}", - }, - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_6.js" without errors 1`] = ` -[ - { - "childContext": { - "color": { - "required": false, - "type": { - "name": "string", - }, - }, - }, - "context": { - "config": { - "required": false, - "type": { - "name": "object", - }, - }, - }, - "description": "", - "displayName": "Button", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "defaultValue": { - "computed": false, - "value": "{}", - }, - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_7.js" without errors 1`] = ` -[ - { - "description": "The is a component to test the document generation", - "displayName": "Component", - "methods": [], - }, -] -`; - -exports[`integration > fixtures > processes component "component_8.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Parent", - "methods": [ - { - "docblock": null, - "modifiers": [], - "name": "onChangeSlider", - "params": [ - { - "name": "[min, max]", - "optional": false, - "type": null, - }, - ], - "returns": null, - }, - ], - }, -] -`; - -exports[`integration > fixtures > processes component "component_9.js" without errors 1`] = ` -[ - { - "description": "Should be recognized as component.", - "displayName": "ExampleComponent", - "methods": [], - }, -] -`; - -exports[`integration > fixtures > processes component "component_10.js" without errors 1`] = ` -[ - { - "description": "React component that display current time at current location.", - "displayName": "Clock", - "methods": [ - { - "description": "Update clock state with new time", - "docblock": "Update clock state with new time", - "modifiers": [], - "name": "updateClock", - "params": [], - "returns": null, - }, - { - "description": "Parse current Date object", - "docblock": "Parse current Date object - -@returns {Object} currentTime - @returns {int} currentTime.hour - @returns {int} currentTime.minutes - @returns {string} currentTime.ampm "am" or "pm" - @returns {string} currentTime.dayOfWeek - @returns {string} currentTime.month - @returns {int} currentTime.date", - "modifiers": [], - "name": "getTime", - "params": [], - "returns": { - "description": "currentTime", - "type": { - "name": "Object", - }, - }, - }, - { - "description": "Update current clock for every 1 second", - "docblock": "Update current clock for every 1 second", - "modifiers": [], - "name": "setTimer", - "params": [], - "returns": null, - }, - ], - "props": { - "title": { - "description": "A text display current's user identity, - "Nobody" if no one is detected in the background, - "Hi, ..name" if an user is detected", - "required": false, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_11.js" without errors 1`] = ` -[ - { - "composes": [ - "OtherProps", - ], - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "fooProp": { - "description": "fooProp is spread in from a locally resolved type", - "flowType": { - "name": "string", - }, - "required": false, - }, - "prop1": { - "description": "The first prop", - "flowType": { - "name": "string", - }, - "required": true, - }, - "prop2": { - "description": "The second, covariant prop", - "flowType": { - "name": "number", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_12.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Paper", - "methods": [], - "props": { - "anchorOrigin": { - "defaultValue": { - "computed": false, - "value": "{ - vertical: 'top', - horizontal: 'left', -}", - }, - "description": "This is the point on the anchor where the popover's -\`anchorEl\` will attach to. This is not used when the -anchorReference is 'anchorPosition'. - -Options: -vertical: [top, center, bottom]; -horizontal: [left, center, right].", - "flowType": { - "name": "signature", - "raw": "{ - horizontal: 'left' | 'center' | 'right' | number, - vertical: 'top' | 'center' | 'bottom' | number, -}", - "signature": { - "properties": [ - { - "key": "horizontal", - "value": { - "elements": [ - { - "name": "literal", - "value": "'left'", - }, - { - "name": "literal", - "value": "'center'", - }, - { - "name": "literal", - "value": "'right'", - }, - { - "name": "number", - }, - ], - "name": "union", - "raw": "'left' | 'center' | 'right' | number", - "required": true, - }, - }, - { - "key": "vertical", - "value": { - "elements": [ - { - "name": "literal", - "value": "'top'", - }, - { - "name": "literal", - "value": "'center'", - }, - { - "name": "literal", - "value": "'bottom'", - }, - { - "name": "number", - }, - ], - "name": "union", - "raw": "'top' | 'center' | 'bottom' | number", - "required": true, - }, - }, - ], - }, - "type": "object", - }, - "required": false, - }, - "children": { - "description": "@ignore", - "flowType": { - "name": "Node", - }, - "required": false, - }, - "classes": { - "description": "Useful to extend the style applied to components.", - "flowType": { - "name": "Object", - }, - "required": false, - }, - "component": { - "defaultValue": { - "computed": false, - "value": "'div'", - }, - "description": "The component used for the root node. -This currently has to be flow cast in defaultProps as of flow 0.59.0", - "flowType": { - "name": "ElementType", - }, - "required": false, - }, - "elevation": { - "defaultValue": { - "computed": false, - "value": "2", - }, - "description": "Shadow depth, corresponds to \`dp\` in the spec. -It's accepting values between 0 and 24 inclusive.", - "flowType": { - "name": "number", - }, - "required": false, - }, - "labelRowsPerPage": { - "defaultValue": { - "computed": false, - "value": "'Rows per page:'", - }, - "description": "Useful to customize the rows per page label. Invoked with a \`{ from, to, count, page }\` -object.", - "flowType": { - "name": "Node", - }, - "required": false, - }, - "timeout": { - "defaultValue": { - "computed": false, - "value": "300", - }, - "description": "The duration for the transition, in milliseconds. -You may specify a single timeout for all transitions, or individually with an object. - -Set to 'auto' to automatically calculate transition time based on height.", - "flowType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - "required": false, - }, - "transition": { - "description": "Transition component.", - "flowType": { - "elements": [ - { - "name": "unknown", - }, - ], - "name": "ComponentType", - "raw": "ComponentType<*>", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_13.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "RootComponent": { - "description": "", - "flowType": { - "name": "ReactElementType", - "raw": "React.ElementType", - }, - "required": false, - }, - "align": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""left"", - }, - { - "name": "literal", - "value": ""center"", - }, - { - "name": "literal", - "value": ""right"", - }, - { - "name": "literal", - "value": ""justify"", - }, - ], - "name": "union", - "raw": ""left" | "center" | "right" | "justify"", - }, - "required": false, - }, - "capitalize": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "center": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "children": { - "description": "", - "flowType": { - "name": "ReactNode", - "raw": "React.Node", - }, - "required": false, - }, - "className": { - "description": "", - "flowType": { - "name": "string", - }, - "required": false, - }, - "color": { - "description": "", - "flowType": { - "name": "string", - }, - "required": false, - }, - "justify": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leading": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""none"", - }, - { - "name": "literal", - "value": ""tight"", - }, - { - "name": "literal", - "value": ""normal"", - }, - { - "name": "literal", - "value": ""loose"", - }, - ], - "name": "union", - "raw": ""none" | "tight" | "normal" | "loose"", - }, - "required": false, - }, - "leadingLoose": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leadingNone": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leadingNormal": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "leadingTight": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "left": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "lowercase": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "muted": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "right": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "size": { - "description": "", - "flowType": { - "name": "string", - }, - "required": false, - }, - "tracking": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""tight"", - }, - { - "name": "literal", - "value": ""normal"", - }, - { - "name": "literal", - "value": ""wide"", - }, - ], - "name": "union", - "raw": ""tight" | "normal" | "wide"", - }, - "required": false, - }, - "trackingNormal": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "trackingTight": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "trackingWide": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "transform": { - "description": "", - "flowType": { - "elements": [ - { - "name": "literal", - "value": ""lowercase"", - }, - { - "name": "literal", - "value": ""uppercase"", - }, - { - "name": "literal", - "value": ""capitalize"", - }, - ], - "name": "union", - "raw": ""lowercase" | "uppercase" | "capitalize"", - }, - "required": false, - }, - "uppercase": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - "wrap": { - "description": "", - "flowType": { - "name": "boolean", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_14.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "UncoloredView", - "methods": [], - "props": { - "color": { - "description": "", - "flowType": { - "name": "string", - "nullable": true, - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_15.js" without errors 1`] = ` -[ - { - "composes": [ - "BarProps", - "BarProps2", - "BarProps3", - ], - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "other": { - "description": "", - "flowType": { - "name": "literal", - "value": "'a'", - }, - "required": true, - }, - "other2": { - "description": "", - "flowType": { - "name": "literal", - "value": "'b'", - }, - "required": true, - }, - "other3": { - "description": "", - "flowType": { - "name": "literal", - "value": "'c'", - }, - "required": true, - }, - "other4": { - "description": "", - "flowType": { - "name": "literal", - "value": "'g'", - }, - "required": true, - }, - "other5": { - "description": "", - "flowType": { - "name": "literal", - "value": "'f'", - }, - "required": true, - }, - "somePropOverride": { - "description": "", - "flowType": { - "name": "literal", - "value": "'baz'", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_16.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "bar": { - "defaultValue": { - "computed": false, - "value": "null", - }, - "description": "This does something.", - "required": false, - "type": { - "name": "custom", - "raw": "PropTypes.node", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_17.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Foo", - "methods": [], - "props": { - "exactProp": { - "description": "", - "required": false, - "type": { - "name": "exact", - "value": { - "c": { - "description": "Comment for property c", - "name": "string", - "required": false, - }, - "d": { - "name": "number", - "required": false, - }, - }, - }, - }, - "oneOfTypeProp": { - "description": "", - "required": false, - "type": { - "name": "union", - "value": [ - { - "description": "Comment for type string", - "name": "string", - }, - { - "name": "number", - }, - ], - }, - }, - "shapeProp": { - "description": "", - "required": false, - "type": { - "name": "shape", - "value": { - "a": { - "description": "Comment for property a", - "name": "string", - "required": false, - }, - "b": { - "name": "number", - "required": false, - }, - }, - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_18.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "UncoloredView", - "methods": [], - "props": { - "color": { - "description": "", - "flowType": { - "name": "string", - "nullable": true, - }, - "required": false, - "type": { - "name": "string", - }, - }, - "id": { - "defaultValue": { - "computed": false, - "value": "'test-forward-ref-default'", - }, - "description": "", - "required": false, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_19.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Component", - "methods": [], - "props": { - "data": { - "description": "", - "flowType": { - "elements": [ - { - "name": "mixed", - }, - ], - "name": "Array", - "raw": "Array", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_20.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Button", - "methods": [], - "props": { - "@computed#children": { - "defaultValue": { - "computed": false, - "value": ""default"", - }, - "description": "This is a test", - "required": false, - "type": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_21.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "required": true, - "tsType": { - "name": "number", - }, - }, - "baz": { - "description": "Complex union prop", - "required": true, - "tsType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - }, - "foo": { - "description": "Optional prop", - "required": false, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_22.tsx" without errors 1`] = ` -[ - { - "description": "This is a TypeScript function component", - "displayName": "TSFunctionComponent", - "methods": [], - "props": { - "align": { - "description": "", - "required": false, - "tsType": { - "elements": [ - { - "name": "literal", - "value": ""left"", - }, - { - "name": "literal", - "value": ""center"", - }, - { - "name": "literal", - "value": ""right"", - }, - { - "name": "literal", - "value": ""justify"", - }, - ], - "name": "union", - "raw": ""left" | "center" | "right" | "justify"", - }, - }, - "center": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - "justify": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - "left": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - "position": { - "description": "position doc", - "required": true, - "tsType": { - "name": "signature", - "raw": "{ - /** - * x coordinate doc - */ - x: number, - /** - * y coordinate doc - */ - y: number -}", - "signature": { - "properties": [ - { - "description": "x coordinate doc", - "key": "x", - "value": { - "name": "number", - "required": true, - }, - }, - { - "description": "y coordinate doc", - "key": "y", - "value": { - "name": "number", - "required": true, - }, - }, - ], - }, - "type": "object", - }, - }, - "right": { - "description": "", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_23.tsx" without errors 1`] = ` -[ - { - "composes": [ - "OtherProps", - ], - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "required": true, - "tsType": { - "name": "number", - }, - }, - "baz": { - "description": "Complex union prop", - "required": true, - "tsType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - }, - "foo": { - "description": "Optional prop", - "required": false, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_24.js" without errors 1`] = ` -[ - { - "composes": [ - "OtherProps", - ], - "description": "This is a flow class component with an interface as props", - "displayName": "FlowComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "flowType": { - "name": "number", - }, - "required": true, - }, - "baz": { - "description": "Complex union prop", - "flowType": { - "elements": [ - { - "name": "number", - }, - { - "name": "signature", - "raw": "{ enter?: number, exit?: number }", - "signature": { - "properties": [ - { - "key": "enter", - "value": { - "name": "number", - "required": false, - }, - }, - { - "key": "exit", - "value": { - "name": "number", - "required": false, - }, - }, - ], - }, - "type": "object", - }, - { - "name": "literal", - "value": "'auto'", - }, - ], - "name": "union", - "raw": "number | { enter?: number, exit?: number } | 'auto'", - }, - "required": true, - }, - "foo": { - "description": "Optional prop", - "flowType": { - "name": "string", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_25.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "required": true, - "tsType": { - "elements": [ - { - "name": "Child", - }, - ], - "name": "Array", - "raw": "Array", - }, - }, - "baz": { - "description": "Complex union prop", - "required": true, - "tsType": { - "name": "number", - }, - }, - "foo": { - "description": "Optional prop", - "required": false, - "tsType": { - "name": "Child", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_26.js" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "FlowComponent", - "methods": [], - "props": { - "bar": { - "description": "Required prop", - "flowType": { - "elements": [ - { - "name": "Child", - }, - ], - "name": "Array", - "raw": "Array", - }, - "required": true, - }, - "baz": { - "description": "Complex union prop", - "flowType": { - "name": "number", - }, - "required": true, - }, - "foo": { - "description": "Optional prop", - "flowType": { - "name": "Child", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_27.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript class component", - "displayName": "TSComponent", - "methods": [ - { - "description": "This is a method", - "docblock": "This is a method", - "modifiers": [], - "name": "foo", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - { - "description": "This is a public method", - "docblock": "This is a public method", - "modifiers": [], - "name": "bar", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - ], - "props": { - "foo": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_28.tsx" without errors 1`] = ` -[ - { - "description": "Example component description", - "displayName": "ABC", - "methods": [], - "props": { - "foo": { - "defaultValue": { - "computed": false, - "value": "true", - }, - "description": "Example prop description", - "required": false, - "tsType": { - "name": "boolean", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_29.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "prop": { - "description": "", - "flowType": { - "name": "T", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_30.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "prop": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_31.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "prop": { - "description": "", - "flowType": { - "name": "T", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_32.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "Segments", - "methods": [ - { - "docblock": null, - "modifiers": [], - "name": "foo", - "params": [ - { - "name": "props", - "optional": false, - "type": { - "alias": "Props", - "name": "signature", - "raw": "{ - segments: Array, -}", - "signature": { - "properties": [ - { - "key": "segments", - "value": { - "elements": [ - { - "name": "T", - }, - ], - "name": "Array", - "raw": "Array", - "required": true, - }, - }, - ], - }, - "type": "object", - }, - }, - ], - "returns": null, - }, - ], - "props": { - "segments": { - "description": "", - "flowType": { - "elements": [ - { - "name": "T", - }, - ], - "name": "Array", - "raw": "Array", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_33.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript component with imported prop types", - "displayName": "ImportedExtendedComponent", - "methods": [], - "props": { - "bar": { - "description": "", - "required": true, - "tsType": { - "name": "number", - }, - }, - "foo": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_34.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "CustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "color": { - "description": "", - "required": false, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_35.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_36.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_37.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_38.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "children": { - "description": "", - "required": true, - "type": { - "name": "string", - }, - }, - "onClick": { - "description": "", - "required": false, - "type": { - "name": "func", - }, - }, - "style": { - "description": "", - "required": false, - "type": { - "name": "object", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_39.tsx" without errors 1`] = ` -[ - { - "description": "This is a typescript component with imported prop types", - "displayName": "ImportedComponent", - "methods": [], - "props": { - "foo": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_40.js" without errors 1`] = ` -[ - { - "description": "", - "displayName": "SuperDuperCustomButton", - "methods": [], - "props": { - "size": { - "defaultValue": { - "computed": true, - "value": "Sizes.EXTRA_LARGE", - }, - "description": "", - "required": false, - "type": { - "computed": true, - "name": "enum", - "value": "Object.values(Sizes)", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_41.tsx" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MyComponent", - "methods": [], - "props": { - "value": { - "description": "String value of a number", - "required": false, - "tsType": { - "name": "STRING_VALS[number]", - "raw": "typeof STRING_VALS[number]", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_42.js" without errors 1`] = ` -[ - { - "description": "", - "methods": [], - "props": { - "foo": { - "defaultValue": { - "computed": false, - "value": "'bar'", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "component_43.tsx" without errors 1`] = ` -[ - { - "description": "", - "displayName": "MenuItem", - "methods": [], - "props": { - "children": { - "description": "Menu item contents.", - "required": false, - "type": { - "name": "node", - }, - }, - "classes": { - "description": "Override or extend the styles applied to the component. See CSS API below for more details.", - "required": false, - "type": { - "name": "object", - }, - }, - "component": { - "defaultValue": { - "computed": false, - "value": "'li'", - }, - "required": false, - }, - "disableGutters": { - "defaultValue": { - "computed": false, - "value": "false", - }, - "required": false, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "flow-export-type.js" without errors 1`] = ` -[ - { - "description": "This is a Flow class component", - "displayName": "FlowComponent", - "methods": [ - { - "docblock": null, - "modifiers": [], - "name": "foo", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - { - "docblock": null, - "modifiers": [], - "name": "bar", - "params": [ - { - "name": "a", - "optional": false, - "type": { - "name": "string", - }, - }, - ], - "returns": { - "type": { - "name": "string", - }, - }, - }, - ], - "props": { - "foo": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "flow-import-type.js" without errors 1`] = ` -[ - { - "description": "This is a Flow component with imported prop types", - "displayName": "ImportedComponent", - "methods": [], - "props": { - "foo": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "flow-spread-import-type.js" without errors 1`] = ` -[ - { - "description": "This is a Flow component with imported prop types", - "displayName": "ImportedExtendedComponent", - "methods": [], - "props": { - "bar": { - "description": "", - "flowType": { - "name": "number", - }, - "required": true, - }, - "foo": { - "description": "", - "flowType": { - "name": "string", - }, - "required": true, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "namespace-export.tsx" without errors 1`] = ` -[ - { - "description": "", - "methods": [], - "props": { - "value": { - "description": "", - "required": true, - "tsType": { - "name": "string", - }, - }, - }, - }, -] -`; - -exports[`integration > fixtures > processes component "test-all-imports.tsx" without errors 1`] = ` -[ - { - "description": "This is a TS component with imported stuff", - "displayName": "ImportedExtendedComponent", - "methods": [], - "props": { - "x": { - "defaultValue": { - "computed": false, - "value": ""string"", - }, - "required": false, - }, - "y": { - "defaultValue": { - "computed": false, - "value": "'otherstring'", - }, - "required": false, - }, - }, - }, -] -`; diff --git a/packages/react-docgen/tests/integration/integration-test.ts b/packages/react-docgen/tests/integration/integration-test.ts index 48d0ba83ded..22321fd7256 100644 --- a/packages/react-docgen/tests/integration/integration-test.ts +++ b/packages/react-docgen/tests/integration/integration-test.ts @@ -1,40 +1,26 @@ -import fs from 'fs'; -import { dirname, join } from 'path'; import { describe, expect, test } from 'vitest'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; import { parse, makeFsImporter } from '../../src/main'; -import { fileURLToPath } from 'url'; describe('integration', () => { - describe('fixtures', () => { - const fixturePath = join( - dirname(fileURLToPath(import.meta.url)), - '__fixtures__', - ); - const fileNames = fs.readdirSync(fixturePath, { withFileTypes: true }); + for (const integrationCase of loadIntegrationCases()) { + test(integrationCase.id, () => { + const run = () => + parse(integrationCase.source, { + importer: makeFsImporter(), + babelOptions: { + filename: integrationCase.filename, + babelrc: false, + }, + }); - for (const entry of fileNames) { - if (entry.isDirectory()) { - continue; + if (integrationCase.error) { + expect(run).toThrow( + expect.objectContaining({ code: integrationCase.error.code }), + ); + } else { + expect(run()).toEqual(integrationCase.output); } - const name = entry.name; - - const filePath = join(fixturePath, name); - const fileContent = fs.readFileSync(filePath, 'utf8'); - - test(`processes component "${name}" without errors`, () => { - let result; - - expect(() => { - result = parse(fileContent, { - importer: makeFsImporter(), - babelOptions: { - filename: filePath, - babelrc: false, - }, - }); - }).not.toThrow(); - expect(result).toMatchSnapshot(); - }); - } - }); + }); + } }); diff --git a/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts b/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts deleted file mode 100644 index 6e337ef54ec..00000000000 --- a/packages/react-docgen/tests/integration/parenthesized-function-type-test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, test } from 'vitest'; -import { parse } from '../../src/main'; - -describe('TypeScript parenthesized function types', () => { - test('preserves a function type inside a union', () => { - const [component] = parse( - ` - interface Props { - name: (() => string) | undefined; - } - - export const MyComponent = ({ name }: Props) =>
; - `, - { - babelOptions: { filename: 'component.tsx' }, - }, - ); - - expect(component.props?.name?.tsType).toMatchObject({ - name: 'union', - elements: [ - { - name: 'signature', - type: 'function', - signature: { arguments: [], return: { name: 'string' } }, - }, - { name: 'undefined' }, - ], - }); - }); -}); diff --git a/packages/react-docgen/vitest.config.ts b/packages/react-docgen/vitest.config.ts index 477c4ebbf79..03499cbb3db 100644 --- a/packages/react-docgen/vitest.config.ts +++ b/packages/react-docgen/vitest.config.ts @@ -10,9 +10,20 @@ export default defineConfig({ }, coverage: { include: ['src/**'], - exclude: ['**/__mocks__/**', '**/__tests__/**'], + exclude: [ + '**/__mocks__/**', + '**/__snapshots__/**', + '**/__tests__/**', + '**/*-test.ts', + ], provider: 'v8', reporter: ['text', 'lcov'], + thresholds: { + statements: 84, + branches: 74, + functions: 94, + lines: 84, + }, }, }, }); diff --git a/packages/typescript/package.json b/packages/typescript/package.json new file mode 100644 index 00000000000..9709189b7a6 --- /dev/null +++ b/packages/typescript/package.json @@ -0,0 +1,37 @@ +{ + "name": "@react-docgen/typescript", + "version": "0.0.0", + "description": "TypeScript parser adapter for react-docgen.", + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "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/reactjs/react-docgen.git", + "directory": "packages/typescript" + }, + "type": "module", + "files": [ + "dist" + ], + "engines": { + "node": "^22.13.0 || ^24.11.0 || >=26.13.0" + }, + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "rimraf dist/ && tsc", + "test": "vitest run" + }, + "dependencies": { + "@react-docgen/core": "workspace:*", + "@typescript-eslint/typescript-estree": "8.67.0", + "@typescript-eslint/visitor-keys": "8.67.0" + }, + "devDependencies": { + "@react-docgen/babel": "workspace:*", + "@react-docgen-internal/integration-tests": "workspace:*" + }, + "license": "MIT" +} diff --git a/packages/typescript/src/__tests__/parse-test.ts b/packages/typescript/src/__tests__/parse-test.ts new file mode 100644 index 00000000000..76b574860a8 --- /dev/null +++ b/packages/typescript/src/__tests__/parse-test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from 'vitest'; +import { + isIdentifier, + isProgram, + traverse, + type AstNode, +} from '@react-docgen/core'; +import { parser } from '../index.js'; + +describe('@react-docgen/typescript', () => { + test.each([ + [ + 'input.js', + "import value from './value.js'; export const result = value;", + 'ImportDeclaration', + ], + ['input.jsx', 'export const View = () =>
;', 'JSXElement'], + [ + 'input.ts', + 'export type Props = { value: string };', + 'TSTypeAliasDeclaration', + ], + [ + 'input.tsx', + 'export function View(props: { value: string }) { return
{props.value}
; }', + 'TSPropertySignature', + ], + ])('normalizes and traverses %s', (testFilename, code, expectedType) => { + const ast = parser.parse({ code, filename: testFilename }); + const nodeTypes: string[] = []; + + traverse( + ast, + parser.visitorKeys, + { + enter(path, state) { + state.push(path.node.type); + }, + }, + nodeTypes, + ); + + expect(isProgram(ast)).toBe(true); + expect(nodeTypes).toContain('ExportNamedDeclaration'); + expect(nodeTypes).toContain(expectedType); + }); + + test('normalizes parser nodes behind core guards', () => { + const ast = parser.parse({ + code: 'const answer = 42;', + filename: 'input.ts', + }); + const declaration = (ast.body as AstNode[])[0]; + const identifier = (declaration.declarations as AstNode[])[0] + ?.id as AstNode; + + expect(isIdentifier(identifier, { name: 'answer' })).toBe(true); + }); +}); diff --git a/packages/typescript/src/__tests__/testUtils.ts b/packages/typescript/src/__tests__/testUtils.ts new file mode 100644 index 00000000000..59cc26526be --- /dev/null +++ b/packages/typescript/src/__tests__/testUtils.ts @@ -0,0 +1,23 @@ +import { + ProjectContext, + type FileState, + type Importer, +} from '@react-docgen/core'; +import parser from '../parser.js'; + +export default function parseFile( + code: string, + filename = 'component.tsx', + importer?: Importer, +): FileState { + const project = new ProjectContext({ + importer: + importer ?? + (() => { + throw new Error('Unexpected import.'); + }), + selectParser: () => parser, + }); + + return project.parse({ code, filename }); +} diff --git a/packages/typescript/src/handlers/typescriptPropsHandler.ts b/packages/typescript/src/handlers/typescriptPropsHandler.ts new file mode 100644 index 00000000000..e041d303f7c --- /dev/null +++ b/packages/typescript/src/handlers/typescriptPropsHandler.ts @@ -0,0 +1,76 @@ +import { + getDescription, + getParameterDefaults, + isArrowFunctionExpression, + isClassDeclaration, + isClassExpression, + isFunctionDeclaration, + isFunctionExpression, + isIdentifier, + isLiteral, + isObjectPattern, + isTSPropertySignature, + isTSTypeAnnotation, + type Handler, +} from '@react-docgen/core'; +import getComposedTypeNames from '../utils/getComposedTypeNames.js'; +import getClassPropsType from '../utils/getClassPropsType.js'; +import getPropsMembers from '../utils/getPropsMembers.js'; +import getTSType from '../utils/getTSType.js'; + +const typescriptPropsHandler: Handler = (documentation, path, file) => { + const parameter = + isFunctionDeclaration(path.node) || + isFunctionExpression(path.node) || + isArrowFunctionExpression(path.node) + ? path.node.params[0] + : undefined; + const annotation = parameter + ? (isIdentifier(parameter) || isObjectPattern(parameter)) && + parameter.typeAnnotation && + isTSTypeAnnotation(parameter.typeAnnotation) + ? parameter.typeAnnotation.typeAnnotation + : null + : isClassDeclaration(path.node) || isClassExpression(path.node) + ? getClassPropsType(file, path.node) + : null; + const propsMembers = getPropsMembers(file, annotation); + const composes = getComposedTypeNames(file, annotation); + const defaults = getParameterDefaults( + parameter && isObjectPattern(parameter) ? parameter : null, + ); + + if (composes.length > 0) documentation.composes = composes; + if (propsMembers.length === 0) return; + + documentation.props = {}; + + for (const member of propsMembers) { + if (!isTSPropertySignature(member) || !isIdentifier(member.key)) continue; + const tsType = getTSType(file, member.typeAnnotation); + + if (!tsType) continue; + const defaultNode = defaults.get(member.key.name); + + documentation.props[member.key.name] = { + description: getDescription(file, member), + required: !member.optional, + tsType, + ...(defaultNode && isLiteral(defaultNode) + ? { + defaultValue: { + computed: false, + value: + defaultNode.raw ?? + file.source.code.slice( + defaultNode.range[0], + defaultNode.range[1], + ), + }, + } + : {}), + }; + } +}; + +export default typescriptPropsHandler; diff --git a/packages/typescript/src/index.ts b/packages/typescript/src/index.ts new file mode 100644 index 00000000000..915ae11231a --- /dev/null +++ b/packages/typescript/src/index.ts @@ -0,0 +1,45 @@ +import { + componentHandler, + contextHandler, + createDocgen, + createMethodHandler, + defaultPropsHandler, + propTypesHandler, + resolveComponentDefinitions, + type ComponentDocumentation, + type Importer, +} from '@react-docgen/core'; +import typescriptPropsHandler from './handlers/typescriptPropsHandler.js'; +import parser from './parser.js'; +import getTSType from './utils/getTSType.js'; + +export { + default as parser, + visitorKeys, + type ParserOptions, +} from './parser.js'; + +export interface ParseOptions { + filename?: string; + importer?: Importer; +} + +const docgen = createDocgen({ + handlers: [ + componentHandler, + typescriptPropsHandler, + propTypesHandler, + defaultPropsHandler, + contextHandler, + createMethodHandler(getTSType), + ], + parser, + resolver: resolveComponentDefinitions, +}); + +export function parse( + code: string, + { filename = 'component.tsx', importer }: ParseOptions = {}, +): ComponentDocumentation[] { + return docgen(code, { filename, importer }); +} diff --git a/packages/typescript/src/normalize.ts b/packages/typescript/src/normalize.ts new file mode 100644 index 00000000000..fc66776153e --- /dev/null +++ b/packages/typescript/src/normalize.ts @@ -0,0 +1,9 @@ +import { isAstNode, type AstNode } from '@react-docgen/core'; + +export default function normalize(node: unknown): AstNode { + if (!isAstNode(node)) { + throw new TypeError('Parser did not return an AST node.'); + } + + return node; +} diff --git a/packages/typescript/src/parser.ts b/packages/typescript/src/parser.ts new file mode 100644 index 00000000000..dd54be0416d --- /dev/null +++ b/packages/typescript/src/parser.ts @@ -0,0 +1,25 @@ +import { parse as parseTypeScript } from '@typescript-eslint/typescript-estree'; +import { visitorKeys as typescriptVisitorKeys } from '@typescript-eslint/visitor-keys'; +import type { Parser, VisitorKeys } from '@react-docgen/core'; +import normalize from './normalize.js'; + +export const visitorKeys: VisitorKeys = typescriptVisitorKeys; +export type ParserOptions = NonNullable[1]>; + +const parser: Parser = { + parse(source, options) { + return normalize( + parseTypeScript(source.code, { + comment: true, + filePath: source.filename, + jsx: true, + loc: true, + range: true, + ...(options as ParserOptions | undefined), + }), + ); + }, + visitorKeys, +}; + +export default parser; diff --git a/packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts b/packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts new file mode 100644 index 00000000000..b385cde7c40 --- /dev/null +++ b/packages/typescript/src/resolver/__tests__/findExportedDefinitions-test.ts @@ -0,0 +1,21 @@ +import { findExportedDefinitions } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns supported named and default declarations only', () => { + const definitions = findExportedDefinitions( + parseFile(` + function Internal() {} + export function Named() {} + export default class Default {} + class CommonJs {} + exports.CommonJs = CommonJs; + `), + ); + + expect(definitions.map(({ node }) => node.type)).toEqual([ + 'FunctionDeclaration', + 'ClassDeclaration', + 'ClassDeclaration', + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts b/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts new file mode 100644 index 00000000000..201c8e2521a --- /dev/null +++ b/packages/typescript/src/utils/__tests__/findImperativeHandleMethods-test.ts @@ -0,0 +1,21 @@ +import { + findExportedDefinitions, + findImperativeHandleMethods, +} from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds methods exposed through useImperativeHandle', () => { + const file = parseFile(` + import { forwardRef, useImperativeHandle } from 'react'; + export const Input = forwardRef(function Input(props, ref) { + useImperativeHandle(ref, () => ({ focus() {}, reset() {} })); + }); + `); + const [definition] = findExportedDefinitions(file); + + expect(definition?.node.type).toBe('FunctionExpression'); + expect( + definition && findImperativeHandleMethods(file, definition), + ).toHaveLength(2); +}); diff --git a/packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts b/packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts new file mode 100644 index 00000000000..53b49cf0d23 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/findTopLevelDefinition-test.ts @@ -0,0 +1,15 @@ +import { findTopLevelDefinition } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds named top-level functions and classes', () => { + const file = parseFile('function View() {} class Panel {}'); + + expect(findTopLevelDefinition(file, 'View')?.node.type).toBe( + 'FunctionDeclaration', + ); + expect(findTopLevelDefinition(file, 'Panel')?.node.type).toBe( + 'ClassDeclaration', + ); + expect(findTopLevelDefinition(file, 'Missing')).toBeNull(); +}); diff --git a/packages/typescript/src/utils/__tests__/getBody-test.ts b/packages/typescript/src/utils/__tests__/getBody-test.ts new file mode 100644 index 00000000000..34ca50471e6 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getBody-test.ts @@ -0,0 +1,12 @@ +import { getBody } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns program body paths', () => { + const body = getBody(parseFile('const first = 1; const second = 2;')); + + expect(body.map(({ node }) => node.type)).toEqual([ + 'VariableDeclaration', + 'VariableDeclaration', + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts b/packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts new file mode 100644 index 00000000000..3ade6718adf --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getClassStaticValue-test.ts @@ -0,0 +1,19 @@ +import { expect, test } from 'vitest'; +import { + findExportedDefinitions, + getClassStaticValue, + isLiteral, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('resolves a static getter return value', () => { + const file = parseFile( + 'const name = "Button"; export default class View { static get displayName() { return name; } }', + ); + const [definition] = findExportedDefinitions(file); + const value = definition + ? getClassStaticValue(file, definition, 'displayName') + : null; + + expect(value && isLiteral(value) ? value.value : null).toBe('Button'); +}); diff --git a/packages/typescript/src/utils/__tests__/getComponentDescription-test.ts b/packages/typescript/src/utils/__tests__/getComponentDescription-test.ts new file mode 100644 index 00000000000..0caad98cb30 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getComponentDescription-test.ts @@ -0,0 +1,19 @@ +import { + findExportedDefinitions, + getComponentDescription, +} from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('reads the docblock above a wrapped variable component', () => { + const file = parseFile(` + /** Wrapped component. */ + const Component = memo(forwardRef(() => null)); + export default Component; + `); + const [definition] = findExportedDefinitions(file); + + expect(definition && getComponentDescription(file, definition)).toBe( + 'Wrapped component.', + ); +}); diff --git a/packages/typescript/src/utils/__tests__/getComponentName-test.ts b/packages/typescript/src/utils/__tests__/getComponentName-test.ts new file mode 100644 index 00000000000..808c43de237 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getComponentName-test.ts @@ -0,0 +1,10 @@ +import { findTopLevelDefinition, getComponentName } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns declaration names', () => { + const file = parseFile('function View() {}'); + const definition = findTopLevelDefinition(file, 'View'); + + expect(definition && getComponentName(definition)).toBe('View'); +}); diff --git a/packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts b/packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts new file mode 100644 index 00000000000..4dd3c8e78ea --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getComposedTypeNames-test.ts @@ -0,0 +1,24 @@ +import { expect, test } from 'vitest'; +import { isTSTypeReference, type AstNode } from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; +import getComposedTypeNames from '../getComposedTypeNames.js'; + +test('reports only unresolved interface compositions', () => { + const file = parseFile( + 'interface Local {} interface Props extends Local, External {} function View(props: Props) {}', + ); + const fn = file.ast.body[2]; + const annotation = + fn?.params && Array.isArray(fn.params) + ? fn.params[0]?.typeAnnotation?.typeAnnotation + : null; + + expect( + annotation && + typeof annotation === 'object' && + 'type' in annotation && + isTSTypeReference(annotation as AstNode) + ? getComposedTypeNames(file, annotation as AstNode) + : [], + ).toEqual(['External']); +}); diff --git a/packages/typescript/src/utils/__tests__/getDescription-test.ts b/packages/typescript/src/utils/__tests__/getDescription-test.ts new file mode 100644 index 00000000000..7aac91d5265 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getDescription-test.ts @@ -0,0 +1,18 @@ +import { getBody, getDescription } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns only adjacent JSDoc descriptions', () => { + const file = parseFile( + '/** Component description. */\nexport function View() {}', + ); + const [declaration] = getBody(file); + + expect(declaration).toBeDefined(); + + if (declaration) { + expect(getDescription(file, declaration.node)).toBe( + 'Component description.', + ); + } +}); diff --git a/packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts b/packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts new file mode 100644 index 00000000000..01dccf24b0f --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getExplicitDisplayName-test.ts @@ -0,0 +1,13 @@ +import { getExplicitDisplayName } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds literal display name assignments', () => { + const file = parseFile(` + export function View() {} + View.displayName = 42; + `); + + expect(getExplicitDisplayName(file, 'View')).toBe(42); + expect(getExplicitDisplayName(file, 'Other')).toBeUndefined(); +}); diff --git a/packages/typescript/src/utils/__tests__/getMemberName-test.ts b/packages/typescript/src/utils/__tests__/getMemberName-test.ts new file mode 100644 index 00000000000..b909b21ead0 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getMemberName-test.ts @@ -0,0 +1,28 @@ +import { getBody, getMemberName } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('returns dotted member names', () => { + const file = parseFile('PropTypes.string.isRequired;'); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + + expect(expression && !Array.isArray(expression)).toBeTruthy(); + expect( + expression && !Array.isArray(expression) + ? getMemberName(expression.node) + : null, + ).toBe('PropTypes.string.isRequired'); +}); + +test('returns identifier names', () => { + const file = parseFile('useImperativeHandle();'); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + const callee = + expression && !Array.isArray(expression) ? expression.get('callee') : null; + + expect( + callee && !Array.isArray(callee) ? getMemberName(callee.node) : null, + ).toBe('useImperativeHandle'); +}); diff --git a/packages/typescript/src/utils/__tests__/getObjectProperties-test.ts b/packages/typescript/src/utils/__tests__/getObjectProperties-test.ts new file mode 100644 index 00000000000..fe3efa40f25 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getObjectProperties-test.ts @@ -0,0 +1,24 @@ +import { expect, test } from 'vitest'; +import { + getBody, + getObjectProperties, + isExpressionStatement, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('flattens local object spreads', () => { + const file = parseFile(` + const shared = { first: 1 }; + ({ ...shared, second: 2 }); + `); + const statement = getBody(file).at(-1); + + expect(statement && isExpressionStatement(statement.node)).toBe(true); + if (!statement || !isExpressionStatement(statement.node)) return; + + expect( + getObjectProperties(file, statement.node.expression).map( + (property) => property.key.type === 'Identifier' && property.key.name, + ), + ).toEqual(['first', 'second']); +}); diff --git a/packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts b/packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts new file mode 100644 index 00000000000..46a31b26945 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getParameterDefaults-test.ts @@ -0,0 +1,32 @@ +import { + findExportedDefinitions, + getParameterDefaults, + isFunctionDeclaration, + isObjectPattern, +} from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('collects destructured parameter defaults', () => { + const [definition] = findExportedDefinitions( + parseFile('export function View({ label = "Save", count }) {}'), + ); + + expect(definition).toBeDefined(); + + if (!definition || !isFunctionDeclaration(definition.node)) { + return; + } + + const [parameter] = definition.node.params; + + expect(parameter && isObjectPattern(parameter)).toBe(true); + + if (!parameter || !isObjectPattern(parameter)) { + return; + } + + expect([...getParameterDefaults(parameter)]).toEqual([ + ['label', expect.objectContaining({ type: 'Literal', value: 'Save' })], + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/getPropType-test.ts b/packages/typescript/src/utils/__tests__/getPropType-test.ts new file mode 100644 index 00000000000..05fc79078c6 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getPropType-test.ts @@ -0,0 +1,35 @@ +import { getBody, getPropType } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('extracts required built-in PropTypes', () => { + const file = parseFile('PropTypes.string.isRequired;'); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + + expect( + expression && !Array.isArray(expression) + ? getPropType(expression.node) + : null, + ).toEqual({ required: true, type: { name: 'string' } }); +}); + +test('extracts nested PropTypes calls', () => { + const file = parseFile( + 'PropTypes.oneOfType([PropTypes.string, PropTypes.number]);', + ); + const [statement] = getBody(file); + const expression = statement?.get('expression'); + + expect( + expression && !Array.isArray(expression) + ? getPropType(expression.node) + : null, + ).toEqual({ + required: false, + type: { + name: 'union', + value: [{ name: 'string' }, { name: 'number' }], + }, + }); +}); diff --git a/packages/typescript/src/utils/__tests__/getPropertyName-test.ts b/packages/typescript/src/utils/__tests__/getPropertyName-test.ts new file mode 100644 index 00000000000..24ac2bac798 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getPropertyName-test.ts @@ -0,0 +1,30 @@ +import { expect, test } from 'vitest'; +import { + getPropertyName, + isObjectExpression, + isProperty, + isVariableDeclaration, + isVariableDeclarator, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('reads identifier and literal property names', () => { + const file = parseFile('const value = { plain: 1, ["text"]: 2, [2]: 3 };'); + const declaration = file.ast.body[0]; + const variable = + declaration && isVariableDeclaration(declaration) + ? declaration.declarations[0] + : null; + const object = + variable && isVariableDeclarator(variable) && variable.init + ? variable.init + : null; + const properties = + object && isObjectExpression(object) ? object.properties : []; + + expect( + properties.map((property) => + isProperty(property) ? getPropertyName(property.key) : null, + ), + ).toEqual(['plain', 'text', '2']); +}); diff --git a/packages/typescript/src/utils/__tests__/getPropsMembers-test.ts b/packages/typescript/src/utils/__tests__/getPropsMembers-test.ts new file mode 100644 index 00000000000..9b2d78d77b9 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getPropsMembers-test.ts @@ -0,0 +1,59 @@ +import { getBody } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; +import getPropsMembers from '../getPropsMembers.js'; + +function getMembers(source: string) { + const file = parseFile(source); + const body = getBody(file); + const exportPath = body.find( + ({ node }) => node.type === 'ExportNamedDeclaration', + ); + const declaration = exportPath?.get('declaration'); + const parameter = + declaration && !Array.isArray(declaration) + ? declaration.get('params') + : null; + const firstParameter = Array.isArray(parameter) ? parameter[0] : null; + const typeAnnotation = firstParameter?.get('typeAnnotation'); + const annotation = + typeAnnotation && !Array.isArray(typeAnnotation) + ? typeAnnotation.get('typeAnnotation') + : null; + + return annotation && !Array.isArray(annotation) + ? getPropsMembers(file, annotation.node) + : []; +} + +test('resolves referenced interface members', () => { + expect( + getMembers(` + interface Props { label: string; disabled?: boolean } + export function View(props: Props) {} + `).map((member) => member.type), + ).toEqual(['TSPropertySignature', 'TSPropertySignature']); +}); + +test('handles circular interface inheritance', () => { + expect( + getMembers(` + interface A extends B { a: number } + interface B extends A { b: number } + export function View(props: A) {} + `).map((member) => member.key), + ).toEqual([ + expect.objectContaining({ name: 'b' }), + expect.objectContaining({ name: 'a' }), + ]); +}); + +test('handles circular type aliases', () => { + expect( + getMembers(` + type Foo = Bar; + type Bar = Foo; + export function View(props: Foo) {} + `), + ).toEqual([]); +}); diff --git a/packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts b/packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts new file mode 100644 index 00000000000..9c30f1fae96 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getResolvedEnumValues-test.ts @@ -0,0 +1,33 @@ +import { expect, test } from 'vitest'; +import { + getResolvedEnumValues, + isCallExpression, + type AstNode, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('evaluates Object.keys passed to oneOf', () => { + const file = parseFile( + 'const values = { first: 1, second: 2 }; PropTypes.oneOf(Object.keys(values));', + ); + let call: AstNode | null = null; + + file.traverse( + { + CallExpression(path) { + if ( + isCallExpression(path.node) && + path.node.arguments[0]?.type === 'CallExpression' + ) { + call = path.node; + path.stop(); + } + }, + }, + undefined, + ); + expect(call ? getResolvedEnumValues(file, call) : null).toEqual([ + { computed: false, value: '"first"' }, + { computed: false, value: '"second"' }, + ]); +}); diff --git a/packages/typescript/src/utils/__tests__/getTSType-test.ts b/packages/typescript/src/utils/__tests__/getTSType-test.ts new file mode 100644 index 00000000000..8604f2a6b62 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getTSType-test.ts @@ -0,0 +1,29 @@ +import { expect, test } from 'vitest'; +import { + isTSInterfaceDeclaration, + isTSPropertySignature, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; +import getTSType from '../getTSType.js'; + +test('serializes composite TypeScript types', () => { + const file = parseFile('interface Props { value: string | number[] }'); + const declaration = file.ast.body[0]; + const member = + declaration && isTSInterfaceDeclaration(declaration) + ? declaration.body.body[0] + : null; + + expect( + member && isTSPropertySignature(member) + ? getTSType(file, member.typeAnnotation) + : null, + ).toEqual({ + name: 'union', + raw: 'string | number[]', + elements: [ + { name: 'string' }, + { name: 'Array', elements: [{ name: 'number' }], raw: 'number[]' }, + ], + }); +}); diff --git a/packages/typescript/src/utils/__tests__/getTypeName-test.ts b/packages/typescript/src/utils/__tests__/getTypeName-test.ts new file mode 100644 index 00000000000..fb8cd91c071 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/getTypeName-test.ts @@ -0,0 +1,28 @@ +import { getBody } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; +import getTypeName from '../getTypeName.js'; + +test('maps supported TypeScript annotations', () => { + const file = parseFile('type Props = { label: string; disabled: boolean };'); + const [alias] = getBody(file); + const annotation = alias?.get('typeAnnotation'); + const members = + annotation && !Array.isArray(annotation) ? annotation.get('members') : null; + + expect(Array.isArray(members)).toBe(true); + + if (!Array.isArray(members)) { + return; + } + + expect( + members.map((member) => { + const typeAnnotation = member.get('typeAnnotation'); + + return typeAnnotation && !Array.isArray(typeAnnotation) + ? getTypeName(typeAnnotation.node) + : null; + }), + ).toEqual(['string', 'boolean']); +}); diff --git a/packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts b/packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts new file mode 100644 index 00000000000..b8e757251f3 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/hasComponentAnnotation-test.ts @@ -0,0 +1,12 @@ +import { getBody, hasComponentAnnotation } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('finds an adjacent component annotation', () => { + const file = parseFile('// @component\nconst Component = () => null;'); + const [declaration] = getBody(file); + + expect(declaration && hasComponentAnnotation(file, declaration.node)).toBe( + true, + ); +}); diff --git a/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts b/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts new file mode 100644 index 00000000000..534c2041561 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/parseMethodDocblock-test.ts @@ -0,0 +1,48 @@ +import { parseMethodDocblock } from '@react-docgen/core'; +import { expect, test } from 'vitest'; + +test('parses method summary, parameters, and return tags', () => { + const parsed = parseMethodDocblock( + 'Formats a value.\n@param {string=} value Input.\n@returns {number} Length.', + ); + + expect(parsed.description).toBe('Formats a value.'); + expect(parsed.params.get('value')).toEqual({ + description: 'Input.', + name: 'value', + optional: true, + type: { name: 'string' }, + }); + expect(parsed.returns).toEqual({ + description: 'Length.', + type: { name: 'number' }, + }); +}); + +test('parses JSDoc compound types and untyped tags', () => { + const parsed = parseMethodDocblock(` +@param {[string, number]} tuple +@param {string|Object|some[]} value +@param [label] Optional label. +@returns The result. + `); + + expect(parsed.params.get('tuple')?.type).toEqual({ + name: 'tuple', + elements: [{ name: 'string' }, { name: 'number' }], + }); + expect(parsed.params.get('value')?.type).toEqual({ + name: 'union', + elements: [ + { name: 'string' }, + { name: 'Object' }, + { name: 'Array', elements: [{ name: 'some' }] }, + ], + }); + expect(parsed.params.get('label')).toEqual({ + description: 'Optional label.', + name: 'label', + optional: true, + }); + expect(parsed.returns).toEqual({ description: 'The result.' }); +}); diff --git a/packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts b/packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts new file mode 100644 index 00000000000..92bc156b81c --- /dev/null +++ b/packages/typescript/src/utils/__tests__/resolveComponentDefinition-test.ts @@ -0,0 +1,18 @@ +import { getBody, resolveComponentDefinition } from '@react-docgen/core'; +import { expect, test } from 'vitest'; +import parseFile from '../../__tests__/testUtils.js'; + +test('resolves nested configured HOCs to their component', () => { + const file = parseFile(` + function View() {} + export default outer({ enabled: true }, inner('option', View)); + `); + const exportPath = getBody(file).at(-1); + const declaration = exportPath?.get('declaration'); + + expect( + declaration && !Array.isArray(declaration) + ? resolveComponentDefinition(file, declaration)?.node.type + : null, + ).toBe('FunctionDeclaration'); +}); diff --git a/packages/typescript/src/utils/__tests__/resolveValue-test.ts b/packages/typescript/src/utils/__tests__/resolveValue-test.ts new file mode 100644 index 00000000000..b87ea5b1d9e --- /dev/null +++ b/packages/typescript/src/utils/__tests__/resolveValue-test.ts @@ -0,0 +1,26 @@ +import { expect, test } from 'vitest'; +import { + isLiteral, + isVariableDeclaration, + isVariableDeclarator, + resolveValue, +} from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('resolves a value imported from another file', () => { + const file = parseFile( + 'import { label } from "./values"; const value = label;', + 'component.tsx', + () => ({ code: 'export const label = "Save";', filename: 'values.ts' }), + ); + const declaration = file.ast.body[1]; + const variable = + declaration && isVariableDeclaration(declaration) + ? declaration.declarations[0] + : null; + const init = + variable && isVariableDeclarator(variable) ? variable.init : null; + const value = init ? resolveValue(file, init) : null; + + expect(value && isLiteral(value) ? value.value : null).toBe('Save'); +}); diff --git a/packages/typescript/src/utils/__tests__/unwrapExpression-test.ts b/packages/typescript/src/utils/__tests__/unwrapExpression-test.ts new file mode 100644 index 00000000000..92388637671 --- /dev/null +++ b/packages/typescript/src/utils/__tests__/unwrapExpression-test.ts @@ -0,0 +1,18 @@ +import { expect, test } from 'vitest'; +import { unwrapExpression, type AstNode } from '@react-docgen/core'; +import parseFile from '../../__tests__/testUtils.js'; + +test('unwraps nested TypeScript expression wrappers', () => { + const file = parseFile('const value = (input as unknown as string)!;'); + const declaration = file.ast.body[0]; + const init = + declaration?.declarations && Array.isArray(declaration.declarations) + ? declaration.declarations[0]?.init + : null; + + expect( + init && typeof init === 'object' && 'type' in init + ? unwrapExpression(init as AstNode) + : null, + ).toMatchObject({ type: 'Identifier', name: 'input' }); +}); diff --git a/packages/typescript/src/utils/getClassPropsType.ts b/packages/typescript/src/utils/getClassPropsType.ts new file mode 100644 index 00000000000..808823ecdf7 --- /dev/null +++ b/packages/typescript/src/utils/getClassPropsType.ts @@ -0,0 +1,114 @@ +import { + getBody, + getPropertyName, + getValueFile, + isAstNode, + isCallExpression, + isIdentifier, + isLiteral, + isMemberExpression, + isPropertyDefinition, + isTSTypeAnnotation, + resolveValue, + type AstNode, + type ClassDeclaration, + type ClassExpression, + type FileState, +} from '@react-docgen/core'; + +function isReactComponentBase(file: FileState, node: AstNode): boolean { + const expression = resolveValue(file, node); + const member = isMemberExpression(expression) ? expression : null; + + if ( + member && + (member.computed || + (!isIdentifier(member.property, { name: 'Component' }) && + !isIdentifier(member.property, { name: 'PureComponent' }))) + ) { + return false; + } + const local = member?.object ?? expression; + + if (!isIdentifier(local)) return false; + + for (const { node: declaration } of getBody(getValueFile(file, expression))) { + if ( + declaration.type !== 'ImportDeclaration' || + !isAstNode(declaration.source) || + !isLiteral(declaration.source) || + declaration.source.value !== 'react' || + !Array.isArray(declaration.specifiers) + ) { + continue; + } + + for (const specifier of declaration.specifiers) { + if ( + !isAstNode(specifier) || + !isAstNode(specifier.local) || + !isIdentifier(specifier.local, { name: local.name }) + ) { + continue; + } + if (member) { + return ( + specifier.type === 'ImportDefaultSpecifier' || + specifier.type === 'ImportNamespaceSpecifier' + ); + } + + return ( + specifier.type === 'ImportSpecifier' && + isAstNode(specifier.imported) && + (isIdentifier(specifier.imported, { name: 'Component' }) || + isIdentifier(specifier.imported, { name: 'PureComponent' })) + ); + } + } + + return false; +} + +export default function getClassPropsType( + file: FileState, + definition: ClassDeclaration | ClassExpression, +): AstNode | null { + const [propsType] = definition.superTypeArguments?.params ?? []; + + if (propsType) return propsType; + const superClass = definition.superClass; + + if (isAstNode(superClass) && isCallExpression(superClass)) { + const [base] = superClass.arguments; + + if ( + base?.type === 'TSInstantiationExpression' && + isAstNode(base.expression) && + isReactComponentBase(file, base.expression) + ) { + const argumentsNode = base.typeArguments ?? base.typeParameters; + + if ( + isAstNode(argumentsNode) && + Array.isArray(argumentsNode.params) && + isAstNode(argumentsNode.params[0]) + ) { + return argumentsNode.params[0]; + } + } + } + + const props = definition.body.body.find( + (member) => + isPropertyDefinition(member) && + !member.static && + !member.computed && + getPropertyName(member.key) === 'props', + ); + const annotation = props?.typeAnnotation; + + return isAstNode(annotation) && isTSTypeAnnotation(annotation) + ? annotation.typeAnnotation + : null; +} diff --git a/packages/typescript/src/utils/getComposedTypeNames.ts b/packages/typescript/src/utils/getComposedTypeNames.ts new file mode 100644 index 00000000000..35e2f1d22e1 --- /dev/null +++ b/packages/typescript/src/utils/getComposedTypeNames.ts @@ -0,0 +1,75 @@ +import { + isExportNamedDeclaration, + isIdentifier, + isTSInterfaceDeclaration, + isTSTypeReference, + type AstNode, + type FileState, + getBody, +} from '@react-docgen/core'; + +export default function getComposedTypeNames( + file: FileState, + annotation: AstNode | null, +): string[] { + if ( + !annotation || + !isTSTypeReference(annotation) || + !isIdentifier(annotation.typeName) + ) { + return []; + } + + const localNames = new Set( + getBody(file).flatMap((path) => { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + const id = declaration.id; + + return (isTSInterfaceDeclaration(declaration) || + declaration.type === 'TSTypeAliasDeclaration') && + id && + typeof id === 'object' && + 'type' in id && + isIdentifier(id as AstNode) + ? [(id as AstNode & { name: string }).name] + : []; + }), + ); + + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + + if ( + !isTSInterfaceDeclaration(declaration) || + declaration.id.name !== annotation.typeName.name + ) { + continue; + } + const heritage = Array.isArray(declaration.extends) + ? declaration.extends + : []; + + return heritage.flatMap((item) => { + if (!item || typeof item !== 'object' || !('expression' in item)) + return []; + const expression = item.expression; + + return expression && + typeof expression === 'object' && + 'type' in expression && + isIdentifier(expression as AstNode) + ? localNames.has((expression as { name: string }).name) + ? [] + : [(expression as { name: string }).name] + : []; + }); + } + + return []; +} diff --git a/packages/typescript/src/utils/getPropsMembers.ts b/packages/typescript/src/utils/getPropsMembers.ts new file mode 100644 index 00000000000..cab0846ee98 --- /dev/null +++ b/packages/typescript/src/utils/getPropsMembers.ts @@ -0,0 +1,213 @@ +import { + isIdentifier, + isExportNamedDeclaration, + isTSInterfaceDeclaration, + isTSTypeAliasDeclaration, + isTSTypeLiteral, + isTSTypeReference, + type AstNode, + type FileState, + getBody, + getValueFile, + resolveValue, +} from '@react-docgen/core'; + +function child(node: AstNode, key: string): AstNode | null { + const value = node[key]; + + return value && typeof value === 'object' && 'type' in value + ? (value as AstNode) + : null; +} + +function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function substitute(node: AstNode, parameters: Map): AstNode { + if (isIdentifier(node) && parameters.has(node.name)) { + const value = parameters.get(node.name); + + return value && isTSTypeReference(value) ? value.typeName : (value ?? node); + } + + const result: Record = { ...node }; + + for (const [key, value] of Object.entries(result)) { + if (Array.isArray(value)) { + result[key] = value.map((item) => + item && typeof item === 'object' && 'type' in item + ? substitute(item as AstNode, parameters) + : item, + ); + } else if (value && typeof value === 'object' && 'type' in value) { + result[key] = substitute(value as AstNode, parameters); + } + } + + return result as AstNode; +} + +function parametersFor( + declaration: AstNode, + reference: AstNode, +): Map { + const declared = child(declaration, 'typeParameters'); + const provided = + child(reference, 'typeArguments') ?? child(reference, 'typeParameters'); + const values = provided ? nodes(provided, 'params') : []; + + return new Map( + (declared ? nodes(declared, 'params') : []).flatMap((parameter, index) => { + const name = child(parameter, 'name') ?? parameter; + const value = values[index]; + + return isIdentifier(name) && value ? [[name.name, value]] : []; + }), + ); +} + +export default function getPropsMembers( + file: FileState, + annotation: AstNode | null, + seen = new WeakSet(), +): AstNode[] { + if (!annotation) return []; + if (isTSTypeLiteral(annotation)) return annotation.members; + + if (annotation.type === 'TSIntersectionType') { + return nodes(annotation, 'types').flatMap((type) => + getPropsMembers(file, type), + ); + } + + if (!isTSTypeReference(annotation)) return []; + const typeName = annotation.typeName; + + if (!isIdentifier(typeName)) { + const wrapperName = Array.isArray(typeName.range) + ? file.source.code.slice(typeName.range[0], typeName.range[1]) + : ''; + + if ( + /^(?:React\.)?Props(?:WithChildren|WithRef|WithoutRef)$/.test(wrapperName) + ) { + const argumentsNode = + child(annotation, 'typeArguments') ?? + child(annotation, 'typeParameters'); + const [wrapped] = argumentsNode ? nodes(argumentsNode, 'params') : []; + + return getPropsMembers(file, wrapped ?? null); + } + + return []; + } + + const importedDeclaration = resolveValue(file, typeName); + + if (importedDeclaration !== typeName) { + const importedFile = getValueFile(file, importedDeclaration); + + if (isTSTypeAliasDeclaration(importedDeclaration)) { + if (seen.has(importedDeclaration)) return []; + seen.add(importedDeclaration); + const members = getPropsMembers( + importedFile, + importedDeclaration.typeAnnotation, + seen, + ); + + seen.delete(importedDeclaration); + + return members; + } + if (isTSInterfaceDeclaration(importedDeclaration)) { + if (seen.has(importedDeclaration)) return []; + seen.add(importedDeclaration); + const inherited = nodes(importedDeclaration, 'extends').flatMap( + (heritage) => { + const expression = child(heritage, 'expression'); + + if (!expression) return []; + + return getPropsMembers( + importedFile, + { + ...heritage, + type: 'TSTypeReference', + typeName: expression, + } as AstNode, + seen, + ); + }, + ); + + seen.delete(importedDeclaration); + + return [...inherited, ...importedDeclaration.body.body]; + } + } + + for (const path of getBody(file)) { + const declaration = + isExportNamedDeclaration(path.node) && path.node.declaration + ? path.node.declaration + : path.node; + + if ( + isTSTypeAliasDeclaration(declaration) && + declaration.id.name === typeName.name + ) { + if (seen.has(declaration)) return []; + seen.add(declaration); + const members = getPropsMembers( + file, + declaration.typeAnnotation, + seen, + ).map((member) => + substitute(member, parametersFor(declaration, annotation)), + ); + + seen.delete(declaration); + + return members; + } + + if ( + isTSInterfaceDeclaration(declaration) && + declaration.id.name === typeName.name + ) { + if (seen.has(declaration)) return []; + seen.add(declaration); + const parameters = parametersFor(declaration, annotation); + const inherited = nodes(declaration, 'extends').flatMap((heritage) => { + const expression = child(heritage, 'expression'); + + if (!expression) return []; + const reference = { + ...heritage, + type: 'TSTypeReference', + typeName: expression, + } as AstNode; + + return getPropsMembers(file, reference, seen); + }); + + const members = [...inherited, ...declaration.body.body].map((member) => + substitute(member, parameters), + ); + + seen.delete(declaration); + + return members; + } + } + + return []; +} diff --git a/packages/typescript/src/utils/getTSType.ts b/packages/typescript/src/utils/getTSType.ts new file mode 100644 index 00000000000..031a2b9c64a --- /dev/null +++ b/packages/typescript/src/utils/getTSType.ts @@ -0,0 +1,358 @@ +import { + isIdentifier, + isTSPropertySignature, + isTSTypeAliasDeclaration, + isTSTypeAnnotation, + isTSTypeReference, + type AstNode, + type FileState, + type TypeDescriptor, + getBody, + getDescription, + getPropertyName, +} from '@react-docgen/core'; + +function source(file: FileState, node: AstNode): string { + const value = Array.isArray(node.range) + ? file.source.code.slice(node.range[0], node.range[1]) + : ''; + + if (!value.includes('\n')) return value; + const lines = value.split('\n'); + const closingIndent = /^(\s*)/.exec(lines.at(-1) ?? '')?.[1]?.length ?? 0; + + return lines + .map((line, index) => + index === 0 ? line : line.slice(Math.min(closingIndent, line.length)), + ) + .join('\n'); +} + +function nodes(node: AstNode, key: string): AstNode[] { + const value = node[key]; + + return Array.isArray(value) + ? value.filter((item): item is AstNode => + Boolean(item && typeof item === 'object' && 'type' in item), + ) + : []; +} + +function child(node: AstNode, key: string): AstNode | null { + const value = node[key]; + + return value && typeof value === 'object' && 'type' in value + ? (value as AstNode) + : null; +} + +function typeName(file: FileState, node: AstNode): string { + return isIdentifier(node) + ? node.name + : source(file, node).replaceAll('.', ''); +} + +function replaceTypeParameter( + node: AstNode, + name: string, + value: AstNode, +): AstNode { + if (isIdentifier(node, { name })) { + return isTSTypeReference(value) ? value.typeName : value; + } + const result: Record = { ...node }; + + for (const [key, item] of Object.entries(result)) { + if (Array.isArray(item)) { + result[key] = item.map((entry) => + entry && typeof entry === 'object' && 'type' in entry + ? replaceTypeParameter(entry as AstNode, name, value) + : entry, + ); + } else if (item && typeof item === 'object' && 'type' in item) { + result[key] = replaceTypeParameter(item as AstNode, name, value); + } + } + + return result as AstNode; +} + +function objectType( + file: FileState, + node: AstNode, + resolving: Set, +): TypeDescriptor { + const properties = nodes(node, 'members').flatMap((member) => { + if (!isTSPropertySignature(member)) return []; + const key = getPropertyName(member.key); + const annotation = member.typeAnnotation + ? getTSType(file, member.typeAnnotation, resolving) + : null; + const description = getDescription(file, member); + + return key && annotation + ? [ + { + key, + value: { ...annotation, required: !member.optional }, + ...(description ? { description } : {}), + }, + ] + : []; + }); + + return { + name: 'signature', + type: 'object', + raw: source(file, node), + signature: { properties }, + }; +} + +function functionType(file: FileState, node: AstNode): TypeDescriptor { + const parameters = nodes(node, 'params'); + const returnType = child(node, 'returnType'); + + return { + name: 'signature', + type: 'function', + raw: source(file, node), + signature: { + arguments: parameters.flatMap((parameter) => { + const annotation = child(parameter, 'typeAnnotation'); + const nameNode = + parameter.type === 'RestElement' + ? child(parameter, 'argument') + : parameter; + const name = + nameNode && isIdentifier(nameNode) + ? nameNode.name + : source(file, nameNode ?? parameter); + + return annotation + ? [ + { + type: getTSType(file, annotation), + name, + ...(parameter.type === 'RestElement' ? { rest: true } : {}), + ...(parameter.optional ? { optional: true } : {}), + }, + ] + : []; + }), + return: returnType ? getTSType(file, returnType) : { name: 'void' }, + }, + }; +} + +export default function getTSType( + file: FileState, + input: AstNode | undefined, + resolving = new Set(), +): TypeDescriptor | null { + if (!input) return null; + const node = isTSTypeAnnotation(input) ? input.typeAnnotation : input; + const keywords: Record = { + TSAnyKeyword: 'any', + TSBooleanKeyword: 'boolean', + TSNeverKeyword: 'never', + TSNullKeyword: 'null', + TSNumberKeyword: 'number', + TSObjectKeyword: 'object', + TSStringKeyword: 'string', + TSSymbolKeyword: 'symbol', + TSUndefinedKeyword: 'undefined', + TSUnknownKeyword: 'unknown', + TSVoidKeyword: 'void', + }; + const keyword = keywords[node.type]; + + if (keyword) return { name: keyword }; + + if (node.type === 'TSLiteralType') { + const literal = child(node, 'literal'); + + return literal ? { name: 'literal', value: source(file, literal) } : null; + } + + if (node.type === 'TSUnionType' || node.type === 'TSIntersectionType') { + return { + name: node.type === 'TSUnionType' ? 'union' : 'intersection', + raw: source(file, node), + elements: nodes(node, 'types').flatMap((item) => { + const type = getTSType(file, item); + + return type ? [type] : []; + }), + }; + } + + if (node.type === 'TSArrayType') { + const element = child(node, 'elementType'); + + return { + name: 'Array', + elements: element ? [getTSType(file, element)].filter(Boolean) : [], + raw: source(file, node), + }; + } + + if (node.type === 'TSTupleType') { + return { + name: 'tuple', + raw: source(file, node), + elements: nodes(node, 'elementTypes').flatMap((item) => { + const type = getTSType(file, item); + + return type ? [type] : []; + }), + }; + } + + if (node.type === 'TSFunctionType') return functionType(file, node); + if (node.type === 'TSTypeLiteral') return objectType(file, node, resolving); + + if (node.type === 'TSTypeReference') { + const nameNode = child(node, 'typeName'); + + if (!nameNode) return null; + const name = typeName(file, nameNode); + + for (const statement of getBody(file)) { + if ( + isTSTypeAliasDeclaration(statement.node) && + statement.node.id.name === name && + !resolving.has(name) && + (statement.node.typeAnnotation.type === 'TSTupleType' || + statement.node.typeAnnotation.type === 'TSUnionType' || + statement.node.typeAnnotation.type === 'TSIntersectionType' || + statement.node.typeAnnotation.type === 'TSTypeLiteral' || + statement.node.typeAnnotation.type === 'TSArrayType' || + statement.node.typeAnnotation.type === 'TSTypeReference') + ) { + resolving.add(name); + let annotation = statement.node.typeAnnotation; + const declared = child(statement.node, 'typeParameters'); + const provided = + child(node, 'typeArguments') ?? child(node, 'typeParameters'); + const [parameter] = declared ? nodes(declared, 'params') : []; + const [argument] = provided ? nodes(provided, 'params') : []; + const parameterName = parameter + ? (child(parameter, 'name') ?? parameter) + : null; + + if (parameterName && isIdentifier(parameterName) && argument) { + annotation = replaceTypeParameter( + annotation, + parameterName.name, + argument, + ); + } + const result = getTSType(file, annotation, resolving); + + resolving.delete(name); + + return result; + } + } + + const typeArguments = + child(node, 'typeArguments') ?? child(node, 'typeParameters'); + const elements = typeArguments + ? nodes(typeArguments, 'params').flatMap((item) => { + const type = getTSType(file, item); + + return type ? [type] : []; + }) + : []; + + return { + name, + ...(source(file, node) !== name && + (source(file, node).includes('<') || source(file, node).includes('.')) + ? { raw: source(file, node) } + : {}), + ...(elements.length ? { elements } : {}), + }; + } + + if (node.type === 'TSTypeQuery') { + const expression = child(node, 'exprName'); + + return { name: expression ? source(file, expression) : source(file, node) }; + } + + if (node.type === 'TSIndexedAccessType') { + const raw = source(file, node); + const object = child(node, 'objectType'); + const index = child(node, 'indexType'); + const name = + index?.type === 'TSTypeOperator' + ? `${object ? source(file, object).replace(/^./, (value) => value.toLowerCase()) : ''}[${getTSType(file, index, resolving)?.name ?? ''}]` + : raw.replace(/^typeof\s+/, ''); + + return { name, raw }; + } + + if (node.type === 'TSTypeOperator') { + const annotation = child(node, 'typeAnnotation'); + + if (node.operator === 'keyof' && annotation?.type === 'TSTypeLiteral') { + return { + name: 'union', + raw: source(file, node), + elements: nodes(annotation, 'members').flatMap((member) => { + if (!isTSPropertySignature(member)) return []; + const key = getPropertyName(member.key); + + return key ? [{ name: 'literal', value: key }] : []; + }), + }; + } + const raw = annotation ? source(file, annotation) : source(file, node); + + return { name: raw.replace(/^./, (value) => value.toLowerCase()) }; + } + + if (node.type === 'TSMappedType') { + const typeParameter = child(node, 'typeParameter'); + const constraint = + child(node, 'constraint') ?? + (typeParameter ? child(typeParameter, 'constraint') : null); + const annotation = child(node, 'typeAnnotation'); + const keyType = constraint ? getTSType(file, constraint, resolving) : null; + const resolvedValue = annotation + ? getTSType(file, annotation, resolving) + : null; + const valueType = resolvedValue + ? { + ...resolvedValue, + name: resolvedValue.name.replace(/^./, (value) => + value.toLowerCase(), + ), + } + : null; + + return { + name: 'signature', + type: 'object', + raw: source(file, node), + signature: { + properties: + keyType && valueType + ? [ + { + key: { + name: keyType.name, + required: !node.optional, + }, + value: valueType, + }, + ] + : [], + }, + }; + } + + return { name: source(file, node) || node.type }; +} diff --git a/packages/typescript/src/utils/getTypeName.ts b/packages/typescript/src/utils/getTypeName.ts new file mode 100644 index 00000000000..4ab64f39a74 --- /dev/null +++ b/packages/typescript/src/utils/getTypeName.ts @@ -0,0 +1,22 @@ +import { + isTSBooleanKeyword, + isTSStringKeyword, + isTSTypeAnnotation, + type AstNode, +} from '@react-docgen/core'; + +export default function getTypeName(node: AstNode | undefined): string | null { + if (!node || !isTSTypeAnnotation(node)) { + return null; + } + + if (isTSStringKeyword(node.typeAnnotation)) { + return 'string'; + } + + if (isTSBooleanKeyword(node.typeAnnotation)) { + return 'boolean'; + } + + return null; +} diff --git a/packages/typescript/tests/integration/babel-differential-test.ts b/packages/typescript/tests/integration/babel-differential-test.ts new file mode 100644 index 00000000000..2ae0a58fe79 --- /dev/null +++ b/packages/typescript/tests/integration/babel-differential-test.ts @@ -0,0 +1,65 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { describe, expect, test } from 'vitest'; +import babelParser, { parse as parseBabel } from '@react-docgen/babel'; +import { + componentHandler, + createDocgen, + resolveComponentDefinitions, +} from '@react-docgen/core'; +import typescriptPropsHandler from '../../src/handlers/typescriptPropsHandler.js'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { parse as parseTypeScript } from '../../src/index.js'; + +function importer(specifier: string, fromFilename: string) { + const base = path.resolve(path.dirname(fromFilename), specifier); + const extensionless = base.replace(/\.[^./]+$/, ''); + const filename = [base, `${extensionless}.js`, `${extensionless}.jsx`].find( + (candidate) => fs.existsSync(candidate), + ); + + if (!filename) throw new Error(`Cannot resolve ${specifier}.`); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; +} + +describe('Babel differential', () => { + for (const integrationCase of loadIntegrationCases({ languages: ['js'] })) { + if (!integrationCase.output) continue; + test(integrationCase.id, () => { + const typescriptOutput = parseTypeScript(integrationCase.source, { + filename: integrationCase.filename, + importer, + }); + const babelOutput = parseBabel(integrationCase.source, { + filename: integrationCase.filename, + importer, + }); + + expect(babelOutput).toEqual(typescriptOutput); + expect(typescriptOutput).toEqual(integrationCase.output); + }); + } +}); + +describe('Babel mixin differential', () => { + const parse = createDocgen({ + handlers: [componentHandler, typescriptPropsHandler], + parser: babelParser, + resolver: resolveComponentDefinitions, + }); + + for (const integrationCase of loadIntegrationCases({ + languages: ['typescript'], + })) { + if (!integrationCase.id.startsWith('typescript/definitions/mixin-')) { + continue; + } + + test(integrationCase.id, () => { + expect( + parse(integrationCase.source, { filename: integrationCase.filename }), + ).toEqual(integrationCase.output); + }); + } +}); diff --git a/packages/typescript/tests/integration/integration-test.ts b/packages/typescript/tests/integration/integration-test.ts new file mode 100644 index 00000000000..87141a04855 --- /dev/null +++ b/packages/typescript/tests/integration/integration-test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { loadIntegrationCases } from '@react-docgen-internal/integration-tests'; +import { parse } from '../../src/index.js'; + +describe('integration', () => { + for (const integrationCase of loadIntegrationCases({ + languages: ['js', 'typescript'], + })) { + // Its support file uses Babel-only `export defaultFrom` syntax (PLAN.md). + const babelOnly = + integrationCase.id === 'typescript/imports/reexported-default-values'; + + test.skipIf(babelOnly)(integrationCase.id, () => { + const run = () => + parse(integrationCase.source, { + filename: integrationCase.filename, + importer(specifier, fromFilename) { + const base = path.resolve(path.dirname(fromFilename), specifier); + const extensionless = base.replace(/\.[^./]+$/, ''); + const filename = [ + base, + `${extensionless}.js`, + `${extensionless}.jsx`, + `${extensionless}.ts`, + `${extensionless}.tsx`, + ].find((candidate) => fs.existsSync(candidate)); + + if (!filename) throw new Error(`Cannot resolve ${specifier}.`); + + return { code: fs.readFileSync(filename, 'utf8'), filename }; + }, + }); + + if (integrationCase.error) { + expect(run).toThrow( + expect.objectContaining({ code: integrationCase.error.code }), + ); + } else { + expect(run()).toEqual(integrationCase.output); + } + }); + } +}); diff --git a/packages/typescript/tsconfig.json b/packages/typescript/tsconfig.json new file mode 100644 index 00000000000..e9f14970c69 --- /dev/null +++ b/packages/typescript/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "outDir": "./dist", + "rootDir": "./src" + }, + "exclude": ["**/__tests__/**/*", "**/__fixtures__/**/*"], + "include": ["src/**/*"] +} diff --git a/packages/typescript/vitest.config.ts b/packages/typescript/vitest.config.ts new file mode 100644 index 00000000000..aca73767e86 --- /dev/null +++ b/packages/typescript/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + name: 'typescript', + include: ['**/__tests__/**/*-test.ts', '**/tests/integration/**/*-test.ts'], + coverage: { + include: ['src/**'], + provider: 'v8', + reporter: ['text', 'lcov'], + }, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c762e2923fb..77b1734a723 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -233,7 +233,23 @@ importers: specifier: 5.0.5 version: 5.0.5(@types/node@22.20.5)(@vitest/coverage-v8@5.0.5)(vite@8.3.5(@types/node@22.20.5)(jiti@2.7.0)(yaml@2.9.1)) - benchmark: + packages/babel: + dependencies: + '@react-docgen/core': + specifier: workspace:* + version: link:../core + devDependencies: + '@babel/core': + specifier: 7.29.7 + version: 7.29.7(supports-color@7.2.0) + '@babel/types': + specifier: 7.29.8 + version: 7.29.8 + '@types/babel__core': + specifier: 7.20.5 + version: 7.20.5 + + packages/benchmark: dependencies: benchmark: specifier: 2.1.4 @@ -254,6 +270,33 @@ importers: specifier: npm:react-docgen@6.0.0 version: react-docgen@6.0.0(supports-color@7.2.0) + packages/core: + dependencies: + comment-parser: + specifier: ^1.4.9 + version: 1.4.9 + jsdoc-type-pratt-parser: + specifier: 8.0.0 + version: 8.0.0 + + packages/hermes: + dependencies: + '@react-docgen/core': + specifier: workspace:* + version: link:../core + hermes-parser: + specifier: 0.25.1 + version: 0.25.1 + devDependencies: + '@react-docgen-internal/integration-tests': + specifier: workspace:* + version: link:../integration-tests + '@react-docgen/babel': + specifier: workspace:* + version: link:../babel + + packages/integration-tests: {} + packages/react-docgen: dependencies: '@babel/core': @@ -286,6 +329,10 @@ importers: strip-indent: specifier: ^4.0.0 version: 4.1.1 + devDependencies: + '@react-docgen-internal/integration-tests': + specifier: workspace:* + version: link:../integration-tests packages/react-docgen-cli: dependencies: @@ -306,6 +353,25 @@ importers: specifier: 4.1.13 version: 4.1.13 + packages/typescript: + dependencies: + '@react-docgen/core': + specifier: workspace:* + version: link:../core + '@typescript-eslint/typescript-estree': + specifier: 8.67.0 + version: 8.67.0(supports-color@7.2.0)(typescript@6.0.3) + '@typescript-eslint/visitor-keys': + specifier: 8.67.0 + version: 8.67.0 + devDependencies: + '@react-docgen-internal/integration-tests': + specifier: workspace:* + version: link:../integration-tests + '@react-docgen/babel': + specifier: workspace:* + version: link:../babel + packages/website: dependencies: '@codemirror/lang-javascript': @@ -1720,6 +1786,12 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/project-service@8.67.0': + resolution: {integrity: sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/project-service@8.72.1': resolution: {integrity: sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1730,6 +1802,12 @@ packages: resolution: {integrity: sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/tsconfig-utils@8.67.0': + resolution: {integrity: sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/tsconfig-utils@8.72.1': resolution: {integrity: sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1743,10 +1821,20 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/types@8.67.0': + resolution: {integrity: sha512-sBtgslww8nsMYUjhdPBiSyUqSzT8uR6g93A2QXnQC8+cGdjz0CyaOdqHDRJb1AtORbZCNUJBBeFA/tNR2uQmww==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/types@8.72.1': resolution: {integrity: sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/typescript-estree@8.67.0': + resolution: {integrity: sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/typescript-estree@8.72.1': resolution: {integrity: sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1760,6 +1848,10 @@ packages: eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 typescript: '>=4.8.4 <6.1.0' + '@typescript-eslint/visitor-keys@8.67.0': + resolution: {integrity: sha512-fkv8dHRDqfGtTHuJeebdrQ7cX6Ad4WAS00rgHh9UGvMycF1mjBfsxry1XsLIFhWZ6Judlh6UdzK+TYlbpCXgnA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@typescript-eslint/visitor-keys@8.72.1': resolution: {integrity: sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2246,6 +2338,10 @@ packages: resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} engines: {node: '>= 12'} + comment-parser@1.4.9: + resolution: {integrity: sha512-+2AvZKjJaNq9GQljm3tr0utwrig5BL+jgJGvz5rDpGKNIp+ojcRXWUwBbh/sGIi1QCprR6PsKFakub+w1v+4hQ==} + engines: {node: '>= 12.0.0'} + compute-scroll-into-view@3.1.1: resolution: {integrity: sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==} @@ -3356,6 +3452,10 @@ packages: resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true + jsdoc-type-pratt-parser@8.0.0: + resolution: {integrity: sha512-uQu/fXVqVaMg6gM8/E5G5+eygVcZ1NV0Z51CvqhNa2bDWxvHMl484ETr6vph4oPyC+KUcbP/w2W2pewfCiR9aQ==} + engines: {node: '>=20.0.0'} + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} @@ -6457,6 +6557,15 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/project-service@8.67.0(supports-color@7.2.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/tsconfig-utils': 8.67.0(typescript@6.0.3) + '@typescript-eslint/types': 8.67.0 + debug: 4.4.3(supports-color@7.2.0) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + '@typescript-eslint/project-service@8.72.1(supports-color@7.2.0)(typescript@6.0.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.72.1(typescript@6.0.3) @@ -6471,6 +6580,10 @@ snapshots: '@typescript-eslint/types': 8.72.1 '@typescript-eslint/visitor-keys': 8.72.1 + '@typescript-eslint/tsconfig-utils@8.67.0(typescript@6.0.3)': + dependencies: + typescript: 6.0.3 + '@typescript-eslint/tsconfig-utils@8.72.1(typescript@6.0.3)': dependencies: typescript: 6.0.3 @@ -6487,8 +6600,25 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/types@8.67.0': {} + '@typescript-eslint/types@8.72.1': {} + '@typescript-eslint/typescript-estree@8.67.0(supports-color@7.2.0)(typescript@6.0.3)': + dependencies: + '@typescript-eslint/project-service': 8.67.0(supports-color@7.2.0)(typescript@6.0.3) + '@typescript-eslint/tsconfig-utils': 8.67.0(typescript@6.0.3) + '@typescript-eslint/types': 8.67.0 + '@typescript-eslint/visitor-keys': 8.67.0 + debug: 4.4.3(supports-color@7.2.0) + minimatch: 10.2.6 + semver: 7.8.5 + tinyglobby: 0.2.17 + ts-api-utils: 2.5.0(typescript@6.0.3) + typescript: 6.0.3 + transitivePeerDependencies: + - supports-color + '@typescript-eslint/typescript-estree@8.72.1(supports-color@7.2.0)(typescript@6.0.3)': dependencies: '@typescript-eslint/project-service': 8.72.1(supports-color@7.2.0)(typescript@6.0.3) @@ -6515,6 +6645,11 @@ snapshots: transitivePeerDependencies: - supports-color + '@typescript-eslint/visitor-keys@8.67.0': + dependencies: + '@typescript-eslint/types': 8.67.0 + eslint-visitor-keys: 5.0.1 + '@typescript-eslint/visitor-keys@8.72.1': dependencies: '@typescript-eslint/types': 8.72.1 @@ -6977,6 +7112,8 @@ snapshots: commander@8.3.0: {} + comment-parser@1.4.9: {} + compute-scroll-into-view@3.1.1: {} concat-map@0.0.1: {} @@ -8365,6 +8502,8 @@ snapshots: dependencies: argparse: 2.0.1 + jsdoc-type-pratt-parser@8.0.0: {} + jsesc@3.1.0: {} json-schema-traverse@0.4.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index edc8b393647..045a6ea6109 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,4 @@ packages: - - 'benchmark' - 'packages/*' allowBuilds: esbuild: false diff --git a/renovate.json b/renovate.json index 59957c3f131..29e5ff8d319 100644 --- a/renovate.json +++ b/renovate.json @@ -20,7 +20,7 @@ "packageRules": [ { "matchFileNames": [ - "benchmark/package.json", + "packages/benchmark/package.json", "packages/website/package.json", "packages/react-docgen-cli/package.json" ], @@ -46,7 +46,7 @@ }, { "matchFileNames": [ - "benchmark/package.json", + "packages/benchmark/package.json", "packages/website/package.json" ], "matchUpdateTypes": ["minor", "patch"], @@ -59,7 +59,7 @@ }, { "matchFileNames": [ - "benchmark/package.json", + "packages/benchmark/package.json", "packages/website/package.json" ], "semanticCommitType": "chore" diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000000..5f2d83a46f9 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url'; +import { defineConfig } from 'vitest/config'; + +const packages = [ + 'babel', + 'core', + 'hermes', + 'react-docgen', + 'react-docgen-cli', + 'typescript', +]; +const alias = Object.fromEntries( + ['babel', 'core', 'hermes', 'typescript'].map((name) => [ + `@react-docgen/${name}`, + fileURLToPath(new URL(`./packages/${name}/src/index.ts`, import.meta.url)), + ]), +); + +export default defineConfig({ + test: { + projects: packages.map((name) => ({ + extends: `./packages/${name}/vitest.config.ts`, + root: `./packages/${name}`, + resolve: { alias }, + test: { name }, + })), + coverage: { + provider: 'v8', + include: packages.map((name) => `packages/${name}/src/**`), + exclude: ['**/__tests__/**', '**/__mocks__/**', '**/__fixtures__/**'], + reporter: ['text', 'lcov', 'json-summary'], + thresholds: { + 'packages/react-docgen/src/**': { + statements: 84, + branches: 74, + functions: 94, + lines: 84, + }, + }, + }, + }, +});