@chromatic-com/vitest 1.0.0 → 1.0.2

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.
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/dist/setupFile.js DELETED
@@ -1,287 +0,0 @@
1
- // src/browser/setupFile.ts
2
- import { afterEach, beforeEach, inject as inject2 } from "vitest";
3
- import { commands as commands4 } from "vitest/browser";
4
-
5
- // src/browser/public/takeSnapshot.ts
6
- import { assert } from "vitest";
7
- import { commands as commands2 } from "vitest/browser";
8
- import { snapshot as rrwebSnapshot, createMirror } from "@chromaui/rrweb-snapshot";
9
-
10
- // src/browser/getCurrentTest.ts
11
- import * as vitest from "vitest";
12
- var hooks = await resolveHooks();
13
- function getCurrentTest() {
14
- return hooks.getCurrentTest();
15
- }
16
- async function resolveHooks() {
17
- if (vitest.TestRunner) {
18
- return vitest.TestRunner;
19
- }
20
- return await import("vitest/suite");
21
- }
22
-
23
- // src/browser/isChromium.ts
24
- import { server } from "vitest/browser";
25
- function isChromium() {
26
- return server.browser === "chromium";
27
- }
28
-
29
- // src/browser/telemetry.ts
30
- import { commands } from "vitest/browser";
31
- import { inject } from "vitest";
32
- function trackEvent(event) {
33
- const enabled = inject("__chromatic_options")?.telemetry.enabled ?? false;
34
- if (enabled) {
35
- void commands.__chromatic_telemetry(event).catch(() => {
36
- });
37
- }
38
- }
39
-
40
- // src/browser/public/takeSnapshot.ts
41
- async function takeSnapshot(name, options) {
42
- if (!isChromium()) {
43
- return;
44
- }
45
- const test = getCurrentTest();
46
- if (!test) {
47
- trackEvent({
48
- eventType: "take_snapshot_invalid_call",
49
- level: "error",
50
- payload: { isInsideTest: false, isRegisteredTest: void 0, isAwaited: void 0 }
51
- });
52
- throw new TypeError("takeSnapshot() must be called within a test()");
53
- }
54
- if (!test.meta.__chromatic_isRegistered) {
55
- trackEvent({
56
- eventType: "take_snapshot_invalid_call",
57
- level: "error",
58
- payload: { isInsideTest: true, isRegisteredTest: false, isAwaited: void 0 }
59
- });
60
- throw new TypeError(
61
- `takeSnapshot() cannot be called in a test that is not registered for Chromatic plugin.
62
- Make sure ${test.file.projectName || "root"} project has chromaticPlugin() enabled.`
63
- );
64
- }
65
- const mirror = createMirror();
66
- const domSnapshot = snapshot({ document, mirror, onError: trackSnapshotError("capture") });
67
- const pseudoClassIds = {};
68
- for (const className of [":hover", ":focus", ":focus-visible", ":active"]) {
69
- const elements = document.querySelectorAll(className);
70
- const ids = Array.from(elements, (el) => mirror.getId(el)).filter((id) => id !== -1);
71
- pseudoClassIds[className] = ids;
72
- }
73
- const save = async () => {
74
- await replaceBlobUrls(domSnapshot).catch(trackSnapshotError("replace-blob-urls"));
75
- await commands2.__chromatic_uploadDOMSnapshot(
76
- test.id,
77
- domSnapshot,
78
- pseudoClassIds,
79
- name ?? null,
80
- // Convert undefined to null to avoid https://github.com/vitest-dev/vitest/issues/10864
81
- options
82
- ).catch(trackSnapshotError("upload"));
83
- test.meta.__chromatic_isTakeSnapshotCalled = true;
84
- };
85
- if (options?.isAutomaticSnapshot) {
86
- return await save();
87
- }
88
- const error = new Error("takeSnapshot() call was not awaited!");
89
- Error.captureStackTrace?.(error, takeSnapshot);
90
- const pendingCall = { promise: save(), error };
91
- test.meta.__chromatic_pendingTakeSnapshots ||= [];
92
- test.meta.__chromatic_pendingTakeSnapshots.push(pendingCall);
93
- await pendingCall.promise.finally(() => {
94
- const index = test.meta.__chromatic_pendingTakeSnapshots?.indexOf(pendingCall);
95
- if (index !== void 0 && index !== -1) {
96
- test.meta.__chromatic_pendingTakeSnapshots?.splice(index, 1);
97
- }
98
- });
99
- function trackSnapshotError(operation) {
100
- return function onError(error2) {
101
- trackEvent({
102
- eventType: "snapshot_error",
103
- level: "error",
104
- payload: {
105
- operation,
106
- isAutomaticSnapshot: options?.isAutomaticSnapshot ?? false,
107
- error: error2 instanceof Error ? error2.stack ?? error2.message : String(error2)
108
- }
109
- });
110
- throw error2;
111
- };
112
- }
113
- }
114
- function snapshot(options) {
115
- try {
116
- const domSnapshot = rrwebSnapshot(options.document, {
117
- recordCanvas: true,
118
- mirror: options.mirror
119
- });
120
- assert(domSnapshot, "Failed to capture DOM snapshot");
121
- return domSnapshot;
122
- } catch (error) {
123
- options.onError(error);
124
- throw error;
125
- }
126
- }
127
- async function replaceBlobUrls(node) {
128
- if (!("childNodes" in node)) {
129
- return;
130
- }
131
- await Promise.all(
132
- node.childNodes.map(async (childNode) => {
133
- if ("tagName" in childNode && childNode.tagName === "img" && typeof childNode.attributes.src === "string" && childNode.attributes.src?.startsWith("blob:")) {
134
- const base64Url = await toDataURL(childNode.attributes.src);
135
- childNode.attributes.src = base64Url;
136
- }
137
- if ("childNodes" in childNode && childNode.childNodes?.length) {
138
- await replaceBlobUrls(childNode);
139
- }
140
- })
141
- );
142
- }
143
- async function toDataURL(url) {
144
- const blob = await fetch(url).then((res) => res.blob());
145
- return new Promise((resolveFileRead, reject) => {
146
- const reader = new FileReader();
147
- reader.onloadend = () => resolveFileRead(reader.result?.toString() || "");
148
- reader.onerror = reject;
149
- reader.readAsDataURL(blob);
150
- });
151
- }
152
-
153
- // src/browser/public/waitForIdleNetwork.ts
154
- import { commands as commands3 } from "vitest/browser";
155
- async function waitForIdleNetwork(timeout, options) {
156
- if (!isChromium()) {
157
- return;
158
- }
159
- const isCalledByUser = options?._internal !== true;
160
- const test = getCurrentTest();
161
- if (!test) {
162
- trackEvent({
163
- eventType: "wait_for_idle_network_invalid_call",
164
- level: "error",
165
- payload: {
166
- isInsideTest: false,
167
- isRegisteredTest: void 0,
168
- isCalledByUser
169
- }
170
- });
171
- throw new TypeError("waitForIdleNetwork() must be called within a test()");
172
- }
173
- if (!test.meta.__chromatic_isRegistered) {
174
- trackEvent({
175
- eventType: "wait_for_idle_network_invalid_call",
176
- level: "error",
177
- payload: {
178
- isInsideTest: true,
179
- isRegisteredTest: false,
180
- isCalledByUser
181
- }
182
- });
183
- throw new TypeError(
184
- `waitForIdleNetwork() cannot be called in a test that is not registered for Chromatic plugin.
185
- Make sure ${test.file.projectName || "root"} project has chromaticPlugin() enabled.`
186
- );
187
- }
188
- if (isCalledByUser) {
189
- trackEvent({ eventType: "wait_for_idle_network_called", level: "info", payload: { timeout } });
190
- }
191
- try {
192
- await commands3.__chromatic_waitForIdleNetwork(timeout);
193
- } catch (error) {
194
- const isTimeoutError = error instanceof Error && error.message.includes("Timed out waiting for network to be idle");
195
- if (isTimeoutError) {
196
- trackEvent({
197
- eventType: "wait_for_idle_network_timeout",
198
- level: "error",
199
- payload: { timeout, isCalledByUser }
200
- });
201
- }
202
- throw error;
203
- }
204
- }
205
-
206
- // src/browser/setupFile.ts
207
- beforeEach(async ({ task }) => {
208
- const options = inject2("__chromatic_options");
209
- if (options.tags) {
210
- const hasMatchingTag = task.tags?.some((tag) => options.tags?.includes(tag));
211
- if (!hasMatchingTag) {
212
- task.meta.__chromatic_isRegistered = false;
213
- return cleanup;
214
- }
215
- }
216
- task.meta.__chromatic_isRegistered = true;
217
- task.meta.__chromatic_isTakeSnapshotCalled = false;
218
- task.meta.__chromatic_options ||= {};
219
- task.meta.__chromatic_options.disableAutoSnapshot ??= options.disableAutoSnapshot;
220
- task.meta.__chromatic_options.resourceArchiveTimeout ??= options.resourceArchiveTimeout;
221
- await commands4.__chromatic_interceptFetch();
222
- return async function beforeEachCleanup() {
223
- const {
224
- __chromatic_isTakeSnapshotCalled: isTakeSnapshotCalled,
225
- __chromatic_pendingTakeSnapshots: pendingTakeSnapshots,
226
- __chromatic_isRegistered: isRegistered
227
- } = task.meta;
228
- if (!isRegistered) {
229
- return cleanup();
230
- }
231
- if (pendingTakeSnapshots?.length) {
232
- throw new PendingSnapshotsError(pendingTakeSnapshots);
233
- }
234
- if (!isTakeSnapshotCalled) {
235
- await commands4.__chromatic_stopWithoutSnapshots(task.id);
236
- return cleanup();
237
- }
238
- await commands4.__chromatic_writeTestResult(task.id, task.meta.__chromatic_options);
239
- return cleanup();
240
- };
241
- function cleanup() {
242
- task.meta.__chromatic_options = void 0;
243
- task.meta.__chromatic_isTakeSnapshotCalled = void 0;
244
- task.meta.__chromatic_isRegistered = void 0;
245
- task.meta.__chromatic_pendingTakeSnapshots = void 0;
246
- }
247
- });
248
- afterEach(async ({ task }) => {
249
- const {
250
- __chromatic_options: options,
251
- __chromatic_pendingTakeSnapshots: pendingTakeSnapshots,
252
- __chromatic_isRegistered: isRegistered,
253
- __chromatic_options: testOptions
254
- } = task.meta;
255
- if (!isRegistered) {
256
- return;
257
- }
258
- if (pendingTakeSnapshots?.length) {
259
- throw new PendingSnapshotsError(pendingTakeSnapshots);
260
- }
261
- if (testOptions.resourceArchiveTimeout !== 0) {
262
- await document.fonts.ready;
263
- await waitForIdleNetwork(testOptions.resourceArchiveTimeout, { _internal: true });
264
- }
265
- if (!options.disableAutoSnapshot) {
266
- await takeSnapshot(void 0, { isAutomaticSnapshot: true });
267
- }
268
- });
269
- var PendingSnapshotsError = class extends AggregateError {
270
- constructor(pendingCalls) {
271
- super(
272
- pendingCalls.map((call) => call.error),
273
- `${pendingCalls.length} unawaited takeSnapshot() call(s)`
274
- );
275
- this.pendingCalls = pendingCalls;
276
- this.name = "PendingSnapshotsError";
277
- trackEvent({
278
- eventType: "take_snapshot_invalid_call",
279
- level: "error",
280
- payload: {
281
- isAwaited: false,
282
- isInsideTest: true,
283
- isRegisteredTest: true
284
- }
285
- });
286
- }
287
- };
@@ -1,5 +0,0 @@
1
- import { StorybookConfig } from '@storybook/server-webpack5';
2
-
3
- declare const _default: StorybookConfig;
4
-
5
- export { _default as default };
@@ -1,88 +0,0 @@
1
- // src/storybook-config/main.ts
2
- import path3 from "node:path";
3
- import { fileURLToPath, pathToFileURL } from "node:url";
4
- import { existsSync, readFileSync } from "node:fs";
5
-
6
- // ../shared/src/utils/filePaths.ts
7
- import path from "path";
8
- function rootDir() {
9
- return process.cwd();
10
- }
11
- function outputDirOverride() {
12
- const { CHROMATIC_ARCHIVE_LOCATION } = process.env;
13
- return CHROMATIC_ARCHIVE_LOCATION;
14
- }
15
- function archivesDir(defaultOutputDir) {
16
- const outputDir = outputDirOverride() || defaultOutputDir;
17
- return path.resolve(rootDir(), outputDir, "chromatic-archives");
18
- }
19
-
20
- // ../shared/src/utils/storybookPaths.ts
21
- import path2 from "node:path";
22
- import { createRequire } from "node:module";
23
- function storybookParentNodeModulesDir(importMetaUrl) {
24
- const require2 = createRequire(importMetaUrl);
25
- const dir = path2.dirname(path2.dirname(require2.resolve("storybook/package.json")));
26
- return path2.basename(dir) === "node_modules" ? dir : null;
27
- }
28
-
29
- // src/constants.ts
30
- var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
31
-
32
- // src/storybook-config/main.ts
33
- var __filename = fileURLToPath(import.meta.url);
34
- var __dirname = path3.dirname(__filename);
35
- var packageRoot = path3.resolve(__dirname, "..", "..");
36
- var embeddedDir = path3.join(packageRoot, "embedded", "node_modules");
37
- var main_default = {
38
- stories: [path3.resolve(archivesDir(DEFAULT_OUTPUT_DIR), "*.stories.json")],
39
- managerEntries: [path3.resolve(__dirname, "manager.js")],
40
- previewAnnotations: [path3.resolve(__dirname, "preview.js")],
41
- framework: {
42
- name: path3.join(embeddedDir, "@storybook", "server-webpack5"),
43
- options: {}
44
- },
45
- core: {
46
- // ESM does not support directory imports; point to the package entry file.
47
- builder: pathToFileURL(
48
- path3.join(embeddedDir, "@storybook", "builder-webpack5", "dist", "index.js")
49
- ).href,
50
- renderer: pathToFileURL(path3.join(embeddedDir, "@storybook", "server", "preset.js")).href
51
- },
52
- staticDirs: [path3.resolve(archivesDir(DEFAULT_OUTPUT_DIR), "archive")],
53
- features: {
54
- sidebarOnboardingChecklist: false
55
- },
56
- webpackFinal: async (config) => {
57
- config.target = ["web"];
58
- config.plugins.push(new VitestStatsPlugin());
59
- const storybookNodeModules = storybookParentNodeModulesDir(import.meta.url);
60
- if (storybookNodeModules) {
61
- config.resolve ??= {};
62
- config.resolve.modules = [
63
- ...config.resolve.modules ?? ["node_modules"],
64
- storybookNodeModules
65
- ];
66
- }
67
- return config;
68
- }
69
- };
70
- var VitestStatsPlugin = class {
71
- apply(compiler) {
72
- const chromaticResults = path3.dirname(archivesDir(DEFAULT_OUTPUT_DIR));
73
- const previewStats = path3.resolve(chromaticResults, "preview-stats.json");
74
- if (existsSync(previewStats)) {
75
- compiler.hooks.done.tap("Vitest Stats Plugin", (stats) => {
76
- const { modules } = JSON.parse(readFileSync(previewStats, "utf-8"));
77
- const toJson = stats.toJson.bind(stats);
78
- stats.toJson = (...args) => {
79
- const json = toJson(...args);
80
- return { ...json, modules: [...json.modules || [], ...modules] };
81
- };
82
- });
83
- }
84
- }
85
- };
86
- export {
87
- main_default as default
88
- };
@@ -1,2 +0,0 @@
1
-
2
- export { }
@@ -1,14 +0,0 @@
1
- // ../shared/storybook-config/manager.ts
2
- import { addons } from "storybook/manager-api";
3
- addons.setConfig({
4
- sidebar: {
5
- // Ensures we use folders at the root-level instead of categories
6
- showRoots: false
7
- },
8
- layoutCustomisations: {
9
- // Hide toolbar options that don't make sense in e2e setup
10
- showToolbar: () => false,
11
- // Hide bottom panel that's empty in e2e setup
12
- showPanel: () => false
13
- }
14
- });
@@ -1,17 +0,0 @@
1
- import { WebRenderer, RenderToCanvas } from 'storybook/internal/types';
2
-
3
- interface RRWebFramework extends WebRenderer {
4
- component: undefined;
5
- storyResult: Record<string, never>;
6
- }
7
- declare const _default: {
8
- renderToCanvas: RenderToCanvas<RRWebFramework>;
9
- parameters: {
10
- server: {
11
- url: string;
12
- };
13
- layout: string;
14
- };
15
- };
16
-
17
- export { type RRWebFramework, _default as default };
@@ -1,138 +0,0 @@
1
- // ../../node_modules/.pnpm/@rrweb+types@2.1.0/node_modules/@rrweb/types/dist/types.js
2
- var NodeType = /* @__PURE__ */ ((NodeType2) => {
3
- NodeType2[NodeType2["Document"] = 0] = "Document";
4
- NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
5
- NodeType2[NodeType2["Element"] = 2] = "Element";
6
- NodeType2[NodeType2["Text"] = 3] = "Text";
7
- NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
8
- NodeType2[NodeType2["Comment"] = 5] = "Comment";
9
- return NodeType2;
10
- })(NodeType || {});
11
-
12
- // ../shared/storybook-config/preview.ts
13
- import { rebuild, createMirror, createCache } from "@chromaui/rrweb-snapshot";
14
-
15
- // ../shared/src/utils/nodes.ts
16
- function isIframeSerializedNode(node) {
17
- return node.type === NodeType.Element && node.tagName === "iframe" && "contentDocument" in node && !!node.contentDocument;
18
- }
19
- function isElement(node) {
20
- return node?.nodeType === Node.ELEMENT_NODE;
21
- }
22
- function isIframeElement(node) {
23
- return isElement(node) && node.tagName.toLowerCase() === "iframe";
24
- }
25
-
26
- // ../shared/storybook-config/preview.ts
27
- var pageUrl = new URL(window.location.href);
28
- pageUrl.pathname = "";
29
- pageUrl.search = "";
30
- var strippedUrl = pageUrl.toString().replace(/\/$/, "");
31
- var findHtmlNode = (node) => {
32
- if (node.type === NodeType.Element && node.tagName === "html") {
33
- return node;
34
- }
35
- if ("childNodes" in node) {
36
- return node.childNodes.find((childNode) => {
37
- return findHtmlNode(childNode);
38
- });
39
- }
40
- return void 0;
41
- };
42
- var findNodeById = (node, id) => {
43
- if (node.id === id) {
44
- return node;
45
- }
46
- if ("childNodes" in node) {
47
- for (const childNode of node.childNodes) {
48
- const match = findNodeById(childNode, id);
49
- if (match) {
50
- return match;
51
- }
52
- }
53
- }
54
- return void 0;
55
- };
56
- function snapshotFileName(snapshotId, viewport) {
57
- const fileNameParts = [snapshotId, viewport, "snapshot.json"];
58
- return fileNameParts.join(".");
59
- }
60
- async function fetchSnapshot(context) {
61
- const { url, id } = context.storyContext.parameters.server;
62
- const { viewport } = context.storyContext.globals;
63
- let viewportName;
64
- if (typeof viewport === "string") {
65
- viewportName = viewport;
66
- } else {
67
- viewportName = `w${viewport.width}h${viewport.height}`;
68
- }
69
- let response = await fetch(`${url}/${snapshotFileName(id, viewportName)}`);
70
- if (!response.ok) {
71
- const { defaultViewport } = context.storyContext.parameters.viewport;
72
- response = await fetch(`${url}/${snapshotFileName(id, defaultViewport)}`);
73
- }
74
- return response.json();
75
- }
76
- var renderToCanvas = async (context) => {
77
- const { snapshot, pseudoClassIds } = await fetchSnapshot(context);
78
- const htmlNode = findHtmlNode(snapshot);
79
- const mirror = createMirror();
80
- const html = rebuild(htmlNode, {
81
- doc: document,
82
- mirror,
83
- cache: createCache(),
84
- afterAppend: afterAppendIframes(snapshot)
85
- });
86
- for (const [className, ids] of Object.entries(pseudoClassIds)) {
87
- for (const id of ids) {
88
- const el = mirror.getNode(id);
89
- if (isElement(el)) {
90
- el.classList.add(className);
91
- }
92
- }
93
- }
94
- document.replaceChild(html, document.children[0]);
95
- document.head.innerHTML += '<script id="storybook-root"><\/script><script id="storybook-docs"><\/script>';
96
- context.showMain();
97
- return () => {
98
- };
99
- };
100
- function afterAppendIframes(snapshot) {
101
- return function afterAppend(node, id) {
102
- if (!isIframeElement(node)) {
103
- return;
104
- }
105
- const serializedNode = findNodeById(snapshot, id);
106
- if (!isIframeSerializedNode(serializedNode)) {
107
- return;
108
- }
109
- node.onload = () => {
110
- const mirror = createMirror();
111
- rebuild(serializedNode.contentDocument, {
112
- doc: node.contentDocument,
113
- mirror,
114
- cache: createCache(),
115
- // Recursively build iframes within iframes
116
- afterAppend: afterAppendIframes(serializedNode.contentDocument)
117
- });
118
- for (const [className, ids] of Object.entries(serializedNode.pseudoClassIds)) {
119
- for (const id2 of ids) {
120
- const el = mirror.getNode(id2);
121
- if (isElement(el)) {
122
- el.classList.add(className);
123
- }
124
- }
125
- }
126
- };
127
- };
128
- }
129
- var preview_default = {
130
- renderToCanvas,
131
- parameters: {
132
- server: { url: strippedUrl },
133
- layout: "fullscreen"
134
- }
135
- };
136
- export {
137
- preview_default as default
138
- };