@alexgorbatchev/storybook-test-runner-bun 1.0.3 → 1.0.4

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/README.md CHANGED
@@ -14,7 +14,7 @@ Pass your Storybook URL to `runStories`. It returns ordered per-story results, i
14
14
 
15
15
  # How it Really Works
16
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.
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. Its browser user agent includes Storybook’s test-runner marker so Storybook applies its test animation lifecycle. 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
18
 
19
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
20
 
@@ -118,7 +118,7 @@ Existing stories and browser-side `storybook/test` imports stay as they are. Cha
118
118
 
119
119
  # Browser Coverage
120
120
 
121
- The runner starts Playwright's native JavaScript coverage before navigating to the Storybook preview. Chromium tracks execution without instrumenting your application. Relative source-map filenames resolve against their served module, preserving directories in Vite development coverage. 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.
121
+ The runner starts Playwright's native JavaScript coverage before navigating to the Storybook preview. Chromium tracks execution without instrumenting your application. Relative source-map filenames resolve against their served module, preserving directories in Vite development coverage. With a coverage filter, unrelated scripts and inline source maps are discarded after each story to avoid retaining repeated dependency sources. External maps are resolved by Monocart. 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
122
 
123
123
  ```ts
124
124
  const results = await runStories({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgorbatchev/storybook-test-runner-bun",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "Bun-native Storybook browser test runner powered by Playwright",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,49 @@
1
+ import { coverageSourcePath } from "./coverageSourcePath";
2
+
3
+ interface ICoverageSource {
4
+ url: string;
5
+ source?: string;
6
+ }
7
+
8
+ export function coverageEntryMatches(entry: ICoverageSource, glob: Bun.Glob): boolean {
9
+ const servedPath = coverageSourcePath(entry.url, entry);
10
+ if (glob.match(servedPath)) return true;
11
+ const mappings = [...(entry.source ?? "").matchAll(/[#@]\s*sourceMappingURL=(\S+)/g)];
12
+ const mapping = mappings.at(-1)?.[1];
13
+ if (!mapping) return false;
14
+ // External maps are resolved by Monocart. Inline maps let us discard unrelated
15
+ // dependencies before retaining a copy of their source for every story.
16
+ if (!mapping.startsWith("data:")) return true;
17
+ try {
18
+ const comma = mapping.indexOf(",");
19
+ const payload = mapping.slice(comma + 1);
20
+ const sourceMap: unknown = JSON.parse(
21
+ mapping.slice(0, comma).endsWith(";base64")
22
+ ? Buffer.from(payload, "base64").toString("utf8")
23
+ : decodeURIComponent(payload),
24
+ );
25
+ if (
26
+ !sourceMap ||
27
+ typeof sourceMap !== "object" ||
28
+ !("sources" in sourceMap) ||
29
+ !Array.isArray(sourceMap.sources)
30
+ )
31
+ return true;
32
+ const root =
33
+ "sourceRoot" in sourceMap && typeof sourceMap.sourceRoot === "string"
34
+ ? sourceMap.sourceRoot
35
+ : "";
36
+ return sourceMap.sources.some(
37
+ (source: unknown) =>
38
+ typeof source === "string" &&
39
+ glob.match(
40
+ coverageSourcePath(source, {
41
+ url: root ? `${root.replace(/\/$/, "")}/${source}` : source,
42
+ distFile: servedPath,
43
+ }),
44
+ ),
45
+ );
46
+ } catch {
47
+ return true;
48
+ }
49
+ }
package/src/runStories.ts CHANGED
@@ -3,6 +3,7 @@ import { readStories } from "./readStories";
3
3
  import { observeStory } from "./observeStory";
4
4
  import { runHook } from "./runHook";
5
5
  import { writeCoverage } from "./writeCoverage";
6
+ import { coverageEntryMatches } from "./coverageEntryMatches";
6
7
  import type { BrowserCoverage, RunnerOptions, Story, StoryResult } from "./types";
7
8
  export async function runStories(options: RunnerOptions): Promise<StoryResult[]> {
8
9
  const base = new URL(options.url.endsWith("/") ? options.url : `${options.url}/`);
@@ -34,6 +35,8 @@ export async function runStories(options: RunnerOptions): Promise<StoryResult[]>
34
35
  const browser = await chromium.launch(options.launchOptions);
35
36
  const results: StoryResult[] = [];
36
37
  const coverage: BrowserCoverage = [];
38
+ let hasCoverageEntries = false;
39
+ const coverageGlob = options.coverageFilter ? new Bun.Glob(options.coverageFilter) : undefined;
37
40
  const groups = new Map<string, { index: number; story: Story }[]>();
38
41
  stories.forEach((story, index) => {
39
42
  const key = options.isolation === "component" ? story.title : String(index);
@@ -42,10 +45,16 @@ export async function runStories(options: RunnerOptions): Promise<StoryResult[]>
42
45
  const suites = [...groups.values()];
43
46
  const pending = suites.values();
44
47
  try {
48
+ const browserSession = await browser.newBrowserCDPSession();
49
+ const { userAgent } = await browserSession.send("Browser.getVersion");
50
+ await browserSession.detach();
45
51
  await Promise.all(
46
52
  Array.from({ length: Math.min(workers, suites.length) }, async () => {
47
53
  for (const suite of pending) {
48
- const context = await browser.newContext({ extraHTTPHeaders: headers });
54
+ const context = await browser.newContext({
55
+ extraHTTPHeaders: headers,
56
+ userAgent: `${userAgent} StorybookTestRunner`,
57
+ });
49
58
  try {
50
59
  for (const { index, story } of suite) {
51
60
  const started = performance.now();
@@ -100,7 +109,15 @@ export async function runStories(options: RunnerOptions): Promise<StoryResult[]>
100
109
  try {
101
110
  if (options.coverageDirectory) {
102
111
  const page = context.pages()[0];
103
- if (page) coverage.push(...(await page.coverage.stopJSCoverage()));
112
+ if (page) {
113
+ const entries = await page.coverage.stopJSCoverage();
114
+ hasCoverageEntries ||= entries.length > 0;
115
+ coverage.push(
116
+ ...(coverageGlob
117
+ ? entries.filter((entry) => coverageEntryMatches(entry, coverageGlob))
118
+ : entries),
119
+ );
120
+ }
104
121
  }
105
122
  } catch (error) {
106
123
  const message = error instanceof Error ? error.message : String(error);
@@ -118,6 +135,8 @@ export async function runStories(options: RunnerOptions): Promise<StoryResult[]>
118
135
  } finally {
119
136
  await browser.close();
120
137
  }
138
+ if (options.coverageDirectory && hasCoverageEntries && !coverage.length)
139
+ throw new Error("No browser coverage matched the coverage filter");
121
140
  if (options.coverageDirectory)
122
141
  await writeCoverage(coverage, options.coverageDirectory, options.coverageFilter);
123
142
  return results;
@@ -1,6 +1,7 @@
1
1
  import { CoverageReport } from "monocart-coverage-reports";
2
2
  import type { BrowserCoverage } from "./types";
3
3
  import { coverageSourcePath } from "./coverageSourcePath";
4
+ import { coverageEntryMatches } from "./coverageEntryMatches";
4
5
 
5
6
  export async function writeCoverage(
6
7
  data: BrowserCoverage,
@@ -14,10 +15,7 @@ export async function writeCoverage(
14
15
  reports: ["v8", "json", "lcovonly"],
15
16
  sourceFilter: filter,
16
17
  sourcePath: coverageSourcePath,
17
- entryFilter: (entry) =>
18
- !glob ||
19
- glob.match(coverageSourcePath(entry.url, entry)) ||
20
- Boolean(entry.source?.includes("sourceMappingURL=")),
18
+ entryFilter: (entry) => !glob || coverageEntryMatches(entry, glob),
21
19
  inline: true,
22
20
  logging: "off",
23
21
  cleanCache: true,