diff --git a/.changeset/polite-kiwis-flash.md b/.changeset/polite-kiwis-flash.md new file mode 100644 index 0000000..62eaec2 --- /dev/null +++ b/.changeset/polite-kiwis-flash.md @@ -0,0 +1,6 @@ +--- +"@systemfsoftware/storybook-astro-framework": minor +"@systemfsoftware/storybook-astro-renderer": minor +--- + +Fork of storybook-astro 1.17.0 for Astro 7, Vite 8 and Storybook 10.6: the framework renders .astro components as stories. Docgen reads TypeScript's own type flags and no longer reports an optional string as a union, so it works under TypeScript 6. The framework's types pass a TypeScript 6 build. diff --git a/.changeset/sour-books-lick.md b/.changeset/sour-books-lick.md new file mode 100644 index 0000000..1d1adaa --- /dev/null +++ b/.changeset/sour-books-lick.md @@ -0,0 +1,8 @@ +--- +"@systemfsoftware/effect-atom": none +"@systemfsoftware/effect-atom-react": none +"@systemfsoftware/oxlint-config-frontend": none +"@systemfsoftware/storybook-gherkin": none +--- + +Workspace catalog gains the entries the storybook-astro packages use; these packages are unchanged. diff --git a/.gitignore b/.gitignore index ac63cdc..1495fc5 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ apps/site-e2e/artifacts/ .cache/ temp/ .vitest/ +.vitest-*/ diff --git a/docs/plans/2026-11-18-0014-feat-storybook-astro-rewrite-plan.md b/docs/plans/2026-11-18-0014-feat-storybook-astro-rewrite-plan.md new file mode 100644 index 0000000..039bc8f --- /dev/null +++ b/docs/plans/2026-11-18-0014-feat-storybook-astro-rewrite-plan.md @@ -0,0 +1,218 @@ +--- +title: Storybook Astro Rewrite - Plan +type: feat +date: 2026-11-18 +topic: storybook-astro-rewrite +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-brainstorm +execution: code +--- + +# Storybook Astro Rewrite - Plan + +## Goal Capsule + +- **Objective:** `@systemfsoftware/storybook-astro-framework` and `@systemfsoftware/storybook-astro-renderer` render real `.astro` components as Storybook stories, meet this repository's full standard with no rule relaxed for them, are licensed Apache-2.0 with no upstream notice, and are released from this repository for downstream Astro sites to consume. +- **Means:** a full rewrite of both packages, replacing the snapshot of storybook-astro 1.17.0 (upstream commit `ef554bb2f888f138574045c1ddae5ec233b75f5c`, MIT) held in `packages/storybook-astro/`. +- **Product authority:** the repository maintainers. `AGENTS.md`, `CONSTITUTION.md`, the shared lint preset and the enrolled compound packs set the standard; this plan cites them rather than restating them. +- **Open blockers:** the supported version ranges and integrations to keep (see Resolve Before Planning). +- **Stop condition:** this plan is a requirements document. Planning and implementation start only after review. + +## Product Contract + +### Summary + +Rewrite both packages from their behaviour so they pass the repository's gates with no per-package relaxation. Keep every behaviour the snapshot ships unless it is named as dropped. License the result Apache-2.0 with no NOTICE, prove it with a CI test that renders a real `.astro` story, and release both packages. + +### Problem Frame + +The snapshot makes `.astro` stories work on Astro 7, Vite 8 and Storybook 10.6, but it was written to a different standard. Each package's `oxlint.config.ts` turns off 40 rules the rest of the repository keeps on (`packages/storybook-astro/framework/oxlint.config.ts`, `packages/storybook-astro/renderer/oxlint.config.ts`). Linted against the unmodified preset, the two packages produce 3,652 findings across 148 files: 2,929 in the framework, 723 in the renderer, 1,430 of them in tests. The largest families are `strict-boolean-expressions`, `damp-test-naming`, `ban-unknown`, `consistent-type-assertions`, `complexity` and `no-restricted-imports` on Node built-ins. + +Moving those disables into the shared preset, a root override or an ignore pattern would hide the same findings, and `STRATEGY.md` rules out any opt-out or `warn` severity. The upstream code is also MIT-licensed, so the packages carry a NOTICE and a mixed-license story for as long as any of it remains. + +The consumer is a public Astro site. Its `.astro` page components and React islands need stories, and its maintainers want Storybook's accessibility checks to replace a separate accessibility CI job once stories render `.astro` components. + +### Key Decisions + +- **Full rewrite, not a cleaned-up fork.** Governs R1, R2, R4–R11. (session-settled: user-directed — chosen over keeping the upstream code behind lint-config disables: the disables are the defect.) +- **Apache-2.0 for both packages.** Governs R28. (session-settled: user-directed — chosen over keeping MIT or a mixed-license pair: one license, the repository's own.) +- **The NOTICE and MIT text go once the rewrite is complete.** Governs R29, R30. (session-settled: user-directed — chosen over keeping the NOTICE alongside the rewrite: a rewrite carries no upstream expression to attribute.) +- **The enrolled packs are the compound packs of `systemfsoftware/systemfsoftware` at `main`, every pack.** Governs the pack citations throughout. (session-settled: user-directed — chosen over the pack folders under this repository's own `compound-packs/`: those are not enrolled.) +- **`effect` becomes a peer dependency of both packages.** The preset bans `new Promise`, global timers, `process.env` and Node built-in imports, so passing it needs Effect and its platform services at runtime. A consumer installs `effect` 4 alongside Storybook and Astro. Governs R4, R8. +- **The real-render proof runs the built packages through their published entries in a real browser.** A source-level test cannot show that the shipped build works. Governs R22–R24. +- **Stories prove the component and island level of the downstream accessibility job, not the built-page level.** The page-accessibility pack keeps built-page checks (landmarks, headings, colour scheme, sticky header) outside what a story can see. See Outstanding Questions. Governs R24. + +### Requirements + +**Lint and gates** + +- R1. Each package's `oxlint.config.ts` extends the shared preset and nothing else, as `packages/atom/effect-atom/oxlint.config.ts` does: no rule turned off or lowered, no override, no `ignorePatterns`, no inline suppression. (pack: check-hygiene, a-lint-rule-enforces-a-decision-it-never-makes-one.md) +- R2. The shared preset, root lint and TypeScript configuration, and CI workflows are not edited to make either package pass; any change to them lands apart from this work. (pack: check-hygiene, a-lint-rule-enforces-a-decision-it-never-makes-one.md; `AGENTS.md` Boundaries; CONST-E7) +- R3. On the pushed head, `format:check`, `lint`, `lint:tsgo`, `lint:suppressions`, `typecheck`, `test` and `attw` pass for both packages. Neither package defines `lint:tsgo` today; both gain it, as `packages/gherkin/storybook-gherkin` has it. + +**Code shape** + +- R4. Decisions are pure and live in the file kinds the repository names. Effects sit at the edges as values, and each third-party callback (a Storybook preset hook, a Vite plugin hook) only hands its input to Effect code. (CONST-B1, CONST-B4; pack: cell-architecture, file-kinds.md) +- R5. A distinct failure is a tagged error variant, and mutually exclusive states are a tagged union, never an optional-field record or an error string. (CONST-D2, CONST-D4; pack: schema-modelling, states-are-tagged-unions.md) +- R6. A value a consumer or host supplies (framework options, Storybook and Vite payloads, render requests and replies, docgen output) is decoded once at its edge by a schema that declares the wire shape as sent and carries the domain rule, and nothing downstream re-checks it. (pack: schema-modelling, foreign-wire-shapes-are-the-encoded-side.md, invariants-live-in-the-schema.md) +- R7. No module holds mutable state. A cache, registry or memo table belongs to a service instance a Layer builds; the source files that today declare module-level `Map`, `Set` or `WeakMap` bindings (11) or a module-level `let` (6) are redesigned, not annotated. (pack: effect-architecture, instance-state-lives-in-the-constructor.md) +- R8. A third-party driver (Astro, Vite, the TypeScript compiler, a UI-framework plugin) loads inside the adapter's Layer, and a service module names its types with `import type` only. (pack: effect-architecture, adapters-load-their-driver-when-their-layer-builds.md, adapters-are-named-for-their-driver.md) +- R9. A library Layer is named `layer` or `layerConfig`, and layers are built and provided once at the composition root, never inside a decision or a hook body. (pack: effect-architecture, layers-are-named-layer-and-layerConfig.md, services-are-provided-once-at-the-composition-root.md) +- R10. A live instance a program acquires (a Vite server, an Astro container, a render daemon) is a scoped handle released by its scope, never a service or a value its caller must close. (pack: cell-architecture, handles-are-scoped-values.md, scopes-close-at-the-run-edge.md) +- R11. Text a decision produces for a reader (generated Astro source for the docs panel, canvas messages) comes from a pure formatter called after the decision, never from the decision. (pack: cell-architecture, presentation-is-a-formatter-the-write-phase-calls.md) +- R12. Environment variables are described `Config`s declared once, reaching code only through a `Config` in context. The render-server token is `Redacted`, a switchable feature (sanitization) is an enabled-or-disabled union that reads its other settings only when on, and the 6 source files that read `process.env` today stop. (pack: configuration, each-environment-variable-is-one-described-config.md, settings-reach-code-through-context.md, secrets-are-decoded-as-redacted.md, a-switched-off-feature-reads-none-of-its-settings.md) + +**Behaviour kept** + +- R13. Every behaviour the snapshot ships stays unless Scope Boundaries names it as dropped: + - rendering through Astro's Container API with props and slots, scoped styles, client directives and hydration; + - live preview with hot reload, static builds that pre-render Astro stories, and the server render mode with its token authentication; + - args and slot sanitization, story rules and module mocking; + - portable stories and the Vitest helpers, docgen of Astro props into controls, generated source for the docs panel, and decorators; + - the React, Vue, Svelte, Preact, Solid and Alpine.js integrations, `astro:assets` and Astro fonts support, and the render loading indicator. + +**Published surface** + +- R14. Every entry in either `exports` map has a named consumer that imports it. The renderer's per-module subpaths that mirror source files today (`./decoratedTree`, `./slotArgs`, `./storyStyles`, `./extractArgTypes`, `./preview-defaults`, `./decorators`, `./generateAstroSource`) stay only if one does. (pack: package-surface, subpaths-serve-consumers.md) +- R15. A symbol is importable under one name from one entry, and nothing is exported for a test. (pack: package-surface, one-name-one-entry.md; testing, tests-reach-only-the-published-surface.md) + +**Tests** + +- R16. Tests reach each package only through its published entries and live under `tests/`; only laws about a pure module stay in source. The 53 test files beside source today (11,881 lines) are rewritten, not moved. (pack: testing, tests-reach-only-the-published-surface.md) +- R17. Expected values come from the requirement as a story author or consumer meets it, never from the code under test, a snapshot or a recording, and a failing test is fixed in the code. (CONST-T10; pack: testing, expected-values-come-from-the-requirement.md, failing-tests-are-fixed-not-weakened.md) +- R18. No test replaces a platform driver, binding or runtime object with `vi.mock`, `vi.fn`, `vi.spyOn` or a hand-built object (17 of the 53 files use `vi.mock`, `vi.fn` or `vi.spyOn` today), and no test writes to the host: the fixture projects that docgen and render tests create inside the package directory are replaced by in-memory or in-process fixtures. (pack: testing, adapters-run-against-real-local-resources.md, io-runs-in-microvms-never-on-the-host.md) +- R19. Each pure decision (sanitization, args reconstruction, story-rule matching, slot arguments, docgen defaults and prop filtering, date revival) has properties whose inputs are drawn from its schema, whose oracles come from the contract, whose boundaries are built, and each of which is shown failing against a named wrong implementation in the pull request description. (pack: property-testing, drawn-values-reach-the-decision.md, oracles-are-independent-of-the-code-under-test.md, boundaries-and-collisions-are-constructed.md, properties-are-shown-to-fail.md) +- R20. Configuration is neither tested nor gated, and tests supply settings through context. (pack: testing, configuration-gets-no-test-and-no-gate.md; configuration, tests-supply-settings-and-never-mirror-them.md) +- R21. Decision modules are enrolled in on-demand mutation testing as the other workspace packages are, and a survivor is killed or its code deleted. Mutation is not part of CI (`STRATEGY.md`). (pack: testing, surviving-mutants-are-killed-or-their-code-deleted.md) + +**Real-render proof** + +- R22. A test that CI runs renders a story for a real `.astro` component through the built framework and renderer, in a real browser, and asserts what a person sees using role, label or text queries. No simulated DOM. (CONST-T8; pack: ui-testing, stories-are-the-ui-tests.md, queries-are-accessible.md) +- R23. The fixture components are written for this repository about a generic subject, take their data as args and slots, and reach no I/O. (pack: public-repository, material-is-invented-generated-or-public.md; ui-testing, stories-get-io-from-stand-ins-beside-the-io-module.md) +- R24. The same run applies accessibility checks to each fixture story, including a hydrated React island inside an `.astro` component, and a violation fails the run. (pack: page-accessibility, islands-are-proven-by-stories-and-in-the-built-page.md) +- R25. Dev, static-build and server render modes each render a story against the shipped build; a mode that needs real processes follows the end-to-end pack. (CONST-T8; pack: e2e-testing, e2e-is-its-own-package-on-real-processes.md) +- R26. The proof runs under a task the existing CI workflow already runs, and this work edits no workflow (`AGENTS.md` Boundaries; `.github/workflows/ci.yml`). +- R27. Every failure or waiting state the renderer shows in the Storybook canvas says what happened and what the story author can do next, never raw error text. (pack: screen-content, failure-states-say-what-happened-and-what-to-do.md) + +**License and provenance** + +- R28. Both packages are Apache-2.0: the `license` field and the `LICENSE` file of each say so. +- R29. When the rewrite is complete, both `NOTICE` files, the MIT text, and every statement that the packages are a fork or carry upstream code are removed from manifests, READMEs, `files` lists and `packages/storybook-astro/AGENTS.md`. +- R30. The rewrite contains no upstream-authored expression: no carried file, function body, test, comment or documentation text. A per-file overlap check against the snapshot commit shows it, reported in the pull request description and not by a CI check, and R29 lands only after it. (pack: check-hygiene, ci-never-grades-the-repository-itself.md) +- R31. Nothing private appears in any file, fixture, commit message or pull request text. (pack: public-repository, names-are-public-or-placeholders.md, people-and-paths-are-placeholders.md, material-is-invented-generated-or-public.md) + +**Release** + +- R32. One change intent names both packages at the class the surface change sets, the shared release workflow versions and tags them, and `attw` passes on the packed output. (pack: package-surface, surface-changes-are-versioned.md; `release.jsonc`) +- R33. Each manifest is release-ready: a real author, a description with no fork wording, repository and homepage pointing here, no `NOTICE` in `files`, and peer ranges limited to the versions the tests run against. Both manifests carry `author: "TODO "` today. +- R34. Publishing happens only after the maintainers confirm it (`AGENTS.md` Boundaries), and the packages exist on the registry at the released version. + +### Enrolled Pack Coverage + +Every pack in the enrolled source was read at its `main` head. Packs that apply are cited on the requirement they shaped. + +| Pack | Applies | Where or why not | +| ------------------- | ------------- | -------------------------------------------------------------------------------------------------------------- | +| cell-architecture | Yes | R4, R10, R11 | +| check-hygiene | Yes | R1, R2, R30 | +| configuration | Yes | R12, R20 | +| design-system | No | Concerns apps that render the Astryx component library; neither package does | +| e2e-testing | Conditionally | R25, for any mode that needs real processes | +| effect-architecture | Yes | R7, R8, R9 | +| package-surface | Yes | R14, R15, R32 | +| page-accessibility | Partly | R24 (islands); the built-page suite belongs to the consumer site | +| property-testing | Yes | R19 | +| public-repository | Yes | R23, R31 | +| schema-modelling | Yes | R5, R6 | +| screen-content | Narrowly | R27, the canvas states only; the pack's claims and sample-data rules concern product screens | +| testing | Yes | R16, R17, R18, R20, R21 | +| ui-state | No | Concerns effect-atom applications; the preset's React rules still judge the renderer's `.tsx` files through R1 | +| ui-testing | Yes | R22, R23 | + +### Actors + +- A1. Story author: the developer of an Astro site who writes and runs stories for `.astro` components and islands. +- A2. Maintainer: reviews the rewrite, confirms the release. + +### Key Flows + +- F1. Adopting the framework + - **Trigger:** A1 has an Astro 7 site and wants stories. + - **Steps:** A1 installs the two packages and their peers, points `.storybook/main` at the framework, writes a story for an `.astro` component and runs dev, build or the story test run. + - **Outcome:** The story renders the component's markup and styles, an island hydrates, and the accessibility checks report. + - **Covered by:** R13, R22, R24, R25 +- F2. Reviewing the rewrite + - **Trigger:** A2 opens the pull request that completes the rewrite. + - **Steps:** A2 reads the lint configs, the overlap check, the wrong-implementation evidence for each property and the green CI run; then confirms the release. + - **Outcome:** Both packages are versioned, tagged and published. + - **Covered by:** R1, R19, R30, R32, R34 + +### Acceptance Examples + +- AE1. **Covers R1, R2.** Given a head where either package's lint config adds one `'off'`, an `ignorePatterns` entry or an inline suppression, when the work is judged, it is not done, however green CI is. +- AE2. **Covers R22.** Given a fixture `.astro` card taking a title arg and a body slot, when its story runs through the built framework in a real browser, then the play function finds a heading by role with the title as its name and the body text by text. +- AE3. **Covers R24.** Given the same card with an image that has no text alternative, when the story runs, then the accessibility check fails the run. The pull request shows this once; the broken fixture is not committed. +- AE4. **Covers R29, R30.** Given the final head, when the package directories are searched for `NOTICE` and for the MIT license text, then neither is found, and the pull request description holds an overlap check against the snapshot commit showing no carried expression. + +### Success Criteria + +- CI on this repository is green on a head where neither package's lint config disables anything beyond the shared preset (R1–R3). +- A test in CI renders a real `.astro` component story through the framework (R22–R26). +- Both packages are released from this repository (R32–R34). + +### Scope Boundaries + +**Deferred for later** + +- Moving the downstream site's stories onto these packages and retiring its separate accessibility CI job. It depends on the release and is separate work. +- Behaviour that upstream's design notes describe but the snapshot does not ship: the Astro panel addon and the scaffold CLI. + +**Outside this plan** + +- Editing the shared lint preset, rules, CI workflows or gates (R2). +- The downstream built-page accessibility suite (pack: page-accessibility, README.md). +- Upstream's website, example apps and integration projects. +- Running mutation tests (on demand, never in CI or on a development host). +- Dropped behaviour: none named yet. Any entry added here names the behaviour and its reason; Resolve Before Planning asks which. + +### How This Work Fits Together + + + +This plan covers the rewrite and the release of the two packages. The relationships below are the current understanding, not a committed roadmap. + +- Downstream adoption in the consumer site + - Depends on this plan's release. + - Still to decide: how much of that site's accessibility job stories can replace (see Outstanding Questions). + +### Dependencies / Assumptions + +- The catalog pins Astro 7.4.8, Vite 8.3.4, Storybook 10.6.2, Vitest 5.0.5 and `@storybook/addon-vitest` 10.6.2 (`pnpm-workspace.yaml`). It has no accessibility addon entry, so R24 adds one. +- The framework pins `typescript` 6.0.3 because docgen needs TypeScript's JavaScript compiler API, which TypeScript 7 does not ship (`packages/storybook-astro/AGENTS.md`). The rewrite keeps docgen working under that pin. +- `.github/workflows/ci.yml` runs `turbo run format:check lint typecheck test` on a full run. `test:browser` runs only under `pnpm check:ci` through `gate:tasks`. +- Neither package is on the npm registry (it returns 404 for both names), so the surface change is evaluated against nothing released. +- This repository has no `CODING_STANDARDS.md`. The standard is `AGENTS.md`, `CONSTITUTION.md`, `STRATEGY.md`, the shared lint preset and the enrolled packs. + +### Outstanding Questions + +**Resolve Before Planning** + +- Which supported ranges and integrations does the rewrite keep? The snapshot supports Astro 5.5.3+, 6 and 7, Vite 6.4.1+, 7 and 8, Storybook 10 and 11 beta, and six UI integrations. The repository exercises only Astro 7, Vite 8, Storybook 10.6 and React, and R13 and R25 require a real-render proof for everything kept. Recommendation: keep what the repository can test (Astro 7, Vite 8, Storybook 10.6, React and Astro components) and name the rest in Scope Boundaries as dropped, to be restored by a later change that brings its own proof. + +**Deferred to Planning** + +- Which lane carries the real-render proof, given that CI runs `test` and not `test:browser`, and how the testing pack's no-host-process rule applies to a Storybook build run for it (R18, R22, R26). +- Where the single Effect runtime lives for entries a host invokes outside Effect (Storybook's preset loader, Vite plugin hooks), within the effect-architecture pack's host-invoked composition root exception (R4, R9). +- Whether server render mode needs an end-to-end package of its own or can be proven in-process (R25). +- Which of the 21 current entries (9 framework, 12 renderer) have a consumer (R14). +- The first released version. The manifests inherit upstream's 1.17.0 line, which no longer describes the code; the package-surface pack says a version below 1.0.0 never lowers the bump class. A maintainer decides before the release (R32). +- How much of the downstream accessibility job stories can replace. Stories cover components and islands with axe; the page-accessibility pack keeps checks for landmarks, one `h1`, colour scheme, forced colours, focus under a sticky header and reflow in a built-page suite that stories cannot see. A maintainer decides whether the downstream job shrinks or is replaced in part. +- Which accessibility addon and any other net-new dependency the rewrite adds, with the registry and maintainer vetting the repository requires (R24). + +### Sources / Research + +- Enrolled packs: `https://github.com/systemfsoftware/systemfsoftware`, `compound-packs/`, read at `main` head `50853229739c544db221d10b2edc3bd9e5228c4e`, as enrolled by `.compound-engineering/config.yaml`. The folders under this repository's own `compound-packs/` are not enrolled and are not cited. +- Repository standard: `AGENTS.md`, `STRATEGY.md`, `CONSTITUTION.md`, `oxlint.shared.ts`, `packages/oxlint-presets/oxlint-config-frontend/src/index.ts`, `turbo.json`, `.github/workflows/ci.yml`, `release.jsonc`, `pnpm-workspace.yaml`. +- Snapshot under rewrite: `packages/storybook-astro/framework` and `packages/storybook-astro/renderer`, together 114 non-test source files (15,995 lines) and 53 test files (11,881 lines). +- Sibling bar: `packages/atom/effect-atom/oxlint.config.ts` (preset only) and `packages/gherkin/storybook-gherkin` (story suite run by the Storybook Vitest addon). +- Upstream behaviour list: the upstream README at the snapshot commit (features, render modes, sanitization, story rules, framework integrations). diff --git a/packages/storybook-astro/AGENTS.md b/packages/storybook-astro/AGENTS.md new file mode 100644 index 0000000..60e90b1 --- /dev/null +++ b/packages/storybook-astro/AGENTS.md @@ -0,0 +1,7 @@ +# AGENTS.md — `@systemfsoftware/storybook-astro-framework` and `-renderer` + +Root `AGENTS.md` governs. These two packages are a fork of storybook-astro (https://github.com/storybook-astro/storybook-astro), taken at upstream commit `ef554bb2f888f138574045c1ddae5ec233b75f5c` (v1.17.0) without its history, the way `packages/atom` is. The upstream code is MIT; `NOTICE` carries that notice and our changes are Apache-2.0. + +The code is plain TypeScript, not Effect cell code. Each package's `oxlint.config.ts` extends the frontend preset and turns off the Effect-idiom, house-test-naming and type-strictness rules the upstream code was not written to; the promise, throw and suppression rules stay on. Tighten by removing a rule from that list once the code passes it, never by adding an inline suppression. + +`typescript` is pinned to 6.0.3 in the framework: docgen needs TypeScript's JavaScript compiler API, which TypeScript 7 does not ship (docgen then skips with a warning). diff --git a/packages/storybook-astro/framework/.attw.json b/packages/storybook-astro/framework/.attw.json new file mode 100644 index 0000000..76f3418 --- /dev/null +++ b/packages/storybook-astro/framework/.attw.json @@ -0,0 +1 @@ +{ "ignoreRules": ["no-resolution", "cjs-resolves-to-esm"] } diff --git a/packages/storybook-astro/framework/LICENSE b/packages/storybook-astro/framework/LICENSE new file mode 100644 index 0000000..19731ff --- /dev/null +++ b/packages/storybook-astro/framework/LICENSE @@ -0,0 +1,231 @@ +Copyright (c) 2026 Ryan Lee (systemfsoftware) + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Ryan Lee (systemfsoftware) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---------------------------------------------------------------------- +Third-party notices + +Portions of this software are derived from effect-atom +(https://github.com/tim-smart/effect-atom), which is licensed under +the MIT License: + +Copyright (c) 2023-present The Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/storybook-astro/framework/NOTICE b/packages/storybook-astro/framework/NOTICE new file mode 100644 index 0000000..9ee58fa --- /dev/null +++ b/packages/storybook-astro/framework/NOTICE @@ -0,0 +1,29 @@ +@systemfsoftware/storybook-astro-framework and @systemfsoftware/storybook-astro-renderer + +These packages are a fork of storybook-astro (https://github.com/storybook-astro/storybook-astro), +packages @storybook-astro/framework and @storybook-astro/renderer, taken at upstream +commit ef554bb2f888f138574045c1ddae5ec233b75f5c (release v1.17.0). + +The original code is copyright the storybook-astro authors and is licensed under the MIT +License, reproduced below. The modifications made in this fork are licensed under the +Apache License 2.0 (see LICENSE). + +MIT License + +Copyright (c) storybook-astro authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/packages/storybook-astro/framework/README.md b/packages/storybook-astro/framework/README.md new file mode 100644 index 0000000..d524a12 --- /dev/null +++ b/packages/storybook-astro/framework/README.md @@ -0,0 +1,38 @@ +# @systemfsoftware/storybook-astro-framework + +The community-supported [Storybook](https://storybook.js.org/) framework for [Astro](https://astro.build/). + +> Astro 5, 6 & 7 + Storybook 10 & 11 + +## Install + +```bash +npm install -D storybook @storybook/builder-vite @systemfsoftware/storybook-astro-framework +``` + +## Setup + +```javascript +// .storybook/main.js +export default { + stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'], + framework: { + name: '@systemfsoftware/storybook-astro-framework', + options: {}, + }, +} +``` + +## Requirements + +Node.js 20.16+, 22.19+ or 24+ (22.12+ for Storybook 11); Storybook 10 or 11, with `@storybook/builder-vite` at the same version as `storybook`; Astro 5.5.3+, 6 or 7; Vite 6.4.1+, 7 or 8 + +## Links + +- [Getting Started](https://storybook-astro.org/getting-started) +- [Live Demo](https://demo.storybook-astro.org) +- [GitHub](https://github.com/storybook-astro/storybook-astro) + +## License + +Apache-2.0. The upstream code is MIT, copyright the storybook-astro authors; see `NOTICE`. diff --git a/packages/storybook-astro/framework/oxlint.config.ts b/packages/storybook-astro/framework/oxlint.config.ts new file mode 100644 index 0000000..fbd11f9 --- /dev/null +++ b/packages/storybook-astro/framework/oxlint.config.ts @@ -0,0 +1,59 @@ +import recommended from '@systemfsoftware/oxlint-config-frontend' +import { defineConfig } from 'oxlint' + +// Forked storybook-astro code is plain TypeScript, not Effect cell code: the rules below grade +// Effect idioms, house test naming and house strictness that the upstream code does not follow. +// The unsafe-any, non-null and test-style rules are off until the port is typed; every other rule +// of the recommended preset, including the promise and throw rules, stays on. +export default defineConfig({ + extends: [recommended], + // The suites build throwaway fixture projects inside the package, while lint may run beside them. + ignorePatterns: ['.vitest-*/**'], + overrides: [ + { + files: ['**/*.ts', '**/*.tsx'], + rules: { + '@systemfsoftware/test-discipline/damp-test-naming': 'off', + '@systemfsoftware/test-discipline/no-test-file-in-src': 'off', + '@systemfsoftware/test-discipline/vitest-from-systemfsoftware-vitest': 'off', + '@systemfsoftware/cell-architecture/ban-unknown': 'off', + '@systemfsoftware/effect-platform/no-unported-time-source': 'off', + 'effecttsgo/strict-boolean-expressions': 'off', + 'effecttsgo/missing-pipeable-signature': 'off', + 'effecttsgo/global-timers': 'off', + 'effecttsgo/new-promise': 'off', + 'effecttsgo/global-date': 'off', + 'effecttsgo/node-builtin-import': 'off', + 'typescript/consistent-type-assertions': 'off', + 'typescript/no-unnecessary-condition': 'off', + 'typescript/strict-boolean-expressions': 'off', + 'eslint/complexity': 'off', + 'eslint/no-restricted-imports': 'off', + 'typescript/no-unsafe-assignment': 'off', + 'typescript/no-unsafe-member-access': 'off', + 'typescript/no-unsafe-call': 'off', + 'typescript/no-unsafe-argument': 'off', + 'typescript/no-unsafe-return': 'off', + 'typescript/no-non-null-assertion': 'off', + 'typescript/no-explicit-any': 'off', + 'typescript/no-unnecessary-type-assertion': 'off', + 'typescript/no-redundant-type-constituents': 'off', + 'typescript/restrict-template-expressions': 'off', + 'typescript/triple-slash-reference': 'off', + 'typescript/ban-ts-comment': 'off', + 'vitest/require-mock-type-parameters': 'off', + 'vitest/no-conditional-in-test': 'off', + 'vitest/valid-expect': 'off', + 'vitest/require-to-throw-message': 'off', + 'vitest/no-identical-title': 'off', + '@systemfsoftware/cell-architecture/ban-error-string': 'off', + '@systemfsoftware/cell-architecture/ban-classes': 'off', + '@systemfsoftware/cell-architecture/no-direct-tag-access': 'off', + 'effecttsgo/process-env': 'off', + 'unicorn/no-useless-fallback-in-spread': 'off', + 'jsdoc/check-tag-names': 'off', + 'eslint/no-unsafe-optional-chaining': 'off', + }, + }, + ], +}) diff --git a/packages/storybook-astro/framework/package.json b/packages/storybook-astro/framework/package.json new file mode 100644 index 0000000..27e69c3 --- /dev/null +++ b/packages/storybook-astro/framework/package.json @@ -0,0 +1,200 @@ +{ + "name": "@systemfsoftware/storybook-astro-framework", + "license": "Apache-2.0", + "version": "1.17.0", + "author": "TODO ", + "repository": { + "type": "git", + "url": "git+https://github.com/systemfsoftware/frontend.git", + "directory": "packages/storybook-astro/framework" + }, + "homepage": "https://github.com/systemfsoftware/frontend/tree/main/packages/storybook-astro/framework#readme", + "bugs": "https://github.com/systemfsoftware/frontend/issues", + "description": "Storybook framework for Astro components, forked under systemfsoftware from storybook-astro/storybook-astro.", + "keywords": [ + "storybook", + "astro", + "vite" + ], + "type": "module", + "engines": { + "node": ">=20.16.0 || >=22.19.0 || >=24.0.0" + }, + "files": [ + "dist", + "src", + "preset.ts", + "package.json", + "README.md", + "LICENSE", + "NOTICE" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./integrations": { + "types": "./dist/integrations/index.d.ts", + "import": "./dist/integrations/index.js" + }, + "./testing": { + "types": "./dist/testing.d.ts", + "import": "./dist/testing.js" + }, + "./vitest": { + "types": "./dist/vitest/index.d.ts", + "import": "./dist/vitest/index.js" + }, + "./node": { + "types": "./dist/node/index.d.ts", + "import": "./dist/node/index.js" + }, + "./docgen-worker": { + "types": "./dist/docgen/docgen-worker.d.ts", + "import": "./dist/docgen/docgen-worker.js" + }, + "./preset": { + "types": "./dist/preset.d.ts", + "import": "./dist/preset.js" + }, + "./image-service": { + "types": "./dist/storybookImageService.d.ts", + "default": "./dist/storybookImageService.js" + }, + "./shim": { + "types": "./src/shim.d.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "clean": "rimraf dist", + "build": "tsdown -l warn && node scripts/patch-shim-ref.mjs", + "typecheck": "tsc --noEmit -p tsconfig.json", + "test": "vitest run", + "test:watch": "vitest", + "lint": "f=${OXLINT_FORMAT:-${AGENT:+agent}}; oxlint . --config oxlint.config.ts --format=${f:-default}", + "attw": "attw --pack ." + }, + "dependencies": { + "@systemfsoftware/storybook-astro-renderer": "workspace:*", + "get-tsconfig": "5.0.0-beta.4", + "hono": "catalog:", + "sanitize-html": "catalog:", + "vite": "catalog:" + }, + "peerDependencies": { + "@astrojs/alpinejs": "^0.4.5 || ^0.5.0 || ^1.0.0", + "@astrojs/preact": "^4.0.8 || ^5.0.0 || ^6.0.0", + "@astrojs/react": "^4.2.3 || ^5.0.0 || ^6.0.0 || ^7.0.0", + "@astrojs/solid-js": "^5.0.7 || ^6.0.0 || ^7.0.0", + "@astrojs/svelte": "^7.0.9 || ^8.0.0 || ^9.0.0", + "@astrojs/vue": "^5.0.9 || ^6.0.0 || ^7.0.0", + "@preact/preset-vite": "^2.10.1", + "@storybook/preact": "^10.0.0 || ^11.0.0-beta.0", + "@storybook/react": "^10.0.0 || ^11.0.0-beta.0", + "@storybook/svelte": "^10.0.0 || ^11.0.0-beta.0", + "@storybook/vue3": "^10.0.0 || ^11.0.0-beta.0", + "@vitejs/plugin-react": "^5.0.0 || ^6.0.0", + "@vitejs/plugin-vue": "^5.2.3 || ^6.0.0", + "@vitejs/plugin-vue-jsx": "^4.1.2 || ^5.0.0", + "astro": "^5.5.3 || ^6.0.0 || ^7.0.0", + "storybook": "^10.0.0 || ^11.0.0-beta.0", + "storybook-solidjs-vite": ">=10.0.0 <10.1.0 || ^10.6.0 || ^11.0.0-beta.0", + "typescript": "^5.0.0 || ^6.0.0", + "vite": "^6.4.1 || ^7.0.0 || ^8.0.0", + "vitest": "^4.1.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "@astrojs/alpinejs": { + "optional": true + }, + "@astrojs/preact": { + "optional": true + }, + "@astrojs/react": { + "optional": true + }, + "@astrojs/solid-js": { + "optional": true + }, + "@astrojs/svelte": { + "optional": true + }, + "@astrojs/vue": { + "optional": true + }, + "@preact/preset-vite": { + "optional": true + }, + "@storybook/preact": { + "optional": true + }, + "@storybook/react": { + "optional": true + }, + "@storybook/svelte": { + "optional": true + }, + "@storybook/vue3": { + "optional": true + }, + "@vitejs/plugin-react": { + "optional": true + }, + "@vitejs/plugin-vue": { + "optional": true + }, + "@vitejs/plugin-vue-jsx": { + "optional": true + }, + "storybook-solidjs-vite": { + "optional": true + }, + "typescript": { + "optional": true + }, + "vitest": { + "optional": true + } + }, + "devDependencies": { + "@astrojs/react": "catalog:", + "@preact/preset-vite": "^2.10.3", + "@storybook/preact": "catalog:", + "@storybook/react": "catalog:", + "@storybook/svelte": "catalog:", + "@storybook/vue3": "catalog:", + "@sveltejs/vite-plugin-svelte": "^6.0.0", + "@systemfsoftware/arethetypeswrong-cli": "^4.2.0", + "@systemfsoftware/oxlint-config-frontend": "workspace:^", + "@systemfsoftware/storybook-astro-renderer": "workspace:*", + "@systemfsoftware/tsdown-config": "^0.1.2", + "@testing-library/dom": "catalog:", + "@testing-library/react": "catalog:", + "@types/node": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@types/sanitize-html": "^2.16.0", + "@vitejs/plugin-react": "catalog:", + "@vitejs/plugin-vue": "^6.0.0", + "@vitejs/plugin-vue-jsx": "^5.0.0", + "alpinejs": "^3.14.9", + "astro": "catalog:", + "oxlint": "catalog:oxlint", + "preact": "^10.0.0", + "react": "catalog:", + "react-dom": "catalog:", + "rimraf": "catalog:", + "solid-js": "^1.9.0", + "storybook": "catalog:", + "storybook-solidjs-vite": "^10.6.0", + "svelte": "^5.0.0", + "tsdown": "catalog:", + "typescript": "npm:typescript@6.0.3", + "vite": "catalog:", + "vite-plugin-solid": "^2.11.10", + "vitest": "catalog:", + "vue": "^3.5.0" + } +} diff --git a/packages/storybook-astro/framework/preset.ts b/packages/storybook-astro/framework/preset.ts new file mode 100644 index 0000000..287f97f --- /dev/null +++ b/packages/storybook-astro/framework/preset.ts @@ -0,0 +1 @@ +export * from './src/preset.ts' diff --git a/packages/storybook-astro/framework/scripts/patch-shim-ref.mjs b/packages/storybook-astro/framework/scripts/patch-shim-ref.mjs new file mode 100644 index 0000000..9f3a10e --- /dev/null +++ b/packages/storybook-astro/framework/scripts/patch-shim-ref.mjs @@ -0,0 +1,13 @@ +// Prepend the shim reference directive to dist/index.d.ts after tsup finishes. +// This makes `/// ` apply +// automatically when consumers import from @systemfsoftware/storybook-astro-framework, giving +// them typed *.astro imports without any manual env.d.ts changes. +import { readFileSync, writeFileSync } from 'node:fs' + +const path = 'dist/index.d.ts' +const header = '/// \n' +const content = readFileSync(path, 'utf8') + +if (!content.startsWith(header)) { + writeFileSync(path, header + content) +} diff --git a/packages/storybook-astro/framework/src/astroImageService.ts b/packages/storybook-astro/framework/src/astroImageService.ts new file mode 100644 index 0000000..1253bbc --- /dev/null +++ b/packages/storybook-astro/framework/src/astroImageService.ts @@ -0,0 +1,32 @@ +import { createRequire } from 'node:module' +import storybookImageService from './storybookImageService.ts' + +/** + * Astro 5 through 7.3 look for an image service on + * `globalThis.astroAsset.imageService` before importing `virtual:image-service`, + * and that import fails in some Vite module runners (Astro 6 on Vite 7). + * Setting the global sidesteps it. Astro 7.4+ no longer reads the global; see + * `storybookImageServiceConfig` for those versions. + */ +export function ensureAstroPassthroughImageService() { + const asset = globalThis as unknown as { astroAsset?: Record } + + asset.astroAsset ??= {} + asset.astroAsset.imageService = storybookImageService +} + +/** + * The `image.service` config for the SSR servers that render stories. Astro + * 7.4+ keeps the image service in a module-level variable filled only from + * `virtual:image-service`, which loads this entrypoint (issue #196). + * + * The entrypoint is resolved to an absolute path here, rather than passed as a + * package name, so it loads wherever the project's Vite root is: pnpm layouts, + * test fixtures and deployed render servers included. + */ +export function storybookImageServiceConfig() { + return { + entrypoint: createRequire(import.meta.url).resolve('@systemfsoftware/storybook-astro-framework/image-service'), + config: {}, + } +} diff --git a/packages/storybook-astro/framework/src/astroRenderHandler.test.ts b/packages/storybook-astro/framework/src/astroRenderHandler.test.ts new file mode 100644 index 0000000..e3d58a0 --- /dev/null +++ b/packages/storybook-astro/framework/src/astroRenderHandler.test.ts @@ -0,0 +1,578 @@ +import { ASTRO_COMPONENT_MARKER } from '@systemfsoftware/storybook-astro-renderer/types' +import { describe, expect, test, vi } from 'vitest' +import { createAstroRenderHandler, processImageMetadata } from './astroRenderHandler.ts' +import type { ComponentStyles } from './lib/componentStyles.ts' +import type { SanitizationOptions } from './lib/sanitization.ts' + +// In the static-build/testing path, story args arrive as real JS objects (no +// JSON transport), so a Date reaches processImageMetadata as an actual Date. +// It must survive: walking it with Object.entries would flatten it to {}, which +// surfaced as "Invalid time value" when a component formatted the date. +test('processImageMetadata preserves a nested Date instead of flattening it', async () => { + const date = new Date('2022-04-04T05:00:00.000Z') + + const result = await processImageMetadata({ + post: { data: { title: 'Hello', date } }, + }) + + const preserved = (result.post as { data: { date: unknown } }).data.date + + expect(preserved).toBeInstanceOf(Date) + expect((preserved as Date).toISOString()).toBe('2022-04-04T05:00:00.000Z') +}) + +test('processImageMetadata preserves Dates inside arrays', async () => { + const result = await processImageMetadata({ + posts: [{ data: { date: new Date('2022-04-04T05:00:00.000Z') } }], + }) + + const preserved = (result.posts as Array<{ data: { date: unknown } }>)[0].data.date + + expect(preserved).toBeInstanceOf(Date) +}) + +test('processImageMetadata still recurses into plain objects', async () => { + const result = await processImageMetadata({ nested: { keep: 'value', n: 1 } }) + + expect(result.nested).toEqual({ keep: 'value', n: 1 }) +}) + +// --- Decorator root node (`node`) — Decorator Support, Step 3 ------------- +// +// A fake Astro Container: `renderToString` records the component/props/slots +// it was called with and returns a small, deterministic HTML fragment so tests +// can assert on the final assembled string without a real Astro build. A fake +// `loadModule` resolves a moduleId to one of `components`, the same way the +// dev/server transports load a story or decorator component from disk. +// moduleIds here are deliberately bare (no leading slash) so the generated +// fragments below read cleanly as plain strings. + +const marker = (moduleId: string) => ({ [ASTRO_COMPONENT_MARKER]: true as const, moduleId }) + +function fakeComponent(moduleId: string) { + const factory = (() => undefined) as unknown as (() => undefined) & { + isAstroComponentFactory: true + moduleId: string + } + + factory.isAstroComponentFactory = true + factory.moduleId = moduleId + + return factory +} + +type FakeRenderToString = ( + component: { moduleId?: string }, + opts: { props?: Record; slots?: Record }, +) => Promise + +/** `slotHtml` — deterministic and easy to assert on. */ +const defaultRenderToString: FakeRenderToString = async (component, opts) => { + const moduleId = component.moduleId ?? 'unknown' + const slotHtml = Object.values(opts.slots ?? {}).join('') + + return `<${moduleId} props="${JSON.stringify(opts.props ?? {})}">${slotHtml}` +} + +function createHandler(options: { + components: Record + sanitization?: SanitizationOptions + renderToString?: FakeRenderToString + loadComponentStyles?: (componentIds: string[]) => Promise + failOnStyleError?: boolean +}) { + const renderToString = vi.fn(options.renderToString ?? defaultRenderToString) + const loadModule = vi.fn(async (id: string) => ({ default: options.components[id] })) + + const handler = createAstroRenderHandler({ + container: { renderToString } as unknown as Parameters[0]['container'], + sanitization: options.sanitization, + loadModule, + loadComponentStyles: options.loadComponentStyles, + failOnStyleError: options.failOnStyleError, + }) + + return { handler, renderToString } +} + +describe('createAstroRenderHandler — node absent (regression)', () => { + test('renders the plain story exactly as it did before Step 3', async () => { + const { handler } = createHandler({ components: { 'Button.astro': fakeComponent('Button.astro') } }) + + const html = await handler({ + component: 'Button.astro', + args: { label: 'Hi' }, + slots: { default: 'x' }, + }) + + expect(html).toBe('x') + }) +}) + +describe('createAstroRenderHandler — resolving a decorator root node', () => { + test('resolves a two-level nested descriptor chain, innermost story first', async () => { + const { handler, renderToString } = createHandler({ + components: { + 'Layout.astro': fakeComponent('Layout.astro'), + 'Card.astro': fakeComponent('Card.astro'), + 'Story.astro': fakeComponent('Story.astro'), + }, + }) + + const node = { + component: marker('Layout.astro'), + slots: { + default: { + component: marker('Card.astro'), + props: { title: 'Card title' }, + slots: { default: marker('Story.astro') }, + }, + }, + } + + const html = await handler({ + component: 'Story.astro', + args: { label: 'From story args' }, + slots: {}, + node, + }) + + // Innermost (the story) renders before its parent, whose slot content is + // then available when the parent itself renders — the existing + // configured-component-slot machinery's order, reused for the root. + const moduleIds = renderToString.mock.calls.map(([component]) => (component as { moduleId?: string }).moduleId) + + expect(moduleIds).toEqual(['Story.astro', 'Card.astro', 'Layout.astro']) + + // The story keeps its own top-level args as props, wherever it sits in the + // tree — not the empty props a bare slot leaf would otherwise get. + expect(html).toBe( + '' + + '' + + '' + + '' + + '', + ) + }) + + test('resolves an array root — the split form of a string decorator', async () => { + const { handler } = createHandler({ + components: { 'Story.astro': fakeComponent('Story.astro') }, + }) + + const node = ['
', marker('Story.astro'), '
'] + + const html = await handler({ component: 'Story.astro', args: {}, slots: {}, node }) + + expect(html).toBe('
') + }) + + test('runs the story leaf’s render through its own already-processed args/slots, not empty props', async () => { + const { handler, renderToString } = createHandler({ + components: { + 'Wrapper.astro': fakeComponent('Wrapper.astro'), + 'Story.astro': fakeComponent('Story.astro'), + }, + }) + + const node = { component: marker('Wrapper.astro'), slots: { default: marker('Story.astro') } } + + await handler({ + component: 'Story.astro', + args: { title: 'Hello' }, + slots: { footer: '

footer

' }, + node, + }) + + const storyCall = renderToString.mock.calls.find( + ([component]) => (component as { moduleId?: string }).moduleId === 'Story.astro', + ) + const storySlots = storyCall?.[1].slots as Record + + expect(storyCall?.[1].props).toEqual({ title: 'Hello' }) + // `markRawSlots` wraps string slots in Astro's `HTMLString` — compare by + // content, not structural equality. + expect(String(storySlots.footer)).toBe('

footer

') + }) + + // Server mode loads components from a deployed snapshot at a different path + // than the client-sent moduleId (`resolveSnapshotComponentPath` in + // `server/index.ts`), so Astro's compiler embeds `.moduleId` from the + // *snapshot* path on the loaded factory — not the original id the request + // carries as `component`/the marker's `moduleId`. The story leaf must still + // be recognized by *which load it came from*, not by comparing that embedded + // `.moduleId` string against the request's `component`. + test('recognizes the story leaf even when the loaded component reports a different moduleId (server-mode snapshot remap)', async () => { + // The loaded factory's own `.moduleId` (as Astro's compiler embedded it while + // compiling the snapshot copy) deliberately differs from the request's + // `component`/marker moduleId, simulating `resolveSnapshotComponentPath`. + const snapshotStoryFactory = fakeComponent('/snapshot/project/Story.astro') + const loadModule = vi.fn(async (id: string) => ({ + default: id === 'Wrapper.astro' ? fakeComponent('Wrapper.astro') : snapshotStoryFactory, + })) + const renderToString = vi.fn(defaultRenderToString) + const handler = createAstroRenderHandler({ + container: { renderToString } as unknown as Parameters[0]['container'], + loadModule, + }) + + const node = { component: marker('Wrapper.astro'), slots: { default: marker('Story.astro') } } + + await handler({ + component: 'Story.astro', + args: { title: 'Hello' }, + slots: {}, + node, + }) + + const storyCall = renderToString.mock.calls.find( + ([component]) => (component as { moduleId?: string }).moduleId === snapshotStoryFactory.moduleId, + ) + + expect(storyCall?.[1].props).toEqual({ title: 'Hello' }) + }) +}) + +describe('createAstroRenderHandler — decorator security boundary', () => { + test('strips a ', marker('Story.astro'), ''] + + const html = await handler({ component: 'Story.astro', args: {}, slots: {}, node }) + + expect(html).not.toContain('alert(1)') + expect(html).not.toContain('' + + const { handler } = createHandler({ + components: { 'Story.astro': fakeComponent('Story.astro') }, + renderToString: async () => trustedComponentHtml, + }) + + const node = ['
', marker('Story.astro'), '
'] + + const html = await handler({ component: 'Story.astro', args: {}, slots: {}, node }) + + expect(html).toContain('') + expect(html).toContain('') + expect(html).toContain('data-astro-cid-abc123') + }) + + test('keeps a wrapper tag balanced across array entries around the rendered component', async () => { + const { handler } = createHandler({ + components: { 'Story.astro': fakeComponent('Story.astro') }, + renderToString: async () => 'story', + }) + + const node = ['
', marker('Story.astro'), '
'] + + const html = await handler({ component: 'Story.astro', args: {}, slots: {}, node }) + + // A per-entry sanitize pass would auto-close '
' on its + // own and discard the orphan '
' (#149) — this proves the wrapper + // stays balanced around the trusted, spliced-in component HTML. + expect(html).toBe('
story
') + }) +}) + +describe('createAstroRenderHandler — wrapper props pipeline', () => { + test('runs a wrapper descriptor’s own props through reconstructProps + processImageMetadata + reviveDateStrings', async () => { + const { handler, renderToString } = createHandler({ + components: { + 'Wrapper.astro': fakeComponent('Wrapper.astro'), + 'Icon.astro': fakeComponent('Icon.astro'), + 'Story.astro': fakeComponent('Story.astro'), + }, + }) + + const node = { + component: marker('Wrapper.astro'), + props: { + // A component-as-prop marker: must resolve to the real factory, not + // stay a plain marker object, exactly like a top-level story arg does. + Icon: marker('Icon.astro'), + // A JSON-serialized Date: must revive to a real Date instance. + publishedAt: '2022-04-04T05:00:00.000Z', + }, + slots: { default: marker('Story.astro') }, + } + + await handler({ component: 'Story.astro', args: {}, slots: {}, node }) + + const wrapperCall = renderToString.mock.calls.find( + ([component]) => (component as { moduleId?: string }).moduleId === 'Wrapper.astro', + ) + const wrapperProps = wrapperCall?.[1].props as { Icon: unknown; publishedAt: unknown } + + expect(typeof wrapperProps.Icon).toBe('function') + expect((wrapperProps.Icon as { moduleId?: string }).moduleId).toBe('Icon.astro') + expect(wrapperProps.publishedAt).toBeInstanceOf(Date) + expect((wrapperProps.publishedAt as Date).toISOString()).toBe('2022-04-04T05:00:00.000Z') + }) +}) + +describe('createAstroRenderHandler — malformed node rejected', () => { + test('rejects a node that is not a valid SlotValue shape', async () => { + const { handler } = createHandler({ components: { 'Story.astro': fakeComponent('Story.astro') } }) + + await expect( + handler({ component: 'Story.astro', args: {}, slots: {}, node: 42 as never }), + ).rejects.toThrow(/not a valid decorator node/) + }) + + test('rejects a descriptor whose props is not a plain object', async () => { + const { handler } = createHandler({ components: { 'Story.astro': fakeComponent('Story.astro') } }) + + const node = { component: marker('Story.astro'), props: 'not an object' as never } + + await expect(handler({ component: 'Story.astro', args: {}, slots: {}, node })).rejects.toThrow( + /props must be a plain object/, + ) + }) +}) + +describe('createAstroRenderHandler — depth cap', () => { + test('fails loudly instead of silently truncating when nesting exceeds the maximum depth', async () => { + const components: Record = { 'Story.astro': fakeComponent('Story.astro') } + + // Build a chain of wrapper descriptors deeper than MAX_DEPTH (10). + let node: unknown = marker('Story.astro') + + for (let level = 0; level < 12; level += 1) { + const moduleId = `Wrapper${level}.astro` + + components[moduleId] = fakeComponent(moduleId) + node = { component: marker(moduleId), slots: { default: node } } + } + + const { handler } = createHandler({ components }) + + await expect( + handler({ component: 'Story.astro', args: {}, slots: {}, node: node as never }), + ).rejects.toThrow(/maximum node depth/) + }) +}) + +// --- Scoped component styles (issue #189) ---------------------------------- + +describe('createAstroRenderHandler — component styles', () => { + const stylesNamingEachComponent = async (ids: string[]): Promise => ({ + stylesheets: ids.map((id) => `/* ${id} */`), + failures: [], + }) + + test('ships the CSS of every component the story used, decorators first, ahead of the HTML', async () => { + const loadComponentStyles = vi.fn(stylesNamingEachComponent) + const { handler } = createHandler({ + components: { + 'Panel.astro': fakeComponent('Panel.astro'), + 'Badge.astro': fakeComponent('Badge.astro'), + 'Wrapper.astro': fakeComponent('Wrapper.astro'), + }, + loadComponentStyles, + }) + + const html = await handler({ + component: 'Panel.astro', + // A real factory, as the static build passes it straight from the story module. + args: { Icon: fakeComponent('Icon.astro') }, + // A marker, as the browser sends it. + slots: { default: marker('Badge.astro') }, + node: { component: marker('Wrapper.astro'), slots: { default: marker('Panel.astro') } }, + }) + + // The decorator wraps the story like a layout wraps a page, so the story's + // CSS comes after the decorator's, as a page's does after its layout's. + expect(loadComponentStyles).toHaveBeenCalledWith(['Wrapper.astro', 'Panel.astro', 'Icon.astro', 'Badge.astro']) + expect(html).toMatch( + /^("; }'], failures: [] }), + }) + + const html = await handler({ component: 'Button.astro' }) + + expect(html).toContain('content: "<\\/style>"; }/g)).toHaveLength(1) + }) + + function createMockingHandler() { + const loadModule = vi.fn(async (id: string) => ({ default: fakeComponent(id) })) + const invalidateModuleGraph = vi.fn() + const handler = createAstroRenderHandler({ + container: { renderToString: vi.fn(defaultRenderToString) } as unknown as Parameters< + typeof createAstroRenderHandler + >[0]['container'], + loadModule, + invalidateModuleGraph, + resolveRulesConfigModule: () => ({ + rules: [{ + match: 'card--mocked', + use: ({ mock }: { mock: (id: string, factory: () => object) => void }) => mock('./data.ts', () => ({})), + }], + }), + loadComponentStyles: stylesNamingEachComponent, + }) + const render = (storyId: string, request: Partial[0]> = {}) => + handler({ component: 'Card.astro', story: { id: storyId, title: 'Card', name: storyId }, ...request }) + + return { loadModule, invalidateModuleGraph, render } + } + + test('restores the real modules after a story with module mocks, for whichever handler renders next', async () => { + // The modules a mocked render loads import the mocks. The module graph + // outlives the handler (dev makes a new one on every file change), so it + // is reset as soon as the mocked render ends. + const { loadModule, invalidateModuleGraph, render } = createMockingHandler() + + await render('card--real') + await render('card--mocked') + + expect(invalidateModuleGraph).toHaveBeenCalledTimes(2) + + // The next story reloads its components, so it and its styles come from + // the real modules. After that, renders use the cache again. + loadModule.mockClear() + await render('card--real') + expect(loadModule).toHaveBeenCalledWith('Card.astro') + + loadModule.mockClear() + await render('card--real') + expect(loadModule).not.toHaveBeenCalled() + expect(invalidateModuleGraph).toHaveBeenCalledTimes(2) + }) + + test("a mocked story's decorators load with the mocks, and the next story does not reuse them", async () => { + const { loadModule, render } = createMockingHandler() + const node = { component: marker('Wrapper.astro'), slots: { default: marker('Card.astro') } } + + await render('card--real', { node }) + loadModule.mockClear() + await render('card--mocked', { node }) + expect(loadModule).toHaveBeenCalledWith('Wrapper.astro') + + loadModule.mockClear() + await render('card--real', { node }) + expect(loadModule).toHaveBeenCalledWith('Wrapper.astro') + }) +}) diff --git a/packages/storybook-astro/framework/src/astroRenderHandler.ts b/packages/storybook-astro/framework/src/astroRenderHandler.ts new file mode 100644 index 0000000..14caf39 --- /dev/null +++ b/packages/storybook-astro/framework/src/astroRenderHandler.ts @@ -0,0 +1,518 @@ +import { + isAstroComponentFactory, + isAstroComponentMarker, + type SlotValue, + STORY_STYLE_ATTRIBUTE, +} from '@systemfsoftware/storybook-astro-renderer/types' +import type { experimental_AstroContainer as AstroContainer } from 'astro/container' +import { markHTMLString } from 'astro/runtime/server/index.js' +import type { ComponentStyles } from './lib/componentStyles.ts' +import { assertValidSlotValue, reconstructProps, reconstructSlots } from './lib/reconstruct-component-args.ts' +import { reviveDateStrings } from './lib/revive-dates.ts' +import type { ResolvedSanitizationOptions, SanitizationOptions } from './lib/sanitization.ts' +import { resolveSanitizationOptions, sanitizeArgs, sanitizeRenderPayload } from './lib/sanitization.ts' +import { type ResolveRulesConfigModule, runWithStoryRules } from './storyRulesRuntime.ts' +import type { RenderStoryInput } from './types.ts' + +type AstroCreateResult = { + createAstro?: (...args: unknown[]) => unknown +} + +type AstroComponentFactory = + & (( + result: AstroCreateResult, + props: unknown, + slots: unknown, + ) => unknown) + & { + isAstroComponentFactory?: boolean + moduleId?: string + propagation?: unknown + } + +export type HandlerProps = { + component: string + args?: Record + slots?: Record + /** A decorator tree to resolve around the story (Decorator Support, Step 3). */ + node?: SlotValue + story?: RenderStoryInput +} + +type CreateAstroRenderHandlerOptions = { + container: Awaited> + sanitization?: SanitizationOptions + rulesConfigFilePath?: string + resolveRulesConfigModule?: ResolveRulesConfigModule + loadModule: (id: string) => Promise<{ default: unknown }> + invalidateModuleGraph?: () => void + /** + * Returns the compiled CSS for the components a render loaded, plus their + * imports. Prepended to the HTML as ``, + ) + + return styleTags.join('') + html + }, + ) + } + + const resultPromise = renderQueue.then(executeRender, executeRender) + + renderQueue = resultPromise.then( + () => undefined, + () => undefined, + ) + + return resultPromise + } +} + +/** + * Records the module id of every Astro component found in a render request's + * args, slots or decorator tree, in the order they appear, and whether it's a + * real factory: markers are what the browser sends, and factories are what the + * static build passes straight from the story module (Astro's compiler sets + * `moduleId` on each component it compiles). + * + * It walks every level, guarding only against cycles. It may find components + * the slot and prop resolvers never render (past their depth cap, or in a shape + * they don't read), so the caller keeps only the markers that were loaded. + */ +function addComponentModuleIds(value: unknown, moduleIds: Map, seen = new Set()) { + if (isAstroComponentMarker(value)) { + if (!moduleIds.has(value.moduleId)) { + moduleIds.set(value.moduleId, false) + } + + return + } + + if (isAstroComponentFactory(value)) { + const { moduleId } = value as AstroComponentFactory + + if (moduleId) { + moduleIds.set(moduleId, true) + } + + return + } + + if (!Array.isArray(value) && !isRecord(value)) { + return + } + + if (seen.has(value)) { + return + } + seen.add(value) + + // A configured component wraps its slots, so it comes first, whichever + // order its keys were written in. + const values = isRecord(value) && 'component' in value + ? [value.component, ...Object.values(value)] + : Object.values(value) + + values.forEach((item) => addComponentModuleIds(item, moduleIds, seen)) +} + +type ContainerRenderToString = Awaited>['renderToString'] + +/** + * Resolves a decorator root node (Decorator Support, Step 3) to the final HTML + * string. A root node is a {@link SlotValue} — a string, a component reference, + * a configured descriptor, or an array of those — so it's resolved through the + * same `reconstructSlots` machinery that already resolves any other slot's + * component tree, by wrapping it in a one-entry `{ root: node }` record and + * reading `.root` back. + * + * Two things only the root needs, supplied via the callbacks below: + * + * 1. **The story's own args/slots.** The story itself appears in the tree as a + * bare leaf (wherever a decorator placed `Story()`), not a configured + * descriptor, so it carries no props of its own — its args arrived on the + * request's separate top-level `args`/`slots` fields and were already fully + * processed above. `renderToHtml` needs to recognize that leaf and feed it + * those already-processed values instead of rendering it with nothing. + * + * It can't do that by comparing the *loaded* component's own `.moduleId` to + * `ctx.storyComponentId`: in server mode, `loadComponent` loads from a + * deployed snapshot at a different path than the original project + * (`resolveSnapshotComponentPath` in `server/index.ts`), and Astro's compiler + * embeds `.moduleId` from wherever the file was actually compiled — the + * snapshot path, not the original id the client sent as `storyComponentId`. + * Comparing loaded-component identity instead (`storyComponentInstances`, + * populated by the `moduleId` the marker itself carried *before* loading) + * survives that remapping. + * 2. **The full args pipeline for every descriptor's props.** A decorator's own + * `props` (e.g. `{ theme: ctx.globals.theme }`) are user-authored, args-like + * values, so `processProps` runs them through the same + * reconstructProps → processImageMetadata → reviveDateStrings → sanitizeArgs + * pipeline top-level story args get — uniformly for every descriptor in the + * tree, the story's wrapper or not. + */ +async function renderDecoratedRoot( + node: SlotValue, + ctx: { + storyComponentId: string + storyProps: Record + storySlots: Record + sanitizationOptions: ResolvedSanitizationOptions + loadComponent: (moduleId: string) => Promise + renderToString: ContainerRenderToString + }, +): Promise { + // Sanitize the tree's user-authored string/array content first, exactly like + // any other slot value (array wrapper strings sanitize as one document, #149). + // Descriptor `component`/`props` pass through this pass untouched — `props` + // gets the args pipeline afterwards, once component references have loaded. + const { root: sanitizedNode } = sanitizeRenderPayload( + { args: {}, slots: { root: node } }, + ctx.sanitizationOptions, + ).slots + + // Tracks which *loaded* component instances came from `ctx.storyComponentId`, + // keyed by object identity rather than `.moduleId` (see the function doc above). + const storyComponentInstances = new WeakSet() + const loadComponent = async (moduleId: string) => { + const component = await ctx.loadComponent(moduleId) + + if (moduleId === ctx.storyComponentId) { + storyComponentInstances.add(component) + } + + return component + } + + const resolved = await reconstructSlots( + { root: sanitizedNode }, + { + loadComponent, + renderToHtml: (component, props, slots) => { + if (props === undefined && storyComponentInstances.has(component as AstroComponentFactory)) { + return ctx.renderToString(component as Parameters[0], { + props: ctx.storyProps, + slots: markRawSlots(ctx.storySlots), + }) + } + + return ctx.renderToString(component as Parameters[0], { + props: props ?? {}, + slots: markRawSlots(slots ?? {}), + }) + }, + processProps: async (props) => { + const reconstructed = await reconstructProps(props, { loadComponent }) + const imaged = await processImageMetadata(reconstructed) + const revived = reviveDateStrings(imaged) + + return sanitizeArgs(revived, ctx.sanitizationOptions) + }, + }, + ) + + return resolved.root as string +} + +/** + * Marks each slot's HTML string as already-rendered so the Astro Container emits + * it raw instead of escaping it. Astro 5 and 7 render string slots raw anyway, + * but Astro 6 escapes an unmarked string slot — this normalizes all versions. + * `markHTMLString` tags the string via a global symbol, so it's recognized even + * across Astro module instances. + */ +export function markRawSlots(slots: Record): Record { + const marked: Record = {} + + for (const [name, value] of Object.entries(slots)) { + marked[name] = typeof value === 'string' ? markHTMLString(value) : value + } + + return marked +} + +export function patchCreateAstroCompat(component: unknown): AstroComponentFactory { + if (typeof component !== 'function') { + throw new Error('Expected Astro component factory to be a function.') + } + + const originalComponent = component as AstroComponentFactory + const wrapped = ((result: AstroCreateResult, props: unknown, slots: unknown) => { + if (result && typeof result.createAstro === 'function') { + const originalCreateAstro = result.createAstro + const runtimeExpectsAstroGlobal = originalCreateAstro.length >= 3 + + result.createAstro = (...args: unknown[]) => { + if (args.length === 3 && !runtimeExpectsAstroGlobal) { + return originalCreateAstro(args[1], args[2]) + } + + return originalCreateAstro(...args) + } + } + + return originalComponent(result, props, slots) + }) as AstroComponentFactory + + wrapped.isAstroComponentFactory = originalComponent.isAstroComponentFactory + wrapped.moduleId = originalComponent.moduleId + wrapped.propagation = originalComponent.propagation + + return wrapped +} + +export async function processImageMetadata( + args: Record, +): Promise> { + const processed: Record = {} + + for (const [key, value] of Object.entries(args)) { + if (isImageMetadata(value)) { + // Keep ImageMetadata as an object so Astro's image pipeline still + // recognizes it as an imported image and skips local path validation. + processed[key] = value + + continue + } + + if (Array.isArray(value)) { + processed[key] = await Promise.all( + value.map(async (item) => { + if (isImageMetadata(item)) { + return item + } + + if (isRecord(item)) { + return processImageMetadata(item) + } + + return item + }), + ) + + continue + } + + if (isRecord(value)) { + processed[key] = await processImageMetadata(value) + + continue + } + + processed[key] = value + } + + return processed +} + +function isImageMetadata(value: unknown): value is Record { + return ( + isRecord(value) && + typeof value.src === 'string' && + ('width' in value || 'height' in value || 'format' in value) + ) +} + +// Only plain objects are walked/rebuilt. Other object types (Date, RegExp, +// class instances, …) are left intact — recursing into a Date with +// Object.entries would flatten it to {}, which is how a story's Date arg ended +// up as an invalid date during static prerendering. +function isRecord(value: unknown): value is Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false + } + + const prototype = Object.getPrototypeOf(value) + + return prototype === Object.prototype || prototype === null +} + +function errorMessage(error: unknown) { + return error instanceof Error ? error.message : String(error) +} diff --git a/packages/storybook-astro/framework/src/csf4-decorators.test.ts b/packages/storybook-astro/framework/src/csf4-decorators.test.ts new file mode 100644 index 0000000..2c251de --- /dev/null +++ b/packages/storybook-astro/framework/src/csf4-decorators.test.ts @@ -0,0 +1,54 @@ +import { type AstroComponentFactory, isAstroComponentSlot } from '@systemfsoftware/storybook-astro-renderer/types' +import { expect, test } from 'vitest' +import { definePreview } from './index.ts' +import { composeStory } from './testing/story-composition.ts' + +function fakeAstroComponent(moduleId: string): AstroComponentFactory { + const factory = (() => undefined) as unknown as AstroComponentFactory + + factory.isAstroComponentFactory = true + factory.moduleId = moduleId + + return factory +} + +const Wrapper = fakeAstroComponent('test:Wrapper') +const Widget = fakeAstroComponent('test:Widget') + +// CSF4 coverage (docs/specs/decorators.md#global-decorators): `definePreview` in +// index.ts merges `applyDecorators: input.applyDecorators ?? applyDecorators` +// into the project annotations it hands to Storybook's `definePreviewBase`, +// the same way it merges `render` — this proves a preview built that way +// composes a CSF4 story (`preview.meta().story()`) into the same decorated +// `SlotValue` tree that a plain `.storybook/preview.js` `decorators` array +// produces for CSF3 stories (see Decorator.test.ts in packages/components). +// +// Known limitation, confirmed empirically against Storybook 10.5.2 and left +// undocumented in code otherwise (see the Step 6 report for detail): the CSF4 +// story must be composed with `composeStory` (singular), passing +// `meta.input` — not `meta` itself — as the component annotations. A real +// `.stories.ts` file's `export default meta` is the `meta` wrapper object, and +// neither Storybook's own `composeStories` nor `composeStory` unwrap it to +// `meta.input` automatically, so passing it directly throws "component +// annotation is missing from the default export". Calling the CSF4 story's +// own `.run()` isn't a Node-testable alternative either — it always renders +// through `definePreview`'s production `render`, which needs a browser +// (`document is not defined` outside one). +test('definePreview composes a CSF4 story through applyDecorators into a decorated tree', async () => { + const preview = definePreview({ + decorators: [(_Story) => ({ component: Wrapper })], + }) + + const meta = preview.meta({ component: Widget }) + const story = meta.story({}) + + // `story` (a CSF4 Story factory object) and `meta.input` (its plain + // ComponentAnnotations) don't match `composeStory`'s CSF3-shaped types, but + // are exactly what it expects at runtime — see the limitation note above. + const composed = composeStory(story as any, meta.input as any) + const tree = await (composed as unknown as () => unknown)() + + expect(isAstroComponentSlot(tree)).toBe(true) + expect((tree as { component: unknown }).component).toBe(Wrapper) + expect((tree as { slots: { default: unknown } }).slots.default).toBe(Widget) +}) diff --git a/packages/storybook-astro/framework/src/docgen/apiDescription.test.ts b/packages/storybook-astro/framework/src/docgen/apiDescription.test.ts new file mode 100644 index 0000000..8aba60e --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/apiDescription.test.ts @@ -0,0 +1,217 @@ +import { extractArgTypes } from '@systemfsoftware/storybook-astro-renderer/extractArgTypes' +import { describe, expect, test } from 'vitest' +import { formatApiDescription } from './apiDescription.ts' +import type { AstroDocgenInfo, AstroDocgenProp } from './types.ts' + +function prop(name: string, overrides: Partial = {}): AstroDocgenProp { + return { + name, + required: false, + type: { name: 'string' }, + description: '', + defaultValue: null, + ...overrides, + } +} + +/** Formats a component the way the docgen payload does, from the table's argTypes. */ +function describeComponent(info: Partial) { + const component: AstroDocgenInfo = { displayName: 'Card', description: '', props: {}, ...info } + + return formatApiDescription(extractArgTypes({ __docgenInfo: component }), component) +} + +describe('the props an agent reads', () => { + test('lists required, optional, defaulted and described props as a Props type', () => { + const markdown = describeComponent({ + props: { + title: prop('title', { required: true, description: 'Heading text.' }), + subtitle: prop('subtitle'), + featured: prop('featured', { + type: { name: 'boolean' }, + defaultValue: { value: 'false', source: 'false' }, + }), + variant: prop('variant', { + description: 'How loud the card is.', + type: { + name: 'enum', + raw: '"primary" | "secondary"', + value: [{ value: '"primary"' }, { value: '"secondary"' }], + }, + defaultValue: { value: "'primary'", source: "'primary'" }, + }), + }, + }) + + expect(markdown).toBe( + [ + '## Props', + '', + '```', + 'export type Props = {', + ' /**', + ' Heading text.', + ' */', + ' title: string;', + ' subtitle?: string;', + ' featured?: boolean = false;', + ' /**', + ' How loud the card is.', + ' */', + ' variant?: "primary" | "secondary" = \'primary\';', + '}', + '```', + ].join('\n'), + ) + }) + + test('prints the whole type when the table shows a shortened one (issue #357)', () => { + const untruncated = '{ heading: string; subheading: string; footer: string; }' + const markdown = describeComponent({ + props: { + labels: prop('labels', { type: { name: '{ heading: string; ...; }', untruncated } }), + }, + }) + + expect(markdown).toContain(` labels?: ${untruncated};`) + }) + + test('keeps every line of a multi-line description inside the comment', () => { + const markdown = describeComponent({ + props: { + href: prop('href', { description: 'Where the card links.\n\nUse */ with care.' }), + }, + }) + + expect(markdown).toContain( + [' /**', ' Where the card links.', '', ' Use *\\/ with care.', ' */'].join('\n'), + ) + }) + + test('spells out a named literal union, since its type text is only the alias', () => { + const markdown = describeComponent({ + props: { + variant: prop('variant', { + type: { + name: 'enum', + raw: 'Variant', + value: [{ value: '"primary"' }, { value: '"secondary"' }], + }, + }), + }, + }) + + expect(markdown).toContain(' variant?: "primary" | "secondary";') + }) + + test('prints a default as the component wrote it, whatever the declared type', () => { + const markdown = describeComponent({ + props: { + href: prop('href', { + type: { name: 'string | URL' }, + defaultValue: { value: "'/home'", source: "'/home'" }, + }), + title: prop('title', { defaultValue: { value: 'defaultTitle', source: 'defaultTitle' } }), + }, + }) + + expect(markdown).toContain(" href?: string | URL = '/home';") + expect(markdown).toContain(' title?: string = defaultTitle;') + }) + + test('prints a null default', () => { + const markdown = describeComponent({ + props: { + nothing: prop('nothing', { + type: { name: 'string | null' }, + defaultValue: { value: 'null', source: 'null' }, + }), + }, + }) + + expect(markdown).toContain(' nothing?: string | null = null;') + }) + + test('keeps a multi-line array default written in the source on its prop line', () => { + const source = "[\n 'a',\n 'b'\n]" + const markdown = describeComponent({ + props: { + items: prop('items', { type: { name: 'string[]' }, defaultValue: { value: source, source: source } }), + }, + }) + + expect(markdown).toContain(" items?: string[] = [ 'a', 'b' ];\n}") + }) + + test('keeps the spacing inside a string default', () => { + const markdown = describeComponent({ + props: { + label: prop('label', { defaultValue: { value: "'Read more'", source: "'Read more'" } }), + }, + }) + + expect(markdown).toContain(" label?: string = 'Read more';") + }) +}) + +describe('the slots an agent reads', () => { + test('lists each slot with its description, and how to fill a named one', () => { + const markdown = describeComponent({ + props: { title: prop('title') }, + slots: [ + { name: 'default', description: 'The card body' }, + { name: 'actions', description: '' }, + ], + }) + + expect(markdown).toContain( + [ + '## Slots', + '', + '- `default` (child content): The card body', + '- `actions`', + '', + "In a story, pass slot content in `args.slots` (`slots: { : '…' }`). " + + 'In an Astro template, put `slot=""` on the child element.', + ].join('\n'), + ) + // Slot rows live in the same argTypes, but they are not props. + expect(markdown).not.toContain('slot-default') + }) + + test('a component with only a default slot is told to fill it through args.slots', () => { + const markdown = describeComponent({ slots: [{ name: 'default', description: '' }] }) + + expect(markdown).toBe( + [ + '## Slots', + '', + '- `default` (child content)', + '', + "In a story, pass slot content in `args.slots` (`slots: { default: '…' }`).", + ].join('\n'), + ) + }) + + test('keeps a wrapped @slot description in one list item', () => { + const markdown = describeComponent({ + slots: [{ name: 'footer', description: 'Shown under the body.\n * Accepts markup.\nKeep it short.' }], + }) + + expect(markdown).toContain( + ['## Slots', '', '- `footer`: Shown under the body. Accepts markup. Keep it short.', ''].join('\n'), + ) + }) + + test('keeps Markdown emphasis at the start of a slot description line', () => { + const markdown = describeComponent({ + slots: [{ name: 'body', description: '**Required.** The body\n*Optional* footer' }], + }) + + expect(markdown).toContain('- `body`: **Required.** The body *Optional* footer\n') + }) +}) + +test('a component with no props or slots has no API description', () => { + expect(describeComponent({})).toBeUndefined() +}) diff --git a/packages/storybook-astro/framework/src/docgen/apiDescription.ts b/packages/storybook-astro/framework/src/docgen/apiDescription.ts new file mode 100644 index 0000000..55ebc31 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/apiDescription.ts @@ -0,0 +1,117 @@ +import type { StrictArgTypes } from 'storybook/internal/types' +import type { AstroDocgenInfo } from './types.ts' + +/** + * The Markdown `DocgenPayload.apiDescription` carries: a component's props and + * slots, for AI agents reading `@storybook/addon-mcp`'s `docs-show` and for + * `/manifests/components.html`. + * + * Storybook core drops `argTypes` before it formats a component for an agent + * and builds the props section only from React docgen, so without this an + * Astro component reaches the agent with no props (issue #353). The props + * section copies the shape core gives React components (`formatPropsSection` + * in core's docs toolset), so an agent reads both the same way. + * + * It is built from the extractor's argTypes, the rows the props table starts + * from, so a prop the extractor leaves out (the prop filter) is left out + * here too. Defaults print as the author wrote them, from the extractor's + * `defaultValue.source`. A story's `argTypes` aren't applied: + * `table: { disable: true }` there hides a row from the table only. + * The type text comes from the extractor, untruncated, and a literal union + * prints as its members, since the table summarizes it as `enum` and the + * extractor's type text names an aliased union (`type Variant = …`) only by + * its alias. + */ +export function formatApiDescription( + argTypes: StrictArgTypes | null, + info: AstroDocgenInfo, +): string | undefined { + const sections = [...propsSection(argTypes, info), ...slotsSection(info)] + + return sections.length > 0 ? sections.join('\n').trim() : undefined +} + +function propsSection(argTypes: StrictArgTypes | null, info: AstroDocgenInfo): string[] { + // Slot rows share the argTypes; only keys the extractor read as props count. + const props = Object.entries(argTypes ?? {}).filter(([key]) => key in info.props) + + if (props.length === 0) { + return [] + } + + const lines = ['## Props', '', '```', 'export type Props = {'] + + for (const [key, argType] of props) { + const { type, defaultValue } = info.props[key] + // `null` and `undefined` members aren't in `value`, so a required + // `'a' | 'b' | null` prints without its `| null`. + const typeText = type.name === 'enum' && type.value + ? type.value.map(({ value }) => value).join(' | ') + : (type.untruncated ?? type.name) + const optional = argType.type?.required ? '' : '?' + // An array or object default keeps its source's line breaks, which would + // read as stray members of the type. Only whitespace around a line break + // goes, so spaces inside a string literal stay as written. + const defaultText = defaultValue + ? ` = ${defaultValue.source.replace(/\s*\n\s*/g, ' ')}` + : '' + + lines.push(...docComment(argType.description)) + lines.push(` ${key}${optional}: ${typeText}${defaultText};`) + } + + lines.push('}', '```', '') + + return lines +} + +function slotsSection(info: AstroDocgenInfo): string[] { + const slots = info.slots ?? [] + + if (slots.length === 0) { + return [] + } + + const lines = ['## Slots', ''] + + for (const { name, description } of slots) { + const label = name === 'default' ? '`default` (child content)' : `\`${name}\`` + // A wrapped `@slot` comment would otherwise break out of its list item. + // Only a continuation line's JSDoc `*` goes, not Markdown emphasis. + const text = description + .split('\n') + .map((line, index) => index === 0 ? line.trim() : line.replace(/^\s*\*(?:\s+|$)/, '').trim()) + .filter(Boolean) + .join(' ') + + lines.push(text ? `- ${label}: ${text}` : `- ${label}`) + } + + lines.push('') + + // Astro stories have no `children` arg, so even a default slot needs saying. + if (slots.some(({ name }) => name !== 'default')) { + lines.push( + "In a story, pass slot content in `args.slots` (`slots: { : '…' }`). " + + 'In an Astro template, put `slot=""` on the child element.', + '', + ) + } else { + lines.push("In a story, pass slot content in `args.slots` (`slots: { default: '…' }`).", '') + } + + return lines +} + +function docComment(description: string | undefined): string[] { + const text = description?.trim() + + if (!text) { + return [] + } + + // A `*/` inside the description would close the comment early. + const lines = text.replaceAll('*/', '*\\/').split('\n') + + return [' /**', ...lines.map((line) => (line ? ` ${line}` : '')), ' */'] +} diff --git a/packages/storybook-astro/framework/src/docgen/defaultValues.test.ts b/packages/storybook-astro/framework/src/docgen/defaultValues.test.ts new file mode 100644 index 0000000..afddbb5 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/defaultValues.test.ts @@ -0,0 +1,108 @@ +import typescript from 'typescript' +import { describe, expect, test } from 'vitest' +import { readAstroPropsBinding } from './defaultValues.ts' +import { buildVirtualSource } from './virtualFile.ts' + +/** Reads the binding out of real `.astro` frontmatter, the way the extractor does. */ +function bindingFor(frontmatter: string) { + const source = buildVirtualSource(`---\n${frontmatter}\n---\n
`) as string + const sourceFile = typescript.createSourceFile( + '/src/Component.astro.ts', + source, + typescript.ScriptTarget.Latest, + true, + ) + + return readAstroPropsBinding(typescript, sourceFile) +} + +describe('defaults are read from the destructuring pattern', () => { + test.each([ + ["const { a = 'x' } = Astro.props;", "'x'"], + ['const { a = "x" } = Astro.props;', '"x"'], + ['const { a = 42 } = Astro.props;', '42'], + ['const { a = -1 } = Astro.props;', '-1'], + ['const { a = true } = Astro.props;', 'true'], + ['const { a = null } = Astro.props;', 'null'], + ['const { a = undefined } = Astro.props;', 'undefined'], + ['const { a = `x` } = Astro.props;', '`x`'], + ['const { a = defaultNavItems } = Astro.props;', 'defaultNavItems'], + ["const { a = ['a', 'b'] } = Astro.props;", "['a', 'b']"], + ['const { a = -offset } = Astro.props;', '-offset'], + ['const { a = `${base}/home` } = Astro.props;', '`${base}/home`'], + ])('a default keeps its source text: %s', (frontmatter, expected) => { + expect(bindingFor(frontmatter).defaults.get('a')?.source).toBe(expected) + }) + + test.each([ + ["const { a = 'x' } = Astro.props;", 'x'], + ['const { a = `x` } = Astro.props;', 'x'], + ['const { a = 42 } = Astro.props;', 42], + ['const { a = -1 } = Astro.props;', -1], + ['const { a = true } = Astro.props;', true], + ['const { a = null } = Astro.props;', null], + ['const { a = defaultNavItems } = Astro.props;', 'defaultNavItems'], + ])('a prop filter still reads a literal default as its value: %s', (frontmatter, expected) => { + expect(bindingFor(frontmatter).defaults.get('a')?.value).toBe(expected) + }) + + test('a prop destructured without a default has none', () => { + const binding = bindingFor('const { a } = Astro.props;') + + expect(binding.defaults.has('a')).toBe(false) + expect(binding.destructured.has('a')).toBe(true) + }) +}) + +describe('the annotated forms of Astro.props are all recognised', () => { + test.each([ + 'const { a = 1 } = Astro.props;', + 'const { a = 1 } = Astro.props as Props;', + 'const { a = 1 } = Astro.props satisfies Props;', + 'const { a = 1 } = (Astro.props as Props);', + ])('%s', (frontmatter) => { + expect(bindingFor(frontmatter).defaults.get('a')?.source).toBe('1') + }) +}) + +describe('the destructured set is the component author’s public surface', () => { + test('a renamed binding records the prop name, not the local alias', () => { + const binding = bindingFor("const { class: className = 'card' } = Astro.props;") + + expect(binding.destructured.has('class')).toBe(true) + expect(binding.destructured.has('className')).toBe(false) + expect(binding.defaults.get('class')?.source).toBe("'card'") + }) + + test('a rest element is not a prop', () => { + const binding = bindingFor('const { as = "button", ...rest } = Astro.props;') + + expect([...binding.destructured]).toEqual(['as']) + }) + + test('every destructured name is captured, defaulted or not', () => { + const binding = bindingFor( + "const { as = 'button', href, disabled = false } = Astro.props as Props;", + ) + + expect([...binding.destructured].sort()).toEqual(['as', 'disabled', 'href']) + }) +}) + +describe('unrelated code is left alone', () => { + test('a destructure of something other than Astro.props', () => { + expect(bindingFor('const { a = 1 } = someOtherObject;').destructured.size).toBe(0) + }) + + test('Astro.props read without destructuring', () => { + expect(bindingFor('const props = Astro.props;').destructured.size).toBe(0) + }) + + test('a destructure nested in a function is not the component surface', () => { + const binding = bindingFor( + ['function helper() {', ' const { a = 1 } = Astro.props;', '}'].join('\n'), + ) + + expect(binding.destructured.size).toBe(0) + }) +}) diff --git a/packages/storybook-astro/framework/src/docgen/defaultValues.ts b/packages/storybook-astro/framework/src/docgen/defaultValues.ts new file mode 100644 index 0000000..efd19d1 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/defaultValues.ts @@ -0,0 +1,132 @@ +import type ts from 'typescript' +import type { AstroDocgenDefault } from './types.ts' + +export interface AstroPropsBinding { + /** Prop name → its default, for props destructured with one. */ + defaults: Map + /** + * Every prop name the component destructures, with or without a default. + * + * This is the author's own statement of the public surface, so the prop + * filter keeps these regardless of where they were declared — it is what + * recovers `as`, `href` and `class` on a polymorphic component whose types + * all come from `node_modules` (docs/specs/docgen.md#prop-filtering). + */ + destructured: Set +} + +/** + * Reads `const { … } = Astro.props` from a component's frontmatter. + * + * Only top-level statements are considered: a destructure nested inside a + * function isn't the component's prop surface. The `as Props` and + * `satisfies Props` forms are both recognised, since neither changes what is + * being destructured. + */ +export function readAstroPropsBinding( + typescript: typeof ts, + sourceFile: ts.SourceFile, +): AstroPropsBinding { + const defaults = new Map() + const destructured = new Set() + + for (const statement of sourceFile.statements) { + if (!typescript.isVariableStatement(statement)) { + continue + } + + for (const declaration of statement.declarationList.declarations) { + if ( + !declaration.initializer || + !isAstroProps(typescript, declaration.initializer) || + !typescript.isObjectBindingPattern(declaration.name) + ) { + continue + } + + for (const element of declaration.name.elements) { + // `...rest` collects whatever is left over; it isn't a prop itself. + if (element.dotDotDotToken) { + continue + } + + // `{ class: className }` documents `class`, not `className`. The prior + // art read the binding name here and so recorded the local alias. + const propName = (element.propertyName ?? element.name).getText(sourceFile) + + destructured.add(propName) + + if (element.initializer) { + defaults.set(propName, { + value: literalValueOf(typescript, element.initializer, sourceFile), + source: element.initializer.getText(sourceFile), + }) + } + } + } + } + + return { defaults, destructured } +} + +/** Matches `Astro.props`, `Astro.props as Props` and `Astro.props satisfies Props`. */ +function isAstroProps(typescript: typeof ts, node: ts.Expression): boolean { + let expression = node + + while ( + typescript.isAsExpression(expression) || + typescript.isSatisfiesExpression(expression) || + typescript.isTypeAssertionExpression(expression) || + typescript.isParenthesizedExpression(expression) + ) { + expression = expression.expression + } + + return ( + typescript.isPropertyAccessExpression(expression) && + typescript.isIdentifier(expression.expression) && + expression.expression.text === 'Astro' && + expression.name.text === 'props' + ) +} + +/** + * Narrows an initializer to something safe to serialise into the bundle. + * Anything that isn't a plain literal keeps its source text, which is what + * readers want to see for `navItems = defaultNavItems`. + */ +function literalValueOf( + typescript: typeof ts, + node: ts.Expression, + sourceFile: ts.SourceFile, +): string | number | boolean | null { + if (typescript.isStringLiteral(node) || typescript.isNoSubstitutionTemplateLiteral(node)) { + return node.text + } + + if (node.kind === typescript.SyntaxKind.TrueKeyword) { + return true + } + + if (node.kind === typescript.SyntaxKind.FalseKeyword) { + return false + } + + if (node.kind === typescript.SyntaxKind.NullKeyword) { + return null + } + + if (typescript.isNumericLiteral(node)) { + return Number(node.text) + } + + if ( + typescript.isPrefixUnaryExpression(node) && + node.operator === typescript.SyntaxKind.MinusToken && + typescript.isNumericLiteral(node.operand) + ) { + return -Number(node.operand.text) + } + + return node.getText(sourceFile) +} diff --git a/packages/storybook-astro/framework/src/docgen/description.ts b/packages/storybook-astro/framework/src/docgen/description.ts new file mode 100644 index 0000000..2f9c9bd --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/description.ts @@ -0,0 +1,105 @@ +import type ts from 'typescript' + +export interface ComponentDescription { + /** Free text only — block tags are split out so they don't render as noise. */ + text: string + tags?: Record +} + +/** + * Finds the component's description in its frontmatter. + * + * A "floating" JSDoc block isn't floating: TypeScript attaches it to whatever + * statement follows, so the block above `const buttonVariants = cva(…)` is + * reachable from that statement. Precedence, first non-empty winning + * (docs/specs/docgen.md#description-precedence): + * + * 1. the first statement whose JSDoc carries `@component` or `@description` + * 2. JSDoc on the `Props` declaration + * 3. the frontmatter's leading block, whatever statement it attaches to + * + * Rule 3 deliberately does not care that the leading block usually attaches to + * an import: Astro frontmatter puts imports first, so a component description + * written at the top of the file almost always lands on one. What keeps this + * honest is that the block must be the *first* thing in the frontmatter — the + * prior art takes the first block found anywhere by regex, so a JSDoc on the + * third import or on some mid-file constant becomes the component description. + */ +export function readComponentDescription( + typescript: typeof ts, + sourceFile: ts.SourceFile, +): ComponentDescription { + const blocks = sourceFile.statements.map((statement) => ({ + statement, + tags: tagsOf(typescript, statement), + text: freeTextOf(typescript, statement), + })) + + const explicit = blocks.find((block) => 'component' in block.tags || 'description' in block.tags) + + if (explicit) { + const { description, ...rest } = explicit.tags + + return { + text: description || explicit.text, + tags: Object.keys(rest).length > 0 ? rest : undefined, + } + } + + const props = blocks.find( + (block) => + (typescript.isInterfaceDeclaration(block.statement) || + typescript.isTypeAliasDeclaration(block.statement)) && + block.statement.name.text === 'Props' && + block.text, + ) + + if (props) { + return { text: props.text, tags: tagsOrUndefined(props.tags) } + } + + const [leading] = blocks + + if (leading?.text) { + return { text: leading.text, tags: tagsOrUndefined(leading.tags) } + } + + return { text: '' } +} + +function tagsOrUndefined(tags: Record): Record | undefined { + return Object.keys(tags).length > 0 ? tags : undefined +} + +function tagsOf(typescript: typeof ts, node: ts.Node): Record { + const tags: Record = {} + + for (const tag of typescript.getJSDocTags(node)) { + tags[tag.tagName.text] = commentToString(typescript, tag.comment).trim() + } + + return tags +} + +/** The prose above the first block tag, which is what a description should be. */ +function freeTextOf(typescript: typeof ts, node: ts.Node): string { + return typescript + .getJSDocCommentsAndTags(node) + .filter((each): each is ts.JSDoc => !!(each as ts.JSDoc).comment || 'tags' in each) + .map((each) => commentToString(typescript, (each as ts.JSDoc).comment)) + .join('\n') + .trim() +} + +function commentToString( + typescript: typeof ts, + comment: string | ts.NodeArray | undefined, +): string { + if (comment === undefined) { + return '' + } + + return typeof comment === 'string' + ? comment + : typescript.displayPartsToString(comment as unknown as ts.SymbolDisplayPart[]) +} diff --git a/packages/storybook-astro/framework/src/docgen/docgen-payload.test.ts b/packages/storybook-astro/framework/src/docgen/docgen-payload.test.ts new file mode 100644 index 0000000..bb4dd32 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/docgen-payload.test.ts @@ -0,0 +1,350 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { IndexEntry } from 'storybook/internal/types' +import { afterAll, beforeAll, describe, expect, test } from 'vitest' +import { buildDocgenPayload, type DocgenSource } from './docgen-payload.ts' +import { createAstroDocgen } from './index.ts' +import type { AstroDocgenInfo } from './types.ts' + +// Inside the package so `astro/types` resolves by walking up, matching the +// existing .vitest-*-fixture-* convention. +const packageDir = fileURLToPath(new URL('../..', import.meta.url)) +const workingDir = mkdtempSync(join(packageDir, '.vitest-payload-fixture-')) + +const write = (name: string, lines: string[]) => writeFileSync(join(workingDir, name), lines.join('\n')) + +beforeAll(() => { + write('Card.astro', [ + '---', + '/**', + ' * A card that holds a heading.', + ' * @deprecated use Panel instead', + ' */', + 'interface Props {', + ' /** Heading text. */', + ' title?: string;', + '}', + "const { title = 'Hello' } = Astro.props;", + '---', + '

{title}

', + ]) + + write('Badge.astro', [ + '---', + "type Variant = 'primary' | 'secondary';", + 'interface Props {', + ' variant?: Variant;', + '}', + "const { variant = 'primary' } = Astro.props;", + '---', + 'Badge', + ]) + + write('Link.astro', [ + '---', + "const defaultLabel = 'Read more';", + 'interface Props {', + ' href?: string | URL;', + ' label?: string;', + ' icon?: string | null;', + ' /** @ignore */', + ' trackingId?: string;', + '}', + "const { href = '/home', label = defaultLabel, icon = null, trackingId } = Astro.props;", + '---', + '{icon}{label}', + ]) + + write('Link.stories.jsx', [ + "import Link from './Link.astro';", + '', + 'export default {', + " title: 'Astro/Link',", + ' component: Link', + '};', + '', + 'export const Default = {};', + ]) + + write('Badge.stories.jsx', [ + "import Badge from './Badge.astro';", + '', + 'export default {', + " title: 'Astro/Badge',", + ' component: Badge', + '};', + '', + 'export const Default = {};', + ]) + + write('Card.stories.jsx', [ + "import Card from './Card.astro';", + '', + 'export default {', + " title: 'Astro/Card',", + ' component: Card', + '};', + '', + 'export const Default = {};', + ]) + + write('Renamed.stories.jsx', [ + "import TheCard from './Card.astro';", + '', + '/** The story file has the last word on the description. */', + 'export default {', + " title: 'Astro/Renamed',", + ' component: TheCard', + '};', + '', + 'export const Default = {};', + ]) + + write('Widget.tsx', ['export const Widget = () => null;']) + + write('Widget.stories.jsx', [ + "import { Widget } from './Widget.tsx';", + '', + 'export default {', + " title: 'React/Widget',", + ' component: Widget', + '};', + '', + 'export const Default = {};', + ]) + + write('Nameless.stories.jsx', [ + 'export default {', + " title: 'Astro/Nameless'", + '};', + '', + 'export const Default = { render: () => null };', + ]) + + write('Broken.stories.jsx', ['export default { title: "Astro/Broken", component: ((( };']) +}) + +afterAll(() => rmSync(workingDir, { recursive: true, force: true })) + +function storyEntry(importPath: string, title: string): IndexEntry { + return { + type: 'story', + subtype: 'story', + id: `${title.toLowerCase().replace(/\W+/g, '-')}--default`, + name: 'Default', + title, + importPath: `./${importPath}`, + } as IndexEntry +} + +/** A stand-in extractor, so the branchy cases don't each warm a TypeScript program. */ +function stubSource(info: Partial = {}): DocgenSource & { calls: string[] } { + const calls: string[] = [] + + return { + calls, + async extract(path) { + calls.push(path) + + return { + displayName: 'Card', + description: 'A card that holds a heading.', + props: {}, + ...info, + } + }, + } +} + +const build = (entry: IndexEntry, docgen: DocgenSource) => buildDocgenPayload({ entry }, { docgen, workingDir }) + +describe('an Astro story', () => { + test('reads the real component into a payload', async () => { + const docgen = createAstroDocgen({ projectRoot: workingDir }) + const payload = await build(storyEntry('Card.stories.jsx', 'Astro/Card'), docgen) + + expect(payload).toMatchObject({ + id: 'astro-card', + name: 'Card', + path: './Card.stories.jsx', + description: 'A card that holds a heading.', + renderer: 'astro', + }) + expect(payload?.argTypes?.title).toMatchObject({ + name: 'title', + description: 'Heading text.', + // As the component writes it, as React's react-docgen tables show it. + table: { defaultValue: { summary: "'Hello'" } }, + }) + + docgen.dispose() + }) + + test('describes the props in Markdown for AI agents, which never see argTypes', async () => { + const docgen = createAstroDocgen({ projectRoot: workingDir }) + const payload = await build(storyEntry('Card.stories.jsx', 'Astro/Card'), docgen) + + expect(payload?.apiDescription).toBe( + [ + '## Props', + '', + '```', + 'export type Props = {', + ' /**', + ' Heading text.', + ' */', + " title?: string = 'Hello';", + '}', + '```', + ].join('\n'), + ) + + docgen.dispose() + }) + + test('spells out the members of an aliased literal union for AI agents', async () => { + const docgen = createAstroDocgen({ projectRoot: workingDir }) + const payload = await build(storyEntry('Badge.stories.jsx', 'Astro/Badge'), docgen) + + expect(payload?.apiDescription).toContain( + ` variant?: "primary" | "secondary" = 'primary';`, + ) + + docgen.dispose() + }) + + test('shows each default as the component writes it (issue #355)', async () => { + const docgen = createAstroDocgen({ projectRoot: workingDir }) + const payload = await build(storyEntry('Link.stories.jsx', 'Astro/Link'), docgen) + const tableDefault = (name: string) => payload?.argTypes?.[name]?.table?.defaultValue + + // A string on a type that isn't exactly `string` keeps its quotes. + expect(tableDefault('href')).toEqual({ summary: "'/home'" }) + // An identifier on a `string` prop isn't quoted as if it were text. + expect(tableDefault('label')).toEqual({ summary: 'defaultLabel' }) + expect(tableDefault('icon')).toEqual({ summary: 'null' }) + expect(payload?.apiDescription).toContain(" href?: string | URL = '/home';") + expect(payload?.apiDescription).toContain(' label?: string = defaultLabel;') + expect(payload?.apiDescription).toContain(' icon?: string | null = null;') + + docgen.dispose() + }) + + test('leaves out a prop marked @ignore, for the table and AI agents alike (issue #356)', async () => { + const docgen = createAstroDocgen({ projectRoot: workingDir }) + const payload = await build(storyEntry('Link.stories.jsx', 'Astro/Link'), docgen) + + expect(Object.keys(payload?.argTypes ?? {})).toEqual(['href', 'label', 'icon']) + expect(payload?.apiDescription).not.toContain('trackingId') + + docgen.dispose() + }) + + test('carries the component JSDoc tags through', async () => { + const docgen = createAstroDocgen({ projectRoot: workingDir }) + const payload = await build(storyEntry('Card.stories.jsx', 'Astro/Card'), docgen) + + expect(payload?.jsDocTags.deprecated).toEqual(['use Panel instead']) + + docgen.dispose() + }) + + test("names the component after the story file's import", async () => { + const payload = await build(storyEntry('Renamed.stories.jsx', 'Astro/Renamed'), stubSource()) + + expect(payload?.name).toBe('TheCard') + }) + + test("the story meta's own docblock wins over the component description", async () => { + const payload = await build(storyEntry('Renamed.stories.jsx', 'Astro/Renamed'), stubSource()) + + expect(payload?.description).toBe('The story file has the last word on the description.') + }) +}) + +describe('slots on the Docgen Server path', () => { + test('each get a text control, which the preview seeds and locks from the story', async () => { + const docgen = stubSource({ slots: [{ name: 'default', description: 'The card body' }] }) + const payload = await build(storyEntry('Card.stories.jsx', 'Astro/Card'), docgen) + + expect(payload?.argTypes?.['slot-default']).toMatchObject({ + name: 'default', + description: 'The card body', + control: { type: 'text' }, + table: { category: 'slots' }, + }) + expect(payload?.apiDescription).toContain('- `default` (child content): The card body') + }) +}) + +describe('a static build (issue #375)', () => { + test('turns off every control, since the stories are pre-rendered', async () => { + const docgen = stubSource({ + props: { + title: { + name: 'title', + required: false, + type: { name: 'string' }, + description: '', + defaultValue: null, + }, + }, + slots: [ + { name: 'default', description: '' }, + { name: 'footer', description: '' }, + ], + }) + const payload = await buildDocgenPayload( + { entry: storyEntry('Card.stories.jsx', 'Astro/Card') }, + { docgen, workingDir, prerendered: true }, + ) + + const rows = Object.values(payload?.argTypes ?? {}) + + expect(rows.length).toBeGreaterThan(2) + expect(rows.every((row) => row.control === false)).toBe(true) + // The table still describes the slot. + expect(payload?.argTypes?.['slot-footer']).toMatchObject({ name: 'footer' }) + }) +}) + +describe('stories that are not ours', () => { + test('a framework component is left to its own provider', async () => { + const docgen = stubSource() + const payload = await build(storyEntry('Widget.stories.jsx', 'React/Widget'), docgen) + + expect(payload).toBeUndefined() + // Never opened: a .tsx is not something our extractor can read. + expect(docgen.calls).toEqual([]) + }) + + test('a story with no meta.component is passed downstream', async () => { + expect( + await build(storyEntry('Nameless.stories.jsx', 'Astro/Nameless'), stubSource()), + ).toBeUndefined() + }) + + test('an indexed entry whose file is gone is passed downstream', async () => { + expect( + await build(storyEntry('Deleted.stories.jsx', 'Astro/Deleted'), stubSource()), + ).toBeUndefined() + }) + + test('a component that yields no docgen is passed downstream', async () => { + const empty: DocgenSource = { extract: async () => null } + + expect(await build(storyEntry('Card.stories.jsx', 'Astro/Card'), empty)).toBeUndefined() + }) +}) + +describe('a story file that will not parse', () => { + test('is reported on the payload rather than swallowed', async () => { + const payload = await build(storyEntry('Broken.stories.jsx', 'Astro/Broken'), stubSource()) + + expect(payload?.error?.name).toBe('Story file could not be parsed') + expect(payload?.error?.message).toContain('./Broken.stories.jsx') + // The name still falls back to the title so the docs page has a heading. + expect(payload?.name).toBe('Broken') + }) +}) diff --git a/packages/storybook-astro/framework/src/docgen/docgen-payload.ts b/packages/storybook-astro/framework/src/docgen/docgen-payload.ts new file mode 100644 index 0000000..d9be4d0 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/docgen-payload.ts @@ -0,0 +1,174 @@ +import { extractArgTypes } from '@systemfsoftware/storybook-astro-renderer/extractArgTypes' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { + createMetaComponentResolver, + getComponentIdFromEntry, + getStoryImportPathFromEntry, +} from 'storybook/internal/common' +import { type CsfFile, extractComponentDescription, extractDescription, loadCsf } from 'storybook/internal/csf-tools' +import type { DocgenPayload, DocgenProviderInput, StrictArgTypes } from 'storybook/internal/types' +import { formatApiDescription } from './apiDescription.ts' +import type { AstroDocgenInfo } from './types.ts' + +/** One instance per worker: the resolver caches its module resolutions. */ +const resolveMetaComponent = createMetaComponentResolver({ extensions: ['.astro'] }) + +/** Reads one component's docgen. Satisfied by `AstroDocgen` from `./index.ts`. */ +export interface DocgenSource { + extract(astroFilePath: string, astroSource: string): Promise +} + +export interface DocgenPayloadContext { + docgen: DocgenSource + /** + * Directory the story index's import paths are relative to. The worker shares + * the dev server's process, so its `cwd` is the one core resolved the index + * against; tests pass a fixture directory instead. + */ + workingDir?: string + /** + * The payload is for a static build, whose stories are pre-rendered. The + * preview turns off the controls of the rows it knows about, but the manager + * merges ours under those, so ours have to be off too (issue #375). + */ + prerendered?: boolean +} + +/** + * Builds the docgen payload for the `.astro` component one story file documents. + * + * Returns `undefined` to hand the request to the rest of the provider chain. + * That covers both "nothing here to read" and "not an Astro component" — a + * React or Vue story reached through an integration belongs to that renderer's + * provider, and claiming it would starve them. + */ +export async function buildDocgenPayload( + input: DocgenProviderInput, + context: DocgenPayloadContext, +): Promise { + const storyImportPath = getStoryImportPathFromEntry(input.entry) + + if (!storyImportPath) { + return undefined + } + + const storyPath = join(context.workingDir ?? process.cwd(), storyImportPath) + const storySource = await read(storyPath) + + if (storySource === undefined) { + return undefined + } + + const base = { + id: getComponentIdFromEntry(input.entry), + name: componentNameFromTitle(input.entry.title), + path: storyImportPath, + jsDocTags: {}, + } satisfies DocgenPayload + + let csf + + try { + csf = loadCsf(storySource, { makeTitle: () => input.entry.title }).parse() + } catch (error) { + // The one failure worth claiming the payload for. Every other bail below is + // ambiguous enough to belong to another provider, but a story file that + // will not parse leaves the author with a blank page and no clue why. + return { + ...base, + error: { + name: 'Story file could not be parsed', + message: `${messageOf(error)}\n\n${storyImportPath}`, + }, + } + } + + const resolved = resolveMetaComponent(csf, storyPath) + + if ('reason' in resolved) { + return undefined + } + + const { localName, path: componentPath } = resolved.component + + if (!componentPath?.endsWith('.astro')) { + return undefined + } + + const astroSource = await read(componentPath) + + if (astroSource === undefined) { + return undefined + } + + const info = await context.docgen.extract(componentPath, astroSource) + + if (!info) { + return undefined + } + + // The CSF meta's own docblock wins over the component's, and the tag map is + // resolved the same way every other framework's provider resolves it. + const { description, summary, jsDocTags } = extractComponentDescription( + readMetaDescription(csf) || undefined, + info.description || undefined, + toJsDocTags(info.tags), + ) + + const argTypes = extractArgTypes({ __docgenInfo: info }) + const tableArgTypes = argTypes && context.prerendered ? withoutControls(argTypes) : argTypes + + return { + ...base, + name: localName || info.displayName || base.name, + description, + summary, + jsDocTags, + argTypes: tableArgTypes ?? undefined, + // Core strips argTypes before an agent sees the component (issue #353). + apiDescription: formatApiDescription(argTypes, info), + renderer: 'astro', + } +} + +function withoutControls(argTypes: StrictArgTypes): StrictArgTypes { + return Object.fromEntries( + Object.entries(argTypes).map(([key, argType]) => [key, { ...argType, control: false }]), + ) +} + +/** The last segment of a story title, for when the component has no name of its own. */ +function componentNameFromTitle(title: string): string { + return title.split('/').at(-1)!.replace(/\s+/g, '') +} + +/** `undefined` when the file is gone — an indexed entry can outlive its file. */ +async function read(path: string): Promise { + try { + return await readFile(path, 'utf8') + } catch { + return undefined + } +} + +/** Our extractor keeps one value per tag; the payload's tag map holds a list. */ +function toJsDocTags(tags: Record | undefined): Record { + return Object.fromEntries(Object.entries(tags ?? {}).map(([tag, value]) => [tag, [value]])) +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +/** + * The docblock above the stories file's meta. Storybook 11 reads comments + * through the CSF file's source editor, so its `extractDescription` takes the + * editor as a second argument; Storybook 10 takes only the node and has no + * `editor` on the file. Calling it this way works on both. + */ +function readMetaDescription(csf: CsfFile): string { + const extract = extractDescription as (node: unknown, editor?: unknown) => string + + return extract(csf._metaStatement, (csf as { editor?: unknown }).editor) +} diff --git a/packages/storybook-astro/framework/src/docgen/docgen-worker.ts b/packages/storybook-astro/framework/src/docgen/docgen-worker.ts new file mode 100644 index 0000000..6b39eb3 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/docgen-worker.ts @@ -0,0 +1,60 @@ +/** + * Worker-target docgen module, imported by Storybook's docgen worker. + * + * Core spawns one long-lived Node worker, imports this module by absolute path + * and calls {@link createDocgenProvider} once to build the middleware it folds + * into the provider chain. Everything here runs on that thread, so the + * TypeScript language service our extractor keeps warm — around 170 MB and a + * ~0.9s first program — never lands on the dev server's event loop + * (docs/specs/docgen.md#design-decisions). + * + * The framework's preset contributes the descriptor pointing here. This module + * is emitted as its own entry because a descriptor is a module specifier, not a + * closure: nothing can be passed across the thread boundary except plain data. + */ +import { createLazyDocgenMiddleware } from 'storybook/internal/common' +import { logger } from 'storybook/internal/node-logger' +import type { DocgenMiddleware } from 'storybook/internal/types' +import { buildDocgenPayload } from './docgen-payload.ts' +import { createAstroDocgen } from './index.ts' + +/** + * The slice of the framework's `docgen` option that survives the trip to the + * worker. `propFilter` is a function, and functions throw at `postMessage`, so + * a project that needs a custom filter stays on the builder path + * (docs/specs/docgen.md#known-limitations). + */ +export interface AstroDocgenWorkerOptions { + /** Where tsconfig discovery starts, and what declaring-file paths are relative to. */ + projectRoot: string + tsconfigPath?: string + /** A static build: the stories are pre-rendered, so no row gets a live control. */ + prerendered?: boolean +} + +/** + * Builds the Astro docgen middleware. + * + * The extractor is created on the first story request rather than at import + * time, so a Storybook whose stories are all framework components never pays + * for a TypeScript program it has no `.astro` file to read. + */ +export const createDocgenProvider = (options?: AstroDocgenWorkerOptions): DocgenMiddleware => + createLazyDocgenMiddleware({ + createManager: async () => { + if (!options?.projectRoot) { + logger.warn( + '[storybook-astro] Astro docgen is unavailable: the provider was registered without a project root.', + ) + + return undefined + } + + return createAstroDocgen({ + projectRoot: options.projectRoot, + tsconfigPath: options.tsconfigPath, + warn: (message) => logger.warn(message), + }) + }, + extract: (docgen, input) => buildDocgenPayload(input, { docgen, prerendered: options?.prerendered }), + }) diff --git a/packages/storybook-astro/framework/src/docgen/extract.test.ts b/packages/storybook-astro/framework/src/docgen/extract.test.ts new file mode 100644 index 0000000..321b2e0 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/extract.test.ts @@ -0,0 +1,432 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import typescript from 'typescript' +import { afterAll, beforeAll, describe, expect, test } from 'vitest' +import { extractAstroDocgen } from './extract.ts' +import { type AstroTsProject, createAstroTsProject } from './tsProject.ts' + +// The fixture must live inside the package rather than the OS tmpdir, so +// TypeScript can resolve `astro/types` by walking up to the workspace's +// node_modules — the inherited-props cases below depend on it. +const packageDir = fileURLToPath(new URL('../..', import.meta.url)) +const projectRoot = mkdtempSync(join(packageDir, '.vitest-docgen-fixture-')) +let project: AstroTsProject + +beforeAll(() => { + project = createAstroTsProject( + typescript, + { + target: typescript.ScriptTarget.Latest, + module: typescript.ModuleKind.ESNext, + moduleResolution: typescript.ModuleResolutionKind.Bundler, + skipLibCheck: true, + }, + projectRoot, + ) +}) + +afterAll(() => { + project.dispose() + rmSync(projectRoot, { recursive: true, force: true }) +}) + +let componentCount = 0 + +/** Extracts from real `.astro` source, as the Vite plugin will. */ +function docgenFor(astroSource: string, name = `Component${(componentCount += 1)}`) { + const astroFilePath = join(projectRoot, `${name}.astro`) + + return extractAstroDocgen(typescript, project, astroFilePath, astroSource, {}) +} + +function astro(frontmatter: string, template = '
') { + return `---\n${frontmatter}\n---\n${template}` +} + +describe('a plain component', () => { + const docgen = () => + docgenFor( + astro( + [ + '/**', + ' * A simple content card.', + ' */', + 'interface Props {', + ' /** Card heading text. */', + ' title?: string;', + ' /** Applies a highlighted style. */', + ' highlight?: boolean;', + ' /** Required, so no default. */', + ' id: string;', + '}', + '', + "const { title = 'Default title', highlight = false, id } = Astro.props;", + ].join('\n'), + ), + 'Card', + ) + + test('takes its display name from the file', () => { + expect(docgen()?.displayName).toBe('Card') + }) + + test('reads the component description', () => { + expect(docgen()?.description).toBe('A simple content card.') + }) + + test('reads per-prop descriptions from JSDoc', () => { + expect(docgen()?.props.title.description).toBe('Card heading text.') + }) + + test('reads defaults from the Astro.props destructuring, as written', () => { + const props = docgen()!.props + + expect(props.title.defaultValue).toEqual({ value: 'Default title', source: "'Default title'" }) + expect(props.highlight.defaultValue).toEqual({ value: false, source: 'false' }) + }) + + test('a prop with a default is not required', () => { + expect(docgen()?.props.title.required).toBe(false) + }) + + test('a non-optional prop with no default is required', () => { + expect(docgen()?.props.id.required).toBe(true) + }) + + test('strips the redundant undefined from optional prop types', () => { + expect(docgen()?.props.title.type.name).toBe('string') + }) +}) + +describe('literal unions drive select controls', () => { + test('constituents are surfaced as enum options', () => { + const docgen = docgenFor( + astro( + [ + "type Framework = 'react' | 'vue' | 'svelte';", + 'interface Props { framework?: Framework }', + "const { framework = 'react' } = Astro.props;", + ].join('\n'), + ), + ) + + expect(docgen?.props.framework.type.name).toBe('enum') + expect(docgen?.props.framework.type.value?.map((each) => each.value)).toEqual([ + '"react"', + '"vue"', + '"svelte"', + ]) + }) +}) + +describe('props marked @ignore (issue #356)', () => { + test('are left out, so neither the table nor AI agents see them', () => { + const docgen = docgenFor( + astro( + [ + 'interface Props {', + ' /** Shown. */', + ' title?: string;', + ' /**', + ' * Wired up by the parent layout.', + ' * @ignore', + ' */', + ' internal?: string;', + '}', + 'const { title, internal } = Astro.props;', + ].join('\n'), + ), + ) + + expect(Object.keys(docgen!.props)).toEqual(['title']) + }) +}) + +describe('long types (issue #357)', () => { + // Template literal types aren't literals, so this union isn't an enum. + const widthType = Array.from({ length: 30 }, (_, index) => `\`\${number}unit${index}\``).join(' | ') + const docgen = () => + docgenFor( + astro( + [ + 'interface Props {', + ' options?: {', + ' firstOptionWithAVeryLongName: string;', + ' secondOptionWithAVeryLongName: number;', + ' thirdOptionWithAVeryLongName: boolean;', + ' fourthOptionWithAVeryLongName: string[];', + ' fifthOptionWithAVeryLongName: Record;', + ' };', + ` width?: ${widthType};`, + ' label?: string;', + '}', + 'const { options, width, label } = Astro.props;', + ].join('\n'), + ), + ) + + test('record the whole text next to the shortened summary the table shows', () => { + const { options } = docgen()!.props + + expect(options.type.name).toContain('...') + expect(options.type.untruncated).toBe( + '{ firstOptionWithAVeryLongName: string; secondOptionWithAVeryLongName: number; ' + + 'thirdOptionWithAVeryLongName: boolean; fourthOptionWithAVeryLongName: string[]; ' + + 'fifthOptionWithAVeryLongName: Record; }', + ) + }) + + test('record the whole text of a long union that is not all literals', () => { + const { width } = docgen()!.props + + expect(width.type.name).toContain('...') + expect(width.type.untruncated).toBe(widthType) + }) + + test('add nothing for a type that fits', () => { + expect(docgen()!.props.label.type).toEqual({ name: 'string' }) + }) +}) + +describe('a Props imported from a sibling module', () => { + test('resolves, because the virtual file sits beside the component', () => { + writeFileSync( + join(projectRoot, 'shared-props.ts'), + 'export interface CardProps {\n /** From a sibling file. */\n heading?: string;\n}\n', + ) + + const docgen = docgenFor( + astro( + [ + "import type { CardProps } from './shared-props.ts';", + 'interface Props extends CardProps {}', + 'const { heading } = Astro.props;', + ].join('\n'), + ), + ) + + expect(docgen?.props.heading?.description).toBe('From a sibling file.') + }) +}) + +describe('the component from issue #110', () => { + // `interface Props extends Polymorphic<…>` is a hard TS2312: TypeScript + // drops the whole base type, leaving only the inline members. + const source = astro( + [ + "import type { HTMLTag, Polymorphic } from 'astro/types';", + '', + '/**', + ' * @component Button', + ' * @description Semantic button for actions and navigation.', + ' * @usage Some markdown that should not land in the description.', + ' */', + "type ButtonVariants = { variant?: 'solid' | 'outline' };", + '', + "interface Props", + ' extends Polymorphic<{ as: Tag } & ButtonVariants> {', + ' /** Disables interaction. */', + ' disabled?: boolean;', + '}', + '', + "const { as: Tag = 'button', variant = 'solid', disabled = false, href, class: className } =", + ' Astro.props as Props;', + ].join('\n'), + '', + ) + + test('recovers inherited props the heritage clause would have dropped', () => { + const props = docgenFor(source, 'Button')!.props + + expect(Object.keys(props)).toContain('variant') + expect(Object.keys(props)).toContain('as') + }) + + test('keeps destructured props whose types come from node_modules', () => { + const props = docgenFor(source, 'Button')!.props + + // `href` and `class` are declared in astro-jsx.d.ts, not the component. + expect(Object.keys(props)).toContain('href') + expect(Object.keys(props)).toContain('class') + }) + + test('a prop shared by every constituent keeps its full type', () => { + // `as` must offer both tags. Probing only the constituents in turn would + // narrow it to whichever was read first. + const { as: polymorphicTag } = docgenFor(source, 'Button')!.props + + expect(polymorphicTag.type.value?.map((each) => each.value).sort()).toEqual([ + '"a"', + '"button"', + ]) + }) + + test('filters the inherited DOM attribute flood down to a readable table', () => { + const props = docgenFor(source, 'Button')!.props + + expect(Object.keys(props).length).toBeLessThan(20) + expect(props.disabled.description).toBe('Disables interaction.') + }) + + test('uses @description for the description and keeps other tags out of it', () => { + const docgen = docgenFor(source, 'Button')! + + expect(docgen.description).toBe('Semantic button for actions and navigation.') + expect(docgen.description).not.toContain('markdown') + expect(docgen.tags?.usage).toContain('markdown') + }) +}) + +describe('components do not leak props into each other', () => { + // Frontmatter with no import or export is a global script, so `Props` is a + // *global* declaration — and every component shares one TypeScript program. + // Two plain components would otherwise collide and the first would win. + const plain = (prop: string, doc: string) => + astro( + [ + 'interface Props {', + ` /** ${doc} */`, + ` ${prop}?: string;`, + '}', + `const { ${prop} } = Astro.props;`, + ].join('\n'), + ) + + test('two components with no imports each keep their own props', () => { + const first = docgenFor(plain('alpha', 'Belongs to Alpha.'), 'Alpha') + const second = docgenFor(plain('beta', 'Belongs to Beta.'), 'Beta') + + expect(Object.keys(first!.props)).toEqual(['alpha']) + expect(Object.keys(second!.props)).toEqual(['beta']) + expect(second!.props.beta.description).toBe('Belongs to Beta.') + }) + + test('a component with imports does not absorb a plain one', () => { + docgenFor(plain('gamma', 'Belongs to Gamma.'), 'Gamma') + + const withImport = docgenFor( + astro( + [ + "import type { HTMLTag } from 'astro/types';", + 'interface Props {', + ' /** Belongs to Delta. */', + ' delta?: HTMLTag;', + '}', + 'const { delta } = Astro.props;', + ].join('\n'), + ), + 'Delta', + ) + + expect(Object.keys(withImport!.props)).toEqual(['delta']) + }) +}) + +describe('description precedence', () => { + test('a leading block still counts when an import follows it', () => { + // Astro frontmatter puts imports first, so a component description written + // at the top of the file lands on one. PageCard.astro is shaped this way. + const docgen = docgenFor( + astro( + [ + '/** Renders a page card. */', + "import type { HTMLTag } from 'astro/types';", + 'interface Props { a?: HTMLTag }', + 'const { a } = Astro.props;', + ].join('\n'), + ), + ) + + expect(docgen?.description).toBe('Renders a page card.') + }) + + test('a JSDoc buried mid-file is not mistaken for the description', () => { + const docgen = docgenFor( + astro( + [ + "import type { HTMLTag } from 'astro/types';", + '/** A helper, not the component. */', + 'const helper = 1;', + 'interface Props { a?: HTMLTag }', + 'const { a } = Astro.props;', + ].join('\n'), + ), + ) + + expect(docgen?.description).toBe('') + }) + + test('falls back to the JSDoc on the Props declaration', () => { + const docgen = docgenFor( + astro( + [ + '/** Public props for the widget. */', + 'interface Props { a?: string }', + 'const { a } = Astro.props;', + ].join('\n'), + ), + ) + + expect(docgen?.description).toBe('Public props for the widget.') + }) +}) + +describe('components with nothing to extract still behave', () => { + test('no frontmatter and no slots yields no docgen at all', () => { + expect(docgenFor('

markup only

')).toBeNull() + }) + + test('a component with slots but no frontmatter still lists its slots (issue #188)', () => { + const docgen = docgenFor('
', 'Panel') + + expect(docgen).toEqual({ + displayName: 'Panel', + description: '', + props: {}, + slots: [ + { name: 'header', description: '' }, + { name: 'default', description: '' }, + ], + }) + }) + + test('no Props still yields the description, which is the point for slot-only components', () => { + const docgen = docgenFor( + astro(['/**', ' * Wraps its children.', ' */', 'const a = 1;'].join('\n'), ''), + ) + + expect(docgen?.description).toBe('Wraps its children.') + expect(docgen?.props).toEqual({}) + expect(docgen?.slots).toEqual([{ name: 'default', description: '' }]) + }) + + test('a component with Props lists its slots next to its props', () => { + const docgen = docgenFor( + astro( + ['interface Props { title: string }', 'const { title } = Astro.props;'].join('\n'), + '

{title}

\n{/* @slot The section body */}\n', + ), + ) + + expect(Object.keys(docgen?.props ?? {})).toEqual(['title']) + expect(docgen?.slots).toEqual([{ name: 'default', description: 'The section body' }]) + }) + + test('a type error does not stop extraction of the props that do resolve', () => { + const docgen = docgenFor( + astro( + [ + "import { missing } from './does-not-exist.ts';", + 'interface Props {', + ' /** Still readable. */', + ' title?: string;', + '}', + 'const { title } = Astro.props;', + ].join('\n'), + ), + ) + + expect(docgen?.props.title.description).toBe('Still readable.') + }) +}) diff --git a/packages/storybook-astro/framework/src/docgen/extract.ts b/packages/storybook-astro/framework/src/docgen/extract.ts new file mode 100644 index 0000000..b2fdbe1 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/extract.ts @@ -0,0 +1,357 @@ +import { basename } from 'node:path' +import type ts from 'typescript' +import { type AstroPropsBinding, readAstroPropsBinding } from './defaultValues.ts' +import { readComponentDescription } from './description.ts' +import { createDefaultPropFilter } from './propFilter.ts' +import { rewriteInterfaceToTypeAlias, unionConstituentsOfFirstDefault } from './propsDeclaration.ts' +import { readSlots } from './slots.ts' +import type { AstroTsProject } from './tsProject.ts' +import type { + AstroDocgenInfo, + AstroDocgenOptions, + AstroDocgenProp, + AstroDocgenPropType, + DeclarationRef, +} from './types.ts' +import { appendPropsProbes, buildVirtualSource, virtualFilePathFor } from './virtualFile.ts' + +/** "An interface can only extend an object type … with statically known members." */ +const INTERFACE_EXTENDS_NON_OBJECT = 2312 + +/** Guards against `Tag extends HTMLTag = HTMLTag` expanding to every element. */ +const MAX_UNION_CONSTITUENTS = 8 + +/** + * Extracts docgen for one `.astro` component. + * + * Returns `null` only when there is nothing to look at: no frontmatter and no + * slots. A component with frontmatter but no `Props` still yields its + * description with an empty props table, because that description and its + * slots are most of the value for a slot-only component + * (docs/specs/docgen.md#failure-modes). + */ +export function extractAstroDocgen( + typescript: typeof ts, + project: AstroTsProject, + astroFilePath: string, + astroSource: string, + options: AstroDocgenOptions = {}, +): AstroDocgenInfo | null { + const displayName = basename(astroFilePath).replace(/\.astro$/, '') + const slots = readSlots(astroSource) + const virtualSource = buildVirtualSource(astroSource) + + if (virtualSource === null) { + return slots.length > 0 ? { displayName, description: '', props: {}, slots } : null + } + + // Parsed without a checker first: this is cheap, and it tells us whether + // there is a `Props` to instantiate before we involve the program at all. + const parsed = typescript.createSourceFile( + virtualFilePathFor(astroFilePath), + virtualSource, + typescript.ScriptTarget.Latest, + true, + ) + + const description = readComponentDescription(typescript, parsed) + const propsDeclaration = findPropsDeclaration(typescript, parsed) + + if (!propsDeclaration) { + return { displayName, description: description.text, tags: description.tags, props: {}, slots } + } + + const binding = readAstroPropsBinding(typescript, parsed) + const properties = resolveProps(typescript, project, astroFilePath, virtualSource, parsed) + + const propFilter = options.propFilter ?? createDefaultPropFilter(binding.destructured) + const props: Record = {} + + for (const { symbol, checker } of properties) { + const prop = buildProp(typescript, checker, symbol, binding) + + // docs-tools looks for `@ignore` in the description, which holds no tags + // here, so the extractor drops these itself (issue #356). + if (prop.tags && 'ignore' in prop.tags) { + continue + } + + if (propFilter(prop, { name: displayName })) { + props[prop.name] = prop + } + } + + return { displayName, description: description.text, tags: description.tags, props, slots } +} + +/** + * Instantiates `Props` and hands back its properties, merged across union + * constituents. Rewrites the declaration and retries once when TypeScript + * rejects the heritage clause (docs/specs/docgen.md#heritage-rewrite). + */ +function resolveProps( + typescript: typeof ts, + project: AstroTsProject, + astroFilePath: string, + virtualSource: string, + parsed: ts.SourceFile, +): Array<{ symbol: ts.Symbol; checker: ts.TypeChecker }> { + const virtualPath = virtualFilePathFor(astroFilePath) + const constituents = unionConstituentsOfFirstDefault(typescript, parsed, MAX_UNION_CONSTITUENTS) + // The default instantiation goes first so props common to every constituent + // keep their full type — `as` should read `"button" | "a"`, not whichever + // constituent happened to be probed first. The per-constituent probes then + // only contribute the props the collapsed union dropped. + const typeArgumentSets = constituents.length > 1 ? [undefined, ...constituents] : [undefined] + + const read = (source: string) => { + const probes = appendPropsProbes(source, typeArgumentSets) + + project.setVirtualFile(virtualPath, probes.source) + + const program = project.getProgram() + const sourceFile = program?.getSourceFile(virtualPath) + + if (!program || !sourceFile) { + return { properties: [], sourceFile: undefined, program: undefined, probes } + } + + const checker = program.getTypeChecker() + const seen = new Map() + + for (const name of probes.names) { + for (const symbol of propertiesOfProbe(typescript, checker, sourceFile, name)) { + // First constituent to declare a prop wins; later ones only add. + if (!seen.has(symbol.getName())) { + seen.set(symbol.getName(), symbol) + } + } + } + + return { + properties: [...seen.values()].map((symbol) => ({ symbol, checker })), + sourceFile, + program, + probes, + } + } + + const first = read(virtualSource) + + if (!first.sourceFile || !first.program) { + return first.properties + } + + // The rewrite is gated on the diagnostic rather than on an empty result: + // a rejected heritage clause still leaves the members written inline, so + // #110's Button comes back with `disabled` alone and looks like a success. + const rejectedHeritage = first.program + .getSemanticDiagnostics(first.sourceFile) + .some((diagnostic) => diagnostic.code === INTERFACE_EXTENDS_NON_OBJECT) + + if (!rejectedHeritage) { + return first.properties + } + + const rewritten = rewriteInterfaceToTypeAlias(typescript, virtualSource) + + if (rewritten === null) { + return first.properties + } + + const retried = read(rewritten) + + // Only take the rewrite when it actually recovered something. + return retried.properties.length > first.properties.length + ? retried.properties + : first.properties +} + +function propertiesOfProbe( + typescript: typeof ts, + checker: ts.TypeChecker, + sourceFile: ts.SourceFile, + probeName: string, +): ts.Symbol[] { + for (const statement of sourceFile.statements) { + if (!typescript.isVariableStatement(statement)) { + continue + } + + for (const declaration of statement.declarationList.declarations) { + if (typescript.isIdentifier(declaration.name) && declaration.name.text === probeName) { + return checker.getTypeAtLocation(declaration.name).getApparentProperties() + } + } + } + + return [] +} + +function findPropsDeclaration( + typescript: typeof ts, + sourceFile: ts.SourceFile, +): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined { + return sourceFile.statements.find( + (statement): statement is ts.InterfaceDeclaration | ts.TypeAliasDeclaration => + (typescript.isInterfaceDeclaration(statement) || + typescript.isTypeAliasDeclaration(statement)) && + statement.name.text === 'Props', + ) +} + +function buildProp( + typescript: typeof ts, + checker: ts.TypeChecker, + symbol: ts.Symbol, + { defaults }: AstroPropsBinding, +): AstroDocgenProp { + const name = symbol.getName() + const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0] + const type = declaration + ? checker.getTypeOfSymbolAtLocation(symbol, declaration) + : checker.getDeclaredTypeOfSymbol(symbol) + + const defaultValue = defaults.get(name) ?? null + const optional = (symbol.flags & typescript.SymbolFlags.Optional) !== 0 + const required = !optional && !defaultValue + + return { + name, + required, + type: describeType(typescript, checker, type, required), + description: typescript.displayPartsToString(symbol.getDocumentationComment(checker)).trim(), + defaultValue, + parent: declarationRefOf(typescript, declaration), + declarations: (symbol.declarations ?? []) + .map((each) => declarationRefOf(typescript, each)) + .filter((each): each is DeclarationRef => each !== undefined), + tags: jsDocTagsOf(typescript, symbol, checker), + } +} + +function describeType( + typescript: typeof ts, + checker: ts.TypeChecker, + type: ts.Type, + required: boolean, +): AstroDocgenPropType { + const raw = checker.typeToString(type) + // Optional props read as `string | undefined`; the `?` already says that. + const withoutUndefined = (text: string) => required ? text : text.replace(/\s*\|\s*undefined$/, '') + const name = withoutUndefined(raw) + // TypeScript shortens a long type to `{ ...; }` or `... 12 more ...`. That + // suits the props table, but AI agents read the type to pick a valid value, + // so the API description gets the whole text (issue #357). These are + // typeToString's default flags plus NoTruncation. + const fullText = withoutUndefined( + checker.typeToString( + type, + undefined, + typescript.TypeFormatFlags.NoTruncation | + typescript.TypeFormatFlags.AllowUniqueESSymbolType | + typescript.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope, + ), + ) + const result: AstroDocgenPropType = { name } + + if (fullText !== name) { + result.untruncated = fullText + } + + if (!type.isUnion()) { + return result + } + + // An optional prop's type includes `undefined` under `strict`, which would + // otherwise disqualify every optional literal union — i.e. most of them — + // from becoming a select control. + const meaningful = type.types.filter((constituent) => !isNullish(typescript, constituent)) + // `string | undefined` is just `string` once the optional marker takes the `undefined`. + if (meaningful.length < 2 && !meaningful.some((constituent) => constituent.isLiteral())) { + return result + } + + const literals = meaningful.filter((constituent) => constituent.isLiteral()) + + if (literals.length === 0 || literals.length !== meaningful.length) { + return { ...result, raw } + } + + // apiDescription prints a literal union from `value`, so it needs no + // `untruncated`. + return { + name: 'enum', + raw: name, + value: literals.map((constituent) => ({ value: checker.typeToString(constituent) })), + } +} + +/** `undefined` and `null` say nothing about which control a prop should get. */ +function isNullish(typescript: typeof ts, type: ts.Type): boolean { + // The flag values differ between TypeScript majors (6 renumbered them), so read them from the + // compiler the project actually runs. + return (type.flags & (typescript.TypeFlags.Undefined | typescript.TypeFlags.Null)) !== 0 +} + +function declarationRefOf( + typescript: typeof ts, + declaration: ts.Declaration | undefined, +): DeclarationRef | undefined { + if (!declaration) { + return undefined + } + + const fileName = declaration.getSourceFile().fileName + const owner = declaration.parent + + // Props coming from `VariantProps` are property assignments in an + // object literal and have no declaring interface at all, so fall back to the + // nearest named ancestor rather than reporting nothing — the prior art's + // undefined `parent` is what makes the usual node_modules filter drop them. + if ( + owner && + (typescript.isInterfaceDeclaration(owner) || typescript.isTypeAliasDeclaration(owner)) + ) { + return { fileName, name: owner.name.text } + } + + return { fileName, name: nearestNamedAncestor(typescript, declaration) } +} + +function nearestNamedAncestor(typescript: typeof ts, declaration: ts.Declaration): string { + let node: ts.Node | undefined = declaration.parent + + while (node) { + if ( + (typescript.isVariableDeclaration(node) || + typescript.isInterfaceDeclaration(node) || + typescript.isTypeAliasDeclaration(node) || + typescript.isClassDeclaration(node)) && + node.name && + typescript.isIdentifier(node.name) + ) { + return node.name.text + } + + node = node.parent + } + + return '' +} + +function jsDocTagsOf( + typescript: typeof ts, + symbol: ts.Symbol, + checker: ts.TypeChecker, +): Record | undefined { + const tags = symbol.getJsDocTags(checker) + + if (tags.length === 0) { + return undefined + } + + return Object.fromEntries( + tags.map((tag) => [tag.name, typescript.displayPartsToString(tag.text ?? []).trim()]), + ) +} diff --git a/packages/storybook-astro/framework/src/docgen/index.test.ts b/packages/storybook-astro/framework/src/docgen/index.test.ts new file mode 100644 index 0000000..08d4466 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/index.test.ts @@ -0,0 +1,261 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, describe, expect, test } from 'vitest' +import { createAstroDocgen } from './index.ts' + +// Inside the package so `astro/types` resolves by walking up, matching the +// existing .vitest-*-fixture-* convention. +const packageDir = fileURLToPath(new URL('../..', import.meta.url)) +const projectRoot = mkdtempSync(join(packageDir, '.vitest-docgen-fixture-')) + +afterAll(() => rmSync(projectRoot, { recursive: true, force: true })) + +const CARD = [ + '---', + '/** A card. */', + 'interface Props {', + ' /** Heading. */', + ' title?: string;', + '}', + "const { title = 'Hello' } = Astro.props;", + '---', + '

{title}

', +].join('\n') + +function createDocgen(overrides: Partial[0]> = {}) { + const warnings: string[] = [] + const docgen = createAstroDocgen({ + projectRoot, + warn: (message) => warnings.push(message), + ...overrides, + }) + + return { docgen, warnings } +} + +describe('extraction through the runtime', () => { + test('reads a component end to end', async () => { + const { docgen } = createDocgen() + const result = await docgen.extract(join(projectRoot, 'Card.astro'), CARD) + + expect(result?.displayName).toBe('Card') + expect(result?.description).toBe('A card.') + expect(result?.props.title.defaultValue).toEqual({ value: 'Hello', source: "'Hello'" }) + + docgen.dispose() + }) + + test('a component with no frontmatter yields nothing', async () => { + const { docgen } = createDocgen() + + expect(await docgen.extract(join(projectRoot, 'Plain.astro'), '

hi

')).toBeNull() + + docgen.dispose() + }) +}) + +describe('results are cached by content', () => { + test('the same source is not re-extracted', async () => { + const { docgen } = createDocgen() + const path = join(projectRoot, 'Cached.astro') + + const first = await docgen.extract(path, CARD) + const second = await docgen.extract(path, CARD) + + expect(second).toBe(first) + + docgen.dispose() + }) + + test('edited source is re-extracted', async () => { + const { docgen } = createDocgen() + const path = join(projectRoot, 'Edited.astro') + + await docgen.extract(path, CARD) + const edited = await docgen.extract(path, CARD.replace('Heading.', 'Changed.')) + + expect(edited?.props.title.description).toBe('Changed.') + + docgen.dispose() + }) + + test('a component with nothing to extract is not retried on every tick', async () => { + const { docgen } = createDocgen() + const path = join(projectRoot, 'Empty.astro') + + const first = await docgen.extract(path, '

hi

') + const second = await docgen.extract(path, '

hi

') + + expect(first).toBeNull() + expect(second).toBeNull() + + docgen.dispose() + }) +}) + +describe('the project tsconfig is honoured', () => { + test('path aliases declared by the project resolve', async () => { + writeFileSync( + join(projectRoot, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { + baseUrl: '.', + paths: { '@shared/*': ['./shared/*'] }, + moduleResolution: 'Bundler', + module: 'ESNext', + target: 'ESNext', + }, + }), + ) + writeFileSync( + join(projectRoot, 'shared-types.ts'), + 'export interface Shared {\n /** Via a path alias. */\n aliased?: string;\n}\n', + ) + + const { docgen } = createDocgen() + const source = [ + '---', + "import type { Shared } from '@shared/../shared-types.ts';", + 'interface Props extends Shared {}', + 'const { aliased } = Astro.props;', + '---', + '
', + ].join('\n') + + const result = await docgen.extract(join(projectRoot, 'Aliased.astro'), source) + + expect(result?.props.aliased?.description).toBe('Via a path alias.') + + docgen.dispose() + }) +}) + +describe('failures never take rendering down', () => { + test('an unreadable tsconfig warns once and still extracts', async () => { + const badRoot = mkdtempSync(join(packageDir, '.vitest-docgen-fixture-')) + + writeFileSync( + join(badRoot, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { target: 'not-a-real-target' } }), + ) + + const { docgen, warnings } = createDocgen({ projectRoot: badRoot }) + const result = await docgen.extract(join(badRoot, 'Card.astro'), CARD) + + expect(result?.props.title).toBeDefined() + expect(warnings.some((message) => message.includes('tsconfig.json'))).toBe(true) + + docgen.dispose() + rmSync(badRoot, { recursive: true, force: true }) + }) + + test('warming up before any extraction is safe', async () => { + const { docgen } = createDocgen() + + await expect(docgen.warmUp()).resolves.toBeUndefined() + + docgen.dispose() + }) +}) + +describe('what reaches the browser bundle', () => { + test('declaring paths are project-relative, not absolute machine paths', async () => { + writeFileSync( + join(projectRoot, 'trim-types.ts'), + 'export interface Trimmed {\n /** Declared elsewhere. */\n elsewhere?: string;\n}\n', + ) + + const { docgen } = createDocgen() + const source = [ + '---', + "import type { Trimmed } from './trim-types.ts';", + 'interface Props extends Trimmed {}', + 'const { elsewhere } = Astro.props;', + '---', + '
', + ].join('\n') + + const result = await docgen.extract(join(projectRoot, 'Trim.astro'), source) + const parentFile = result?.props.elsewhere?.parent?.fileName ?? '' + + // A published static Storybook is public; whoever built it shouldn't be + // shipping their home directory in it. + expect(parentFile).toBe('trim-types.ts') + expect(JSON.stringify(result)).not.toContain(projectRoot) + + docgen.dispose() + }) + + test('a type from a sibling package stays relative rather than absolute', async () => { + // The monorepo case: the app root is integration/astroN while the component + // and its types live in packages/components, so the declaring file is above + // the root. Climbing out with `../` beats shipping a home directory. + const nestedRoot = join(projectRoot, 'app') + + mkdirSync(nestedRoot, { recursive: true }) + writeFileSync( + join(projectRoot, 'outside-types.ts'), + 'export interface Outside {\n /** Declared above the app root. */\n outer?: string;\n}\n', + ) + + const { docgen } = createDocgen({ projectRoot: nestedRoot }) + const source = [ + '---', + "import type { Outside } from '../outside-types.ts';", + 'interface Props extends Outside {}', + 'const { outer } = Astro.props;', + '---', + '
', + ].join('\n') + + const result = await docgen.extract(join(nestedRoot, 'Nested.astro'), source) + + expect(result?.props.outer?.parent?.fileName).toBe('../outside-types.ts') + expect(JSON.stringify(result)).not.toContain(packageDir) + + docgen.dispose() + }) + + test('server-only declaration data is not shipped', async () => { + const { docgen } = createDocgen() + const result = await docgen.extract(join(projectRoot, 'NoDecls.astro'), CARD) + + expect(result?.props.title).toBeDefined() + expect(JSON.stringify(result)).not.toContain('declarations') + + docgen.dispose() + }) + + test('an optional literal union still becomes a select control under strict', async () => { + writeFileSync( + join(projectRoot, 'tsconfig.json'), + JSON.stringify({ compilerOptions: { strict: true, moduleResolution: 'Bundler' } }), + ) + + const { docgen } = createDocgen() + const source = [ + '---', + "type Tone = 'solid' | 'outline';", + 'interface Props {', + ' /** Visual treatment. */', + ' tone?: Tone;', + '}', + "const { tone = 'solid' } = Astro.props;", + '---', + '
', + ].join('\n') + + const result = await docgen.extract(join(projectRoot, 'Strict.astro'), source) + + // Under `strict` an optional prop's type includes `undefined`, which would + // otherwise disqualify most real unions from becoming a select. + expect(result?.props.tone.type.name).toBe('enum') + expect(result?.props.tone.type.value?.map((each) => each.value)).toEqual([ + '"solid"', + '"outline"', + ]) + + docgen.dispose() + }) +}) diff --git a/packages/storybook-astro/framework/src/docgen/index.ts b/packages/storybook-astro/framework/src/docgen/index.ts new file mode 100644 index 0000000..c243ab0 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/index.ts @@ -0,0 +1,267 @@ +import { getTsconfig } from 'get-tsconfig' +import { createHash } from 'node:crypto' +import { dirname, relative } from 'node:path' +import type ts from 'typescript' +import { extractAstroDocgen } from './extract.ts' +import { type AstroTsProject, createAstroTsProject } from './tsProject.ts' +import type { AstroDocgenInfo, AstroDocgenOptions } from './types.ts' + +export type { AstroDocgenInfo, AstroDocgenOptions, PropFilter } from './types.ts' + +/** TypeScript below this lacks `resolveModuleNameLiterals`, which we rely on. */ +const MINIMUM_TYPESCRIPT = 5 + +export interface AstroDocgen { + /** + * Loads TypeScript and warms the language service. Call without awaiting from + * `buildStart` so the one-time cost overlaps Storybook's own boot rather than + * landing on the first story request. + */ + warmUp(): Promise + /** Docgen for one component, or `null` when there is nothing to extract. */ + extract(astroFilePath: string, astroSource: string): Promise + /** Called from Vite's watcher when a file the components depend on changes. */ + invalidate(filePath: string): void + dispose(): void +} + +export interface AstroDocgenSetup extends AstroDocgenOptions { + projectRoot: string + /** Reports a problem once. Repeats are swallowed. */ + warn?: (message: string) => void +} + +/** + * Owns the docgen runtime: the TypeScript import, the shared language service + * and the extraction cache. + * + * Everything here is best-effort. Docgen is a side channel — when it cannot + * run, components still render (docs/specs/docgen.md#failure-modes). + */ +export function createAstroDocgen(setup: AstroDocgenSetup): AstroDocgen { + const warned = new Set() + const warn = (message: string) => { + if (warned.has(message)) { + return + } + + warned.add(message) + ;(setup.warn ?? console.warn)(`[storybook-astro] ${message}`) + } + + const cache = new Map() + let session: Promise | undefined + + const ensureSession = () => (session ??= startSession(setup, warn)) + + return { + async warmUp() { + // Callers fire this without awaiting, so a rejection here would surface + // as an unhandled one and take Storybook or Vitest down with it. + try { + const active = await ensureSession() + + // Building the program is what actually costs the ~0.9s; getting the + // service alone is nearly free and would just defer it. + active?.project.getProgram() + } catch (error) { + warn(`Component documentation is unavailable: ${messageOf(error)}`) + } + }, + + async extract(astroFilePath, astroSource) { + const active = await ensureSession() + + if (!active) { + return null + } + + const key = fingerprint(astroFilePath, astroSource, active.optionsFingerprint) + const cached = cache.get(key) + + // Negative results are cached too, so a component that legitimately has + // no props doesn't re-run a type check on every HMR tick. + if (cached !== undefined) { + return cached + } + + let docgen: AstroDocgenInfo | null = null + + try { + const extracted = extractAstroDocgen( + active.typescript, + active.project, + astroFilePath, + astroSource, + setup, + ) + + docgen = extracted && forPublishing(extracted, setup.projectRoot) + } catch (error) { + warn(`Could not read documentation from ${astroFilePath}: ${messageOf(error)}`) + } + + cache.set(key, docgen) + + return docgen + }, + + invalidate(filePath) { + // A shared type moving invalidates every component that imported it, and + // the cache is keyed by component source — which hasn't changed. + cache.clear() + void session?.then((active) => active?.project.invalidate(filePath)) + }, + + dispose() { + cache.clear() + void session?.then((active) => active?.project.dispose()) + session = undefined + }, + } +} + +/** + * Strips what shouldn't ship to a browser. + * + * Docgen goes into the preview bundle, and a published static Storybook is + * public — so declaring-file paths get trimmed to project-relative rather than + * carrying whatever absolute path the machine that built it happened to use. + * `declarations` is dropped entirely: only the prop filter reads it, and that + * already ran server-side (docs/specs/docgen.md#prop-filtering). + */ +function forPublishing(docgen: AstroDocgenInfo, projectRoot: string): AstroDocgenInfo { + const props = Object.fromEntries( + Object.entries(docgen.props).map(([name, prop]) => { + const { declarations: _serverOnly, parent, ...rest } = prop + + return [ + name, + parent ? { ...rest, parent: { ...parent, fileName: trim(parent.fileName, projectRoot) } } : rest, + ] + }), + ) + + return { ...docgen, props } +} + +function trim(fileName: string, projectRoot: string): string { + // Dependency types are more recognisable by package than by path depth. + const installed = fileName.lastIndexOf('node_modules/') + + if (installed !== -1) { + return fileName.slice(installed + 'node_modules/'.length) + } + + const fromRoot = relative(projectRoot, fileName) + + // Relative even when it climbs out of the app — in a monorepo the declaring + // file usually lives in a sibling package, and `../../packages/…` is worth a + // few extra segments to keep an absolute home directory out of a public build. + return fromRoot || fileName +} + +interface Session { + typescript: typeof ts + project: AstroTsProject + optionsFingerprint: string +} + +async function startSession( + setup: AstroDocgenSetup, + warn: (message: string) => void, +): Promise { + let typescript: typeof ts + + try { + typescript = (await import('typescript')).default + } catch { + warn('TypeScript is not installed, so component documentation cannot be extracted.') + + return undefined + } + + // TypeScript 7 (the native port) ships no JavaScript compiler API: its + // default export is just `version` and `versionMajorMinor`, so the version + // check below passes and the first `ScriptTarget` read throws (issue #197). + if (typeof typescript.createLanguageService !== 'function') { + warn( + `TypeScript ${typescript.version} does not include the compiler API that documentation extraction uses, so component descriptions and props tables are skipped. Install TypeScript 5 or 6 to get them.`, + ) + + return undefined + } + + if (Number.parseInt(typescript.versionMajorMinor, 10) < MINIMUM_TYPESCRIPT) { + warn( + `TypeScript ${typescript.version} is too old for documentation extraction; 5.0 or newer is required.`, + ) + + return undefined + } + + const compilerOptions = readCompilerOptions(typescript, setup, warn) + + return { + typescript, + project: createAstroTsProject(typescript, compilerOptions, setup.projectRoot), + optionsFingerprint: JSON.stringify(compilerOptions), + } +} + +/** + * Compiler options from the project's own tsconfig, so path aliases and + * `moduleResolution` match how the component is actually built. `skipLibCheck` + * is forced on because we only ever ask about one file's types. + */ +function readCompilerOptions( + typescript: typeof ts, + setup: AstroDocgenSetup, + warn: (message: string) => void, +): ts.CompilerOptions { + const found = setup.tsconfigPath + ? getTsconfig(setup.tsconfigPath) + : getTsconfig(setup.projectRoot) + + const fallback: ts.CompilerOptions = { + target: typescript.ScriptTarget.Latest, + module: typescript.ModuleKind.ESNext, + moduleResolution: typescript.ModuleResolutionKind.Bundler, + allowJs: true, + } + + if (!found) { + return { ...fallback, skipLibCheck: true, noEmit: true } + } + + const { options, errors } = typescript.convertCompilerOptionsFromJson( + found.config.compilerOptions ?? {}, + dirname(found.path), + ) + + if (errors.length > 0) { + warn( + `Could not read ${found.path}, falling back to defaults: ${ + typescript.flattenDiagnosticMessageText(errors[0].messageText, ' ') + }`, + ) + + return { ...fallback, skipLibCheck: true, noEmit: true } + } + + return { ...fallback, ...options, skipLibCheck: true, noEmit: true } +} + +function fingerprint(filePath: string, source: string, optionsFingerprint: string): string { + return createHash('sha256') + .update(filePath) + .update('\0') + .update(source) + .update('\0') + .update(optionsFingerprint) + .digest('hex') +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} diff --git a/packages/storybook-astro/framework/src/docgen/index.typescript7.test.ts b/packages/storybook-astro/framework/src/docgen/index.typescript7.test.ts new file mode 100644 index 0000000..da16fe5 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/index.typescript7.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test, vi } from 'vitest' +import { createAstroDocgen } from './index.ts' + +// TypeScript 7 (the native port) installs as `typescript`, but its default +// export is only the version — no compiler API (issue #197). Its own file +// because mocking `typescript` would take extraction away from the other suites. +vi.mock('typescript', () => ({ default: { version: '7.0.2', versionMajorMinor: '7.0' } })) + +describe('with TypeScript 7 installed', () => { + test('docgen skips with a warning instead of crashing Storybook', async () => { + const warnings: string[] = [] + const docgen = createAstroDocgen({ + projectRoot: process.cwd(), + warn: (message) => warnings.push(message), + }) + + await expect(docgen.warmUp()).resolves.toBeUndefined() + await expect(docgen.extract('/project/Card.astro', '---\n---\n

')).resolves.toBeNull() + + expect(warnings).toEqual([ + expect.stringContaining('TypeScript 7.0.2 does not include the compiler API'), + ]) + }) +}) diff --git a/packages/storybook-astro/framework/src/docgen/propFilter.ts b/packages/storybook-astro/framework/src/docgen/propFilter.ts new file mode 100644 index 0000000..9f5e985 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/propFilter.ts @@ -0,0 +1,43 @@ +import type { AstroDocgenProp, PropFilter } from './types.ts' + +const NODE_MODULES = /[/\\]node_modules[/\\]/ + +/** + * Keeps the props a reader came to see and drops inherited DOM noise. + * + * A `Props` extending `HTMLAttributes` or `Polymorphic` resolves to around 200 + * properties, 191 of them from `astro/astro-jsx.d.ts`. Unfiltered, every Astro + * props table is unusable (docs/specs/docgen.md#prop-filtering). + * + * Two rules that the conventional `react-docgen-typescript` recipe gets wrong + * for Astro: + * + * - A prop survives if *any* declaration sits outside `node_modules`. A + * locally redeclared `disabled` also has a declaration in `astro/types`, so + * dropping on the first `node_modules` hit silently deletes it. + * - A prop the component destructures from `Astro.props` always survives, + * wherever its type was declared. That destructuring is the author's own + * statement of the public surface, and it is what recovers `as`, `href` and + * `class` on a polymorphic component whose types all live in `node_modules`. + */ +export function createDefaultPropFilter(destructuredProps: ReadonlySet): PropFilter { + return (prop) => { + // Astro takes content through , so a `children` prop is inherited + // noise from a framework type unless someone documented it. + if (prop.name === 'children' && !prop.description) { + return false + } + + return destructuredProps.has(prop.name) || isDeclaredInProject(prop) + } +} + +function isDeclaredInProject(prop: AstroDocgenProp): boolean { + const declarations = prop.declarations ?? [] + + // No declaration information is not evidence of third-party origin. + return ( + declarations.length === 0 || + declarations.some((declaration) => !NODE_MODULES.test(declaration.fileName)) + ) +} diff --git a/packages/storybook-astro/framework/src/docgen/propsDeclaration.ts b/packages/storybook-astro/framework/src/docgen/propsDeclaration.ts new file mode 100644 index 0000000..e9be598 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/propsDeclaration.ts @@ -0,0 +1,101 @@ +import type ts from 'typescript' + +/** + * Rewrites `interface Props … extends A, B { … }` as `type Props … = A & B & { … }`. + * + * Astro's polymorphic idiom resolves to a deferred indexed access on a type + * parameter, and an interface may only extend types with statically known + * members. TypeScript reports 2312 and then drops the *entire* base type, so + * the component from #110 yields three props instead of 199. An intersection + * has no such restriction (docs/specs/docgen.md#heritage-rewrite). + * + * Returns `null` when there is nothing to rewrite. This is a fallback path, so + * unlike the rest of the virtual file it does not preserve byte offsets — the + * extractor reads types through the checker, not positions. + */ +export function rewriteInterfaceToTypeAlias( + typescript: typeof ts, + virtualSource: string, +): string | null { + const sourceFile = typescript.createSourceFile( + 'props-rewrite.ts', + virtualSource, + typescript.ScriptTarget.Latest, + true, + ) + + const declaration = sourceFile.statements.find( + (statement): statement is ts.InterfaceDeclaration => + typescript.isInterfaceDeclaration(statement) && + statement.name.text === 'Props' && + (statement.heritageClauses?.length ?? 0) > 0, + ) + + if (!declaration) { + return null + } + + const openBrace = declaration + .getChildren(sourceFile) + .find((child) => child.kind === typescript.SyntaxKind.OpenBraceToken) + + if (!openBrace) { + return null + } + + const typeParameters = declaration.typeParameters + ? `<${declaration.typeParameters.map((each) => each.getText(sourceFile)).join(', ')}>` + : '' + + const bases = (declaration.heritageClauses ?? []) + .flatMap((clause) => clause.types) + .map((each) => each.getText(sourceFile)) + + const members = virtualSource.slice(openBrace.getStart(sourceFile), declaration.end) + const alias = `type Props${typeParameters} = ${[...bases, members].join(' & ')};` + + return ( + virtualSource.slice(0, declaration.getStart(sourceFile)) + + alias + + virtualSource.slice(declaration.end) + ) +} + +/** + * String-literal constituents of the first type parameter's default. + * + * `keyof (A | B)` is the intersection of keys, so instantiating a polymorphic + * `Props<'a' | 'button'>` in one go loses `href` and `type` — each exists on + * only one constituent. Returning them lets the extractor instantiate per + * constituent and merge. Returns an empty array when there is nothing to split, + * or when the union is wider than `maxConstituents` — an unbounded default like + * `Tag extends HTMLTag = HTMLTag` would otherwise expand to every element. + */ +export function unionConstituentsOfFirstDefault( + typescript: typeof ts, + sourceFile: ts.SourceFile, + maxConstituents: number, +): string[] { + const declaration = sourceFile.statements.find( + (statement): statement is ts.InterfaceDeclaration | ts.TypeAliasDeclaration => + (typescript.isInterfaceDeclaration(statement) || + typescript.isTypeAliasDeclaration(statement)) && + statement.name.text === 'Props', + ) + + const defaultType = declaration?.typeParameters?.[0]?.default + + if (!defaultType || !typescript.isUnionTypeNode(defaultType)) { + return [] + } + + const constituents = defaultType.types.filter( + (each) => typescript.isLiteralTypeNode(each) && typescript.isStringLiteral(each.literal), + ) + + if (constituents.length !== defaultType.types.length || constituents.length > maxConstituents) { + return [] + } + + return constituents.map((each) => each.getText(sourceFile)) +} diff --git a/packages/storybook-astro/framework/src/docgen/slots.test.ts b/packages/storybook-astro/framework/src/docgen/slots.test.ts new file mode 100644 index 0000000..56e391d --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/slots.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, test } from 'vitest' +import { readSlots } from './slots.ts' + +describe('readSlots', () => { + test('lists the default slot and named slots, in the order they appear', () => { + const source = [ + '---', + 'const { title } = Astro.props;', + '---', + '
', + '
', + ' ', + "
Fallback
", + '
', + ].join('\n') + + expect(readSlots(source)).toEqual([ + { name: 'header', description: '' }, + { name: 'default', description: '' }, + { name: 'footer', description: '' }, + ]) + }) + + test('reads a description from an @slot comment directly before the slot', () => { + const source = [ + '
', + ' {/* @slot The card body */}', + ' ', + ' ', + ' ', + ' {/* A note about layout, not a slot description */}', + ' ', + '
', + ].join('\n') + + expect(readSlots(source)).toEqual([ + { name: 'default', description: 'The card body' }, + { name: 'actions', description: 'Actions shown under the body' }, + { name: 'aside', description: '' }, + ]) + }) + + test('ignores an @slot comment separated from the slot by other markup', () => { + const source = ['{/* @slot Not this one */}', '

Intro

', ''].join('\n') + + expect(readSlots(source)).toEqual([{ name: 'default', description: '' }]) + }) + + test('skips commented-out slots and slots with a computed name', () => { + const source = [ + '', + '{/* */}', + '', + '', + ].join('\n') + + expect(readSlots(source)).toEqual([{ name: 'kept', description: '' }]) + }) + + test('still finds slots after a comment inside an expression', () => { + const source = [ + '
    {/* render rows */ items.map((item) =>
  • {item}
  • )}
', + '', + '', + '{/* @slot Footer area */}', + '', + ].join('\n') + + expect(readSlots(source)).toEqual([ + { name: 'header', description: '' }, + { name: 'default', description: '' }, + { name: 'footer', description: 'Footer area' }, + ]) + }) + + test('lists each slot once, keeping the first description found', () => { + const source = ['', '{/* @slot The leading icon */}', ''].join('\n') + + expect(readSlots(source)).toEqual([{ name: 'icon', description: 'The leading icon' }]) + }) + + test('includes slots the frontmatter reads through Astro.slots', () => { + const source = [ + '---', + "const html = await Astro.slots.render('content');", + 'const hasFooter = Astro.slots.has("footer");', + '---', + '', + '', + ].join('\n') + + expect(readSlots(source)).toEqual([ + { name: 'footer', description: '' }, + { name: 'content', description: '' }, + ]) + }) + + test("doesn't read a written in a frontmatter string as a slot", () => { + const source = ['---', 'const example = \'\';', '---', '
'].join('\n') + + expect(readSlots(source)).toEqual([]) + }) +}) diff --git a/packages/storybook-astro/framework/src/docgen/slots.ts b/packages/storybook-astro/framework/src/docgen/slots.ts new file mode 100644 index 0000000..4bd5589 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/slots.ts @@ -0,0 +1,82 @@ +import type { AstroDocgenSlot } from './types.ts' +import { findClosingFence } from './virtualFile.ts' + +// A comment Astro strips (`{/* … */}`) or keeps (``), or a `` +// element. Matching comments in the same pass means a commented-out `` +// is consumed as part of its comment and never counts. The `{/* … */}` body +// can't cross a `*/`: a comment that opens an expression +// (`{/* rows */ items.map(…)}`) isn't a whole-expression comment, and letting it +// run on to the next `*/}` would swallow every slot in between. +const COMMENT_OR_SLOT = /\{\/\*((?:(?!\*\/)[\s\S])*)\*\/\}||]*)>/g +const SLOT_DESCRIPTION = /^\s*\*?\s*@slot\b\s*([\s\S]*?)\s*$/ +const NAME_ATTRIBUTE = /\bname\s*=\s*(?:"([^"]*)"|'([^']*)'|(\{))/ +const SLOTS_API_CALL = /\bAstro\.slots\.(?:render|has)\(\s*(?:'([^']+)'|"([^"]+)"|`([^`$]+)`)/g + +/** + * Lists the slots an `.astro` component accepts (issue #188): every `` in + * its template, plus the names its frontmatter reads through `Astro.slots.render` + * or `Astro.slots.has`. Slots have no TypeScript declaration, so this reads the + * source text, in the order slots first appear. + * + * A slot's description is a comment starting with `@slot` directly before it, + * the convention Vue's docgen uses: `{/* @slot The card body *\/}` or + * ``. A slot whose name is an expression + * (`name={…}`) can't be known without rendering, so it's skipped. + */ +export function readSlots(astroSource: string): AstroDocgenSlot[] { + const { frontmatter, template } = splitFrontmatter(astroSource) + const slots = new Map() + const add = (name: string, description = '') => { + const existing = slots.get(name) + + if (!existing) { + slots.set(name, { name, description }) + } else if (!existing.description) { + existing.description = description + } + } + + let pendingDescription: { text: string; end: number } | undefined + + for (const match of template.matchAll(COMMENT_OR_SLOT)) { + const [whole, astroComment, htmlComment, slotAttributes] = match + + if (slotAttributes === undefined) { + const text = (astroComment ?? htmlComment).match(SLOT_DESCRIPTION)?.[1] + + pendingDescription = text === undefined ? undefined : { text, end: match.index + whole.length } + continue + } + + const describedHere = pendingDescription && !template.slice(pendingDescription.end, match.index).trim() + const description = describedHere ? pendingDescription!.text : '' + + pendingDescription = undefined + + const name = NAME_ATTRIBUTE.exec(slotAttributes) + + if (name?.[3]) { + continue + } + + add(name ? (name[1] ?? name[2]) : 'default', description) + } + + // Frontmatter calls come after the template's slots: a component that renders + // a slot both ways keeps the template's description and position. + for (const match of frontmatter.matchAll(SLOTS_API_CALL)) { + add(match[1] ?? match[2] ?? match[3]) + } + + return [...slots.values()] +} + +function splitFrontmatter(source: string) { + const closingFence = source.startsWith('---') ? findClosingFence(source) : -1 + + if (closingFence === -1) { + return { frontmatter: '', template: source } + } + + return { frontmatter: source.slice(3, closingFence), template: source.slice(closingFence + 3) } +} diff --git a/packages/storybook-astro/framework/src/docgen/story-docs-payload.test.ts b/packages/storybook-astro/framework/src/docgen/story-docs-payload.test.ts new file mode 100644 index 0000000..179f0e4 --- /dev/null +++ b/packages/storybook-astro/framework/src/docgen/story-docs-payload.test.ts @@ -0,0 +1,399 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { IndexEntry } from 'storybook/internal/types' +import { afterAll, beforeAll, describe, expect, test } from 'vitest' +import { buildStoryDocsPayload } from './story-docs-payload.ts' + +// Inside the package, matching the existing .vitest-*-fixture-* convention. +const packageDir = fileURLToPath(new URL('../..', import.meta.url)) +const workingDir = mkdtempSync(join(packageDir, '.vitest-story-docs-fixture-')) + +const write = (name: string, lines: string[]) => writeFileSync(join(workingDir, name), lines.join('\n')) + +beforeAll(() => { + write('Button.astro', ['---', 'const { variant } = Astro.props;', '---', '']) + + write('Button.stories.jsx', [ + "import Button from './Button.astro';", + '', + "const shared = { size: 'lg' };", + '', + 'export default {', + " title: 'Astro/Button',", + ' component: Button,', + " args: { variant: 'solid' }", + '};', + '', + 'export const Default = {', + " parameters: { docs: { description: { story: 'Default solid button.' } } },", + " args: { slots: { default: 'Click me' } }", + '};', + '', + '/** Outline variant at large size. */', + 'export const Outline = {', + " args: { ...shared, variant: 'outline', items: [1, 2], slots: { default: 'Read the docs' } }", + '};', + '', + 'export const Labeled = {', + " name: 'With a label',", + " args: { 'slot-default': 'Labeled', onClick: () => {} }", + '};', + ]) + + write('Unreadable.stories.jsx', [ + "import Button from './Button.astro';", + "import { theme } from './theme.js';", + '', + 'export default {', + " title: 'Astro/Unreadable',", + ' component: Button', + '};', + '', + 'export const FromCall = { args: { variant: theme() } };', + '', + "export const Delegated = { parameters: { renderer: 'react' }, args: { variant: 'solid' } };", + ]) + + write('Options.stories.jsx', [ + "import Button from './Button.astro';", + '', + 'export default {', + " title: 'Astro/Options',", + ' component: Button,', + " args: { 'slot-default': 'Fallback' }", + '};', + '', + "export const SlotsArg = { args: { slots: { default: 'Real content' } } };", + '', + 'export const InlineObjects = {', + " parameters: { docs: { source: { objectProps: 'inline' } } },", + ' args: { items: [1, 2] }', + '};', + '', + '/** From the JSDoc. */', + 'export const BothDescriptions = {', + " parameters: { docs: { description: { story: 'From the parameter.' } } }", + '};', + '', + 'export const HandWritten = {', + " parameters: { docs: { source: { code: '' } } }", + '};', + '', + 'export const CsfSource = {', + " parameters: { docs: { source: { type: 'code' } } }", + '};', + ]) + + write('Handlers.stories.jsx', [ + "import { fn } from 'storybook/test';", + "import dedent from 'ts-dedent';", + "import Button from './Button.astro';", + '', + 'export default {', + " title: 'Astro/Handlers',", + ' component: Button,', + " args: { variant: 'solid', onClick: fn() }", + '};', + '', + 'export const Spy = {};', + '', + 'export const Method = {', + ' args: { onHover() {} }', + '};', + '', + 'export const TaggedCode = {', + ' parameters: { docs: { source: { code: dedent`` } } }', + '};', + ]) + + write('Shapes.stories.jsx', [ + "import Button from './Button.astro';", + '', + 'export default {', + " title: 'Astro/Shapes',", + ' component: Button', + '};', + '', + "export const CustomRender = { render: () => 'x', args: { label: 'a' } };", + '', + "export const RenderWithArgs = { render: (args) => args.label, args: { label: 'a' } };", + '', + "export const NoParams = () => 'x';", + ]) + + write('HiddenParameters.stories.jsx', [ + "import Button from './Button.astro';", + '', + "const delegated = { renderer: 'react' };", + "const reactParams = { renderer: 'react' };", + "const RENDERER = 'react';", + '', + 'export default {', + " title: 'Astro/HiddenParameters',", + ' component: Button', + '};', + '', + "export const FromVariable = { parameters: delegated, args: { variant: 'solid' } };", + '', + "export const FromSpread = { parameters: { ...reactParams }, args: { variant: 'solid' } };", + '', + "export const RendererVariable = { parameters: { renderer: RENDERER }, args: { variant: 'solid' } };", + '', + "export const Readable = { parameters: { layout: 'centered' }, args: { variant: 'solid' } };", + ]) + + write('HiddenMetaParameters.stories.jsx', [ + "import Button from './Button.astro';", + '', + "const shared = { renderer: 'react' };", + '', + 'export default {', + " title: 'Astro/HiddenMetaParameters',", + ' component: Button,', + ' parameters: shared', + '};', + '', + "export const Default = { args: { variant: 'solid' } };", + ]) + + write('Widget.tsx', ['export const Widget = () => null;']) + + write('Widget.stories.jsx', [ + "import { Widget } from './Widget.tsx';", + '', + 'export default {', + " title: 'React/Widget',", + ' component: Widget', + '};', + '', + 'export const Default = {};', + ]) +}) + +afterAll(() => rmSync(workingDir, { recursive: true, force: true })) + +function storyEntry(importPath: string, title: string): IndexEntry { + return { + type: 'story', + subtype: 'story', + id: `${title.toLowerCase().replace(/\W+/g, '-')}--default`, + name: 'Default', + title, + importPath: `./${importPath}`, + } as IndexEntry +} + +const build = (importPath: string, title: string) => + buildStoryDocsPayload({ entry: storyEntry(importPath, title) }, { workingDir }) + +describe('an Astro stories file', () => { + test('gives each story the Astro snippet Show code prints for it', async () => { + const payload = await build('Button.stories.jsx', 'Astro/Button') + + expect(payload).toMatchObject({ id: 'astro-button', name: 'Button', path: './Button.stories.jsx' }) + // Self-contained: core would put an `import` outside the frontmatter. + expect(payload).not.toHaveProperty('import') + expect(Object.keys(payload!.stories)).toEqual([ + 'astro-button--default', + 'astro-button--outline', + 'astro-button--labeled', + ]) + + expect(payload!.stories['astro-button--default']).toEqual({ + id: 'astro-button--default', + name: 'Default', + description: 'Default solid button.', + snippet: [ + '---', + "import Button from './Button.astro';", + '---', + '', + ].join('\n'), + }) + }) + + test('merges meta args, follows spreads and hoists object props as Show code does', async () => { + const payload = await build('Button.stories.jsx', 'Astro/Button') + const outline = payload!.stories['astro-button--outline'] + + expect(outline.description).toBe('Outline variant at large size.') + expect(outline.snippet).toBe( + [ + '---', + "import Button from './Button.astro';", + '', + 'const items = [', + ' 1,', + ' 2', + '];', + '---', + '', + ].join('\n'), + ) + }) + + test('keeps a story name and leaves out functions', async () => { + const payload = await build('Button.stories.jsx', 'Astro/Button') + + // An unedited `slot-` arg defers to `args.slots`, as in Show code + // and the canvas, so a story that sets only the per-slot arg fills no slot. + expect(payload!.stories['astro-button--labeled']).toMatchObject({ + name: 'With a label', + snippet: expect.stringContaining('', + }) + expect(payload!.stories['astro-options--hand-written'].warning).toBeUndefined() + }) + + test("docs.source.type: 'code' without code gets no snippet and no warning", async () => { + const payload = await build('Options.stories.jsx', 'Astro/Options') + const story = payload!.stories['astro-options--csf-source'] + + expect(story.snippet).toBeUndefined() + expect(story.warning).toBeUndefined() + }) +}) + +describe('function args and unreadable source', () => { + test('a meta-level fn() spy is left out, as Show code leaves it out', async () => { + const payload = await build('Handlers.stories.jsx', 'Astro/Handlers') + const story = payload!.stories['astro-handlers--spy'] + + expect(story.warning).toBeUndefined() + expect(story.snippet).toContain(''].join('\n') + + const virtual = buildVirtualSource(source) + + expect(virtual).toContain("const label = 'hi';") + expect(virtual).not.toContain('