@alexgorbatchev/storybook-test-runner-bun 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Gorbatchev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ `@alexgorbatchev/storybook-test-runner-bun` replaces the browser test execution provided by `@storybook/test-runner` for Bun projects. It runs existing Storybook stories and play functions in Chromium, keeps the `test-storybook` command and visit hooks, and collects native browser coverage without a Jest runtime. Storybook can keep its existing Vite, Webpack, or other builder; this runner does not build your Storybook.
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # What It Does
4
+
5
+ - **Discover stories:** Read a running or published Storybook's `index.json`.
6
+ - **Execute interactions:** Wait for story completion and report render, play, and browser errors.
7
+ - **Control isolation:** Run components in parallel with sequential stories in the CLI; give each story a fresh context through the API by default.
8
+ - **Customize checks:** Filter by tags and run asynchronous hooks before and after each story.
9
+ - **Collect browser coverage:** Merge native Chromium coverage across stories and write Monocart HTML, JSON, and LCOV reports.
10
+
11
+ # How It Works
12
+
13
+ Pass your Storybook URL to `runStories`. It returns ordered per-story results, including failures and elapsed milliseconds. Index and browser startup failures reject the call.
14
+
15
+ # How it Really Works
16
+
17
+ The runner fetches `index.json`, opens `iframe.html` and selects each story through Storybook's event channel. It waits for `storyFinished`, which includes play execution, rather than treating an initial render as success. The CLI shares a page among stories with the same title, matching the original runner's component lifecycle. Different titles use separate contexts. The API defaults to a fresh context for every story; set `isolation: "component"` to use the CLI lifecycle. The runner closes its contexts and browser before returning.
18
+
19
+ The supplied Storybook must already be running. Its build system is independent of this package. Real-preview integration tests cover Storybook 10.6.9. Other versions are unverified. Chromium is the supported browser. Jest configuration, snapshot files, custom Jest reporters, watch mode, and Firefox/WebKit are not supported; unsupported command options and configuration keys fail explicitly.
20
+
21
+ # Prerequisites
22
+
23
+ - [Bun](https://bun.sh) 1.3 or later.
24
+ - A reachable Storybook exposing a version 5 story index and the `storyFinished` browser event.
25
+ - Peer dependencies: `playwright` 1.65.1 or later within 1.x, and `monocart-coverage-reports` 2.13.2 or later within 2.x.
26
+ - Playwright Chromium and its operating-system libraries.
27
+
28
+ # Installation
29
+
30
+ ```sh
31
+ bun add -d @alexgorbatchev/storybook-test-runner-bun playwright@^1.65.1 monocart-coverage-reports@^2.13.2
32
+ bun run playwright install chromium
33
+ ```
34
+
35
+ # Quick Start
36
+
37
+ With Storybook running, use the same command as the original runner:
38
+
39
+ ```sh
40
+ bun run test-storybook --url http://localhost:6006 --index-json --maxWorkers=2
41
+ ```
42
+
43
+ The command reads `.storybook/test-runner.ts` (also `.mts`, `.js`, `.mjs`, `.cts`, or `.cjs`), calls `setup` once, and runs `preVisit` and `postVisit` for each selected story. A failed story or an empty selection returns a nonzero exit code.
44
+
45
+ For programmatic use:
46
+
47
+ Save this as `stories.test.ts` and run `bun test stories.test.ts` with your Storybook running:
48
+
49
+ ```ts
50
+ import { expect, test } from "bun:test";
51
+ import { runStories } from "@alexgorbatchev/storybook-test-runner-bun";
52
+
53
+ test("Storybook stories", async () => {
54
+ const results = await runStories({ url: "http://localhost:6006" });
55
+ expect(results.filter((result) => result.error)).toEqual([]);
56
+ }, 120_000);
57
+ ```
58
+
59
+ # Configuration
60
+
61
+ The CLI accepts a positional title regular expression, `-t`/`--testNamePattern` for title plus story name, `-c`/`--config-dir`, `--url`, `--maxWorkers` (integer or percentage), `--testTimeout`, `--includeTags`, `--excludeTags`, `--skipTags`, `--coverage`, `--coverageDirectory`, `--coverageFilter`, `--verbose`, `--json`, and `--outputFile`. `--index-json`, `--ci`, and `--no-cache` are accepted: execution always reads the index, runs once, and uses no test cache. Run `test-storybook --help` for defaults. The CLI selects the `test` tag by default; configuration or CLI include tags override it. Skip tags remove stories from execution.
62
+
63
+ Configuration supports `setup`, `preVisit`, `postVisit`, deprecated `preRender`/`postRender` aliases, `tags`, `getHttpHeaders`, `prepare`, and `errorMessageFormatter`. Modern visit hooks take precedence over deprecated aliases. Headers apply to index requests and browser contexts. As in the original runner, `prepare` replaces default preview navigation: custom preparation must navigate to the preview and make its Storybook channel available.
64
+
65
+ Set `launchOptions` in your test-runner configuration (or `runStories` options) to pass Playwright's Chromium launch options directly to the browser. For example, preserve a macOS Metal GPU opt-in without Jest configuration:
66
+
67
+ ```ts
68
+ export default {
69
+ launchOptions: {
70
+ args:
71
+ process.env.MONOREPO_STORYBOOK_GPU === "1"
72
+ ? ["--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist"]
73
+ : [],
74
+ },
75
+ };
76
+ ```
77
+
78
+ The caller selects platform-specific flags; the runner does not enable Metal on other platforms. Move browser launch settings from Jest's `testEnvironmentOptions["jest-playwright"].launchOptions` here when migrating.
79
+
80
+ | Option | Default | Meaning |
81
+ | ------------------- | ----------- | ------------------------------------------------------------------------------------- |
82
+ | `url` | Required | Storybook base URL, including any deployment path |
83
+ | `workers` | `2` | Maximum parallel browser contexts |
84
+ | `timeout` | `15000` | Milliseconds for index fetch, navigation, readiness, and story completion, separately |
85
+ | `includeTags` | All | Include stories matching any listed tag |
86
+ | `excludeTags` | None | Exclude stories matching any listed tag |
87
+ | `coverageDirectory` | Disabled | Directory for browser coverage JSON, LCOV and HTML reports |
88
+ | `coverageFilter` | All sources | Monocart glob matching original source paths after source-map expansion |
89
+ | `preVisit` | None | Async `(page, story)` hook before selecting the story |
90
+ | `postVisit` | None | Async `(page, story)` hook after successful completion |
91
+
92
+ Each hook has the configured timeout. Timed-out hooks fail the story; hooks must own cleanup of any external work they start. An empty selection rejects rather than silently passing. Each result contains `story`, `duration`, and an optional `error` string. Importing the package does not start a browser.
93
+
94
+ # Migration from @storybook/test-runner
95
+
96
+ Replace the dependency and retain your existing command:
97
+
98
+ ```sh
99
+ bun remove @storybook/test-runner
100
+ bun add -d @alexgorbatchev/storybook-test-runner-bun playwright@^1.65.1 monocart-coverage-reports@^2.13.2
101
+ bun run test-storybook --url http://localhost:6006
102
+ ```
103
+
104
+ Change configuration type imports to the new package:
105
+
106
+ ```ts
107
+ import type { TestRunnerConfig } from "@alexgorbatchev/storybook-test-runner-bun";
108
+
109
+ const config: TestRunnerConfig = {
110
+ async preVisit(page) {
111
+ await page.setViewportSize({ width: 1280, height: 720 });
112
+ },
113
+ };
114
+ export default config;
115
+ ```
116
+
117
+ Existing stories and browser-side `storybook/test` imports stay as they are. Change imports of `getStoryContext` and `waitForPageReady` to the new package too. Hook code depending on Jest must be ported explicitly; changing an import alone does not make Jest snapshots or globals available in this standalone CLI. The package does not export `getJestConfig` or Jest's test transformation utilities. This is a command-and-hook replacement for the supported surface, rather than complete Jest feature parity.
118
+
119
+ # Browser Coverage
120
+
121
+ The runner starts Playwright's native JavaScript coverage before navigating to the Storybook preview. Chromium tracks execution without instrumenting your application. Monocart merges the results, maps bundled code back to original sources, and generates reports. Enable source maps in your Storybook build (for Bun builds, use `sourcemap: "inline"`) and make external source maps accessible to the runner if used.
122
+
123
+ ```ts
124
+ const results = await runStories({
125
+ url: "http://localhost:6006",
126
+ coverageDirectory: "coverage/storybook",
127
+ coverageFilter: "**/components/**",
128
+ });
129
+ expect(results.filter((result) => result.error)).toEqual([]);
130
+ ```
131
+
132
+ The directory receives Istanbul-compatible `coverage-final.json`, `lcov.info`, and a native Monocart HTML report at `index.html`. Collection stops after play and hooks, including failed stories, before closing each browser context. Each call collects fresh data. No collected coverage or a filter matching no source files rejects the call; report-writing errors also reject. Use a dedicated directory per runner call: Monocart replaces its previous reports there. Use `coverageFilter` to exclude Storybook internals, dependencies, and stories. It applies to original sources expanded from source maps; without maps, coverage describes the generated bundle. Files never loaded by the browser are not added automatically.
133
+
134
+ The runner uses Monocart 2.x because Monocart 3.x imports Node's `stripTypeScriptTypes`, which Bun 1.4.5 does not expose. Monocart still uses Istanbul libraries internally for compatible JSON and LCOV reporting; application instrumentation is unnecessary.
135
+
136
+ The runner's tests build a dummy project with three real Storybook HTML stories (Increment, Decrement, Reset) using Bun with inline source maps and no instrumentation. They verify merged component hit counts, untouched code, tag-filtered coverage, collection failures, and JSON/LCOV/HTML output. This browser coverage is separate from `bun test` coverage of the runner itself. Run it with `bun test src/__tests__/writeCoverage.test.ts`; `just test` includes it.
137
+
138
+ # License
139
+
140
+ [MIT](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@alexgorbatchev/storybook-test-runner-bun",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Bun-native Storybook browser test runner powered by Playwright",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/alexgorbatchev/storybook-test-runner-bun.git"
9
+ },
10
+ "bin": {
11
+ "test-storybook": "./src/cli.ts"
12
+ },
13
+ "files": [
14
+ "src/*.ts",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "type": "module",
19
+ "exports": {
20
+ ".": "./src/index.ts"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "devDependencies": {
26
+ "@storybook/html": "^10.6.9",
27
+ "@types/bun": "^1.4.5",
28
+ "@types/istanbul-lib-coverage": "^2.0.6",
29
+ "istanbul-lib-coverage": "^3.2.2",
30
+ "monocart-coverage-reports": "^2.13.2",
31
+ "oxfmt": "^0.80.0",
32
+ "oxlint": "^1.95.0",
33
+ "playwright": "^1.65.1",
34
+ "storybook": "^10.6.9",
35
+ "ts-unused": "^5.0.2",
36
+ "typescript": "^7.0.2"
37
+ },
38
+ "peerDependencies": {
39
+ "monocart-coverage-reports": "^2.13.2",
40
+ "playwright": "^1.65.1"
41
+ },
42
+ "engines": {
43
+ "bun": ">=1.3.0"
44
+ }
45
+ }
@@ -0,0 +1,27 @@
1
+ import type { Page } from "playwright";
2
+ import type { TestContext } from "./config";
3
+ export async function getStoryContext(page: Page, context: TestContext) {
4
+ return page.evaluate(async (id) => {
5
+ const preview = (
6
+ window as unknown as {
7
+ __STORYBOOK_PREVIEW__: {
8
+ storyStore: {
9
+ loadStory(options: { storyId: string }): Promise<{
10
+ id: string;
11
+ parameters: Record<string, unknown>;
12
+ args: Record<string, unknown>;
13
+ [key: string]: unknown;
14
+ }>;
15
+ };
16
+ };
17
+ }
18
+ ).__STORYBOOK_PREVIEW__;
19
+ return await preview.storyStore.loadStory({ storyId: id });
20
+ }, context.id);
21
+ }
22
+ export async function waitForPageReady(page: Page): Promise<void> {
23
+ await page.waitForLoadState("domcontentloaded");
24
+ await page.waitForLoadState("load");
25
+ await page.waitForLoadState("networkidle");
26
+ await page.evaluate(() => document.fonts.ready);
27
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env bun
2
+ import { parseCliArgs } from "./parseCliArgs";
3
+ import { availableParallelism } from "node:os";
4
+ import { runStories } from "./runStories";
5
+ import { getTestRunnerConfig } from "./config";
6
+
7
+ const CLI_HELP = `Usage: test-storybook [options] [pattern]
8
+
9
+ Run Storybook play tests with Bun and Playwright Chromium
10
+
11
+ Arguments:
12
+ pattern Regular expression matching story titles
13
+
14
+ Options:
15
+ --url <url> Storybook URL (default:
16
+ "http://127.0.0.1:6006")
17
+ -c, --config-dir <directory> Storybook configuration directory (default:
18
+ ".storybook")
19
+ -i, --index-json Read the Storybook index (always enabled)
20
+ --maxWorkers <amount> Parallel contexts, integer or percentage
21
+ (default: "2")
22
+ --testTimeout <milliseconds> Timeout per operation (default: "15000")
23
+ -t, --testNamePattern <pattern> Regular expression matching title and story
24
+ name
25
+ --includeTags <tags...> Include any of these tags
26
+ --excludeTags <tags...> Exclude these tags
27
+ --skipTags <tags...> Skip these tags
28
+ --coverage Collect native Chromium coverage
29
+ --coverageDirectory <directory> Coverage output directory (default:
30
+ "coverage/storybook")
31
+ --coverageFilter <glob> Original source paths to include
32
+ --json Print JSON results
33
+ --outputFile <file> Write JSON results
34
+ --verbose Print each result
35
+ --ci Run once for CI
36
+ --no-cache Accepted; no test cache is used
37
+ -h, --help display help for command`;
38
+
39
+ export async function cli(args: string[] = process.argv): Promise<number> {
40
+ try {
41
+ const { values: flags, positionals } = parseCliArgs(args.slice(2));
42
+ if (flags.help) {
43
+ console.log(CLI_HELP);
44
+ return 0;
45
+ }
46
+ const config = await getTestRunnerConfig(flags["config-dir"]);
47
+ const workers = flags.maxWorkers.endsWith("%")
48
+ ? Math.max(
49
+ 1,
50
+ Math.floor((availableParallelism() * Number(flags.maxWorkers.slice(0, -1))) / 100),
51
+ )
52
+ : Number(flags.maxWorkers);
53
+ const results = await runStories({
54
+ ...config,
55
+ isolation: "component",
56
+ url: flags.url,
57
+ workers,
58
+ timeout: Number(flags.testTimeout),
59
+ titlePattern: positionals[0],
60
+ testNamePattern: flags.testNamePattern,
61
+ includeTags: flags.includeTags ?? config.tags?.include ?? ["test"],
62
+ excludeTags: flags.excludeTags ?? config.tags?.exclude,
63
+ skipTags: flags.skipTags ?? config.tags?.skip,
64
+ coverageDirectory: flags.coverage ? flags.coverageDirectory : undefined,
65
+ coverageFilter: flags.coverageFilter,
66
+ });
67
+ const failures = results.filter((result) => result.error);
68
+ const output = JSON.stringify(
69
+ { total: results.length, passed: results.length - failures.length, failures, results },
70
+ null,
71
+ 2,
72
+ );
73
+ if (flags.outputFile) await Bun.write(flags.outputFile, output + "\n");
74
+ if (flags.json) console.log(output);
75
+ else {
76
+ for (const result of results)
77
+ if (flags.verbose || result.error)
78
+ console.log(
79
+ `${result.error ? "FAIL" : "PASS"} ${result.story.title} ${result.story.name}${result.error ? `: ${result.error}` : ""}`,
80
+ );
81
+ console.log(`${results.length - failures.length}/${results.length} stories passed`);
82
+ }
83
+ return failures.length ? 1 : 0;
84
+ } catch (error) {
85
+ console.error(error instanceof Error ? error.message : String(error));
86
+ return 1;
87
+ }
88
+ }
89
+ if (import.meta.main) process.exitCode = await cli();
package/src/config.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import type { Page, BrowserContext, LaunchOptions } from "playwright";
4
+ import type { Story } from "./types";
5
+ export type TestContext = Pick<Story, "id" | "title" | "name"> & { hasFailure?: boolean };
6
+ export type TestHook = (page: Page, context: TestContext) => Promise<void>;
7
+ export interface TestRunnerConfig {
8
+ launchOptions?: LaunchOptions;
9
+ setup?: () => void | Promise<void>;
10
+ preVisit?(page: Page, context: TestContext): Promise<void>;
11
+ postVisit?(page: Page, context: TestContext): Promise<void>;
12
+ preRender?: TestHook;
13
+ postRender?: TestHook;
14
+ tags?: { include?: string[]; exclude?: string[]; skip?: string[] };
15
+ getHttpHeaders?: (url: string) => Promise<Record<string, string>>;
16
+ prepare?: (context: {
17
+ page: Page;
18
+ browserContext: BrowserContext;
19
+ testRunnerConfig: TestRunnerConfig;
20
+ }) => Promise<void>;
21
+ errorMessageFormatter?: (error: string) => string;
22
+ }
23
+ export async function getTestRunnerConfig(directory = ".storybook"): Promise<TestRunnerConfig> {
24
+ for (const extension of ["ts", "mts", "js", "mjs", "cts", "cjs"]) {
25
+ const file = resolve(directory, `test-runner.${extension}`);
26
+ if (await Bun.file(file).exists()) {
27
+ const config = (await import(pathToFileURL(file).href)).default;
28
+ const supported = new Set([
29
+ "launchOptions",
30
+ "setup",
31
+ "preVisit",
32
+ "postVisit",
33
+ "preRender",
34
+ "postRender",
35
+ "tags",
36
+ "prepare",
37
+ "getHttpHeaders",
38
+ "errorMessageFormatter",
39
+ ]);
40
+ for (const key of Object.keys(config))
41
+ if (!supported.has(key)) throw new Error(`Unsupported test-runner configuration: ${key}`);
42
+ return config;
43
+ }
44
+ }
45
+ return {};
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { runStories } from "./runStories";
2
+ export { getStoryContext, waitForPageReady } from "./browserHelpers";
3
+ export { getTestRunnerConfig } from "./config";
4
+ export type { TestRunnerConfig, TestContext, TestHook } from "./config";
5
+ export type { RunnerOptions, Story, StoryResult } from "./types";
@@ -0,0 +1,44 @@
1
+ export function observeStory(input: { id: string; timeout: number }): Promise<void> {
2
+ return new Promise((resolve, reject) => {
3
+ const channel = window.__STORYBOOK_ADDONS_CHANNEL__;
4
+ if (!channel) {
5
+ reject(new Error("Storybook channel is unavailable"));
6
+ return;
7
+ }
8
+ const listeners = new Map<string, (data: unknown) => void>();
9
+ const finish = (error?: string) => {
10
+ clearTimeout(timer);
11
+ for (const [event, listener] of listeners) channel.off(event, listener);
12
+ if (error) reject(new Error(error));
13
+ else resolve();
14
+ };
15
+ const timer = setTimeout(
16
+ () => finish(`Story ${input.id} timed out after ${input.timeout}ms`),
17
+ input.timeout,
18
+ );
19
+ const fail = (data: unknown) => {
20
+ const message =
21
+ data && typeof data === "object" && "message" in data
22
+ ? String(data.message)
23
+ : JSON.stringify(data);
24
+ finish(message || "Story failed");
25
+ };
26
+ listeners.set("storyFinished", (data) => {
27
+ if (data && typeof data === "object" && "storyId" in data && data.storyId !== input.id)
28
+ return;
29
+ if (data && typeof data === "object" && "status" in data && data.status === "error")
30
+ fail(data);
31
+ else finish();
32
+ });
33
+ for (const event of [
34
+ "storyErrored",
35
+ "storyThrewException",
36
+ "playFunctionThrewException",
37
+ "unhandledErrorsWhilePlaying",
38
+ "storyMissing",
39
+ ])
40
+ listeners.set(event, fail);
41
+ for (const [event, listener] of listeners) channel.on(event, listener);
42
+ channel.emit("setCurrentStory", { storyId: input.id, viewMode: "story" });
43
+ });
44
+ }
@@ -0,0 +1,54 @@
1
+ import { parseArgs, type ParseArgsOptionsConfig } from "node:util";
2
+
3
+ const CLI_OPTIONS = {
4
+ url: { type: "string", default: "http://127.0.0.1:6006" },
5
+ "config-dir": { type: "string", short: "c", default: ".storybook" },
6
+ "index-json": { type: "boolean", short: "i" },
7
+ maxWorkers: { type: "string", default: "2" },
8
+ testTimeout: { type: "string", default: "15000" },
9
+ testNamePattern: { type: "string", short: "t" },
10
+ includeTags: { type: "string", multiple: true },
11
+ excludeTags: { type: "string", multiple: true },
12
+ skipTags: { type: "string", multiple: true },
13
+ coverage: { type: "boolean" },
14
+ coverageDirectory: { type: "string", default: "coverage/storybook" },
15
+ coverageFilter: { type: "string" },
16
+ json: { type: "boolean" },
17
+ outputFile: { type: "string" },
18
+ verbose: { type: "boolean" },
19
+ ci: { type: "boolean" },
20
+ "no-cache": { type: "boolean" },
21
+ help: { type: "boolean", short: "h" },
22
+ } satisfies ParseArgsOptionsConfig;
23
+
24
+ export function parseCliArgs(
25
+ args: string[],
26
+ ): ReturnType<typeof parseArgs<{ options: typeof CLI_OPTIONS; allowPositionals: true }>> {
27
+ const normalized: string[] = [];
28
+ let tagOption: string | undefined;
29
+ let isAfterTerminator = false;
30
+ for (const argument of args) {
31
+ if (isAfterTerminator) {
32
+ normalized.push(argument);
33
+ } else if (argument === "--") {
34
+ isAfterTerminator = true;
35
+ tagOption = undefined;
36
+ normalized.push(argument);
37
+ } else if (argument.startsWith("-")) {
38
+ tagOption = /^--(?:include|exclude|skip)Tags$/.test(argument) ? argument : undefined;
39
+ normalized.push(argument);
40
+ } else if (tagOption && normalized.at(-1) !== tagOption) {
41
+ normalized.push(`${tagOption}=${argument}`);
42
+ } else {
43
+ normalized.push(argument);
44
+ }
45
+ }
46
+ const parsed = parseArgs({
47
+ args: normalized,
48
+ strict: true,
49
+ allowPositionals: true,
50
+ options: CLI_OPTIONS,
51
+ });
52
+ if (parsed.positionals.length > 1) throw new Error("Expected at most one story title pattern");
53
+ return parsed;
54
+ }
@@ -0,0 +1,31 @@
1
+ import type { Story } from "./types";
2
+ export function readStories(value: unknown): Story[] {
3
+ if (
4
+ !value ||
5
+ typeof value !== "object" ||
6
+ !("entries" in value) ||
7
+ !value.entries ||
8
+ typeof value.entries !== "object"
9
+ )
10
+ throw new Error("Expected a Storybook index.json with entries");
11
+ const stories: Story[] = [];
12
+ for (const entry of Object.values(value.entries)) {
13
+ if (!entry || typeof entry !== "object" || !("type" in entry) || entry.type !== "story")
14
+ continue;
15
+ if (
16
+ !("id" in entry) ||
17
+ typeof entry.id !== "string" ||
18
+ !("title" in entry) ||
19
+ typeof entry.title !== "string" ||
20
+ !("name" in entry) ||
21
+ typeof entry.name !== "string"
22
+ )
23
+ throw new Error("Invalid story index entry");
24
+ const tags =
25
+ "tags" in entry && Array.isArray(entry.tags)
26
+ ? entry.tags.filter((tag: unknown): tag is string => typeof tag === "string")
27
+ : [];
28
+ stories.push({ id: entry.id, title: entry.title, name: entry.name, tags });
29
+ }
30
+ return stories;
31
+ }
package/src/runHook.ts ADDED
@@ -0,0 +1,16 @@
1
+ export async function runHook(
2
+ hook: () => Promise<void> | undefined,
3
+ timeout: number,
4
+ ): Promise<void> {
5
+ let timer: ReturnType<typeof setTimeout> | undefined;
6
+ try {
7
+ await Promise.race([
8
+ Promise.resolve().then(hook),
9
+ new Promise<never>((_, reject) => {
10
+ timer = setTimeout(() => reject(new Error(`Hook timed out after ${timeout}ms`)), timeout);
11
+ }),
12
+ ]);
13
+ } finally {
14
+ clearTimeout(timer);
15
+ }
16
+ }
@@ -0,0 +1,124 @@
1
+ import { chromium } from "playwright";
2
+ import { readStories } from "./readStories";
3
+ import { observeStory } from "./observeStory";
4
+ import { runHook } from "./runHook";
5
+ import { writeCoverage } from "./writeCoverage";
6
+ import type { BrowserCoverage, RunnerOptions, Story, StoryResult } from "./types";
7
+ export async function runStories(options: RunnerOptions): Promise<StoryResult[]> {
8
+ const base = new URL(options.url.endsWith("/") ? options.url : `${options.url}/`);
9
+ if (!["http:", "https:"].includes(base.protocol))
10
+ throw new Error("Storybook URL must use HTTP or HTTPS");
11
+ const timeout = options.timeout ?? 15000;
12
+ const workers = options.workers ?? 2;
13
+ if (!Number.isInteger(workers) || workers < 1 || !Number.isFinite(timeout) || timeout <= 0)
14
+ throw new Error("workers must be a positive integer and timeout must be positive");
15
+ const title = options.titlePattern ? new RegExp(options.titlePattern, "i") : undefined;
16
+ const name = options.testNamePattern ? new RegExp(options.testNamePattern, "i") : undefined;
17
+ const headers = await options.getHttpHeaders?.(base.href);
18
+ const response = await fetch(new URL("index.json", base), {
19
+ signal: AbortSignal.timeout(timeout),
20
+ headers,
21
+ });
22
+ if (!response.ok) throw new Error(`Storybook index request failed: ${response.status}`);
23
+ const stories = readStories(await response.json()).filter(
24
+ (story) =>
25
+ (!title || title.test(story.title)) &&
26
+ (!name || name.test(`${story.title} ${story.name}`)) &&
27
+ !options.skipTags?.some((tag) => story.tags.includes(tag)) &&
28
+ (!options.includeTags?.length ||
29
+ options.includeTags.some((tag) => story.tags.includes(tag))) &&
30
+ !options.excludeTags?.some((tag) => story.tags.includes(tag)),
31
+ );
32
+ if (!stories.length) throw new Error("No matching stories found");
33
+ await options.setup?.();
34
+ const browser = await chromium.launch(options.launchOptions);
35
+ const results: StoryResult[] = [];
36
+ const coverage: BrowserCoverage = [];
37
+ const groups = new Map<string, { index: number; story: Story }[]>();
38
+ stories.forEach((story, index) => {
39
+ const key = options.isolation === "component" ? story.title : String(index);
40
+ groups.set(key, [...(groups.get(key) ?? []), { index, story }]);
41
+ });
42
+ const suites = [...groups.values()];
43
+ const pending = suites.values();
44
+ try {
45
+ await Promise.all(
46
+ Array.from({ length: Math.min(workers, suites.length) }, async () => {
47
+ for (const suite of pending) {
48
+ const context = await browser.newContext({ extraHTTPHeaders: headers });
49
+ try {
50
+ for (const { index, story } of suite) {
51
+ const started = performance.now();
52
+ let removeErrorListener: (() => void) | undefined;
53
+ try {
54
+ const existing = context.pages()[0];
55
+ const page = existing ?? (await context.newPage());
56
+ page.setDefaultTimeout(timeout);
57
+ page.setDefaultNavigationTimeout(timeout);
58
+ const errors: string[] = [];
59
+ const onError = (error: Error) => errors.push(error.message);
60
+ page.on("pageerror", onError);
61
+ removeErrorListener = () => {
62
+ page.off("pageerror", onError);
63
+ };
64
+ if (options.coverageDirectory) await page.coverage.startJSCoverage();
65
+ if (!existing && options.prepare)
66
+ await runHook(
67
+ () =>
68
+ options.prepare!({
69
+ page,
70
+ browserContext: context,
71
+ testRunnerConfig: options,
72
+ }),
73
+ timeout,
74
+ );
75
+ else if (!existing) await page.goto(new URL("iframe.html", base).href);
76
+ await page.waitForFunction("Boolean(window.__STORYBOOK_ADDONS_CHANNEL__)");
77
+ await page.evaluate(() => document.fonts.ready);
78
+ await runHook(
79
+ () => (options.preVisit ?? options.preRender)?.(page, story),
80
+ timeout,
81
+ );
82
+ await page.evaluate(observeStory, { id: story.id, timeout });
83
+ await runHook(
84
+ () => (options.postVisit ?? options.postRender)?.(page, story),
85
+ timeout,
86
+ );
87
+ if (errors.length) throw new Error(errors.join("\n"));
88
+ results[index] = { story, duration: performance.now() - started };
89
+ } catch (error) {
90
+ results[index] = {
91
+ story,
92
+ error:
93
+ options.errorMessageFormatter?.(
94
+ error instanceof Error ? error.message : String(error),
95
+ ) ?? (error instanceof Error ? error.message : String(error)),
96
+ duration: performance.now() - started,
97
+ };
98
+ } finally {
99
+ removeErrorListener?.();
100
+ try {
101
+ if (options.coverageDirectory) {
102
+ const page = context.pages()[0];
103
+ if (page) coverage.push(...(await page.coverage.stopJSCoverage()));
104
+ }
105
+ } catch (error) {
106
+ const message = error instanceof Error ? error.message : String(error);
107
+ const result = results[index];
108
+ if (result) result.error = [result.error, message].filter(Boolean).join("\n");
109
+ }
110
+ }
111
+ }
112
+ } finally {
113
+ await context.close();
114
+ }
115
+ }
116
+ }),
117
+ );
118
+ } finally {
119
+ await browser.close();
120
+ }
121
+ if (options.coverageDirectory)
122
+ await writeCoverage(coverage, options.coverageDirectory, options.coverageFilter);
123
+ return results;
124
+ }
package/src/types.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { Page } from "playwright";
2
+ import type { TestRunnerConfig } from "./config";
3
+ export type BrowserCoverage = Awaited<ReturnType<Page["coverage"]["stopJSCoverage"]>>;
4
+ export interface Story {
5
+ id: string;
6
+ title: string;
7
+ name: string;
8
+ tags: string[];
9
+ }
10
+ export interface RunnerOptions extends Omit<TestRunnerConfig, "preVisit" | "postVisit"> {
11
+ url: string;
12
+ timeout?: number;
13
+ workers?: number;
14
+ includeTags?: string[];
15
+ excludeTags?: string[];
16
+ skipTags?: string[];
17
+ titlePattern?: string;
18
+ testNamePattern?: string;
19
+ isolation?: "story" | "component";
20
+ coverageDirectory?: string;
21
+ coverageFilter?: string;
22
+ preVisit?: (page: Page, story: Story) => Promise<void>;
23
+ postVisit?: (page: Page, story: Story) => Promise<void>;
24
+ }
25
+ export interface StoryResult {
26
+ story: Story;
27
+ error?: string;
28
+ duration: number;
29
+ }
30
+ export interface BrowserChannel {
31
+ on(event: string, listener: (data: unknown) => void): void;
32
+ off(event: string, listener: (data: unknown) => void): void;
33
+ emit(event: string, data: unknown): void;
34
+ }
35
+ declare global {
36
+ interface Window {
37
+ __STORYBOOK_ADDONS_CHANNEL__?: BrowserChannel;
38
+ }
39
+ }
@@ -0,0 +1,25 @@
1
+ import { CoverageReport } from "monocart-coverage-reports";
2
+ import type { BrowserCoverage } from "./types";
3
+
4
+ export async function writeCoverage(
5
+ data: BrowserCoverage,
6
+ directory: string,
7
+ filter?: string,
8
+ ): Promise<void> {
9
+ if (!data.length) throw new Error("No browser coverage was collected");
10
+ const report = new CoverageReport({
11
+ outputDir: directory,
12
+ reports: ["v8", "json", "lcovonly"],
13
+ sourceFilter: filter,
14
+ inline: true,
15
+ logging: "off",
16
+ cleanCache: true,
17
+ });
18
+ try {
19
+ await report.add(data);
20
+ const results = await report.generate();
21
+ if (!results?.files.length) throw new Error("No browser coverage matched the coverage filter");
22
+ } finally {
23
+ report.cleanCache();
24
+ }
25
+ }