storybook-addon-vis 0.4.0 → 0.6.0

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 CHANGED
@@ -1,6 +1,6 @@
1
- MIT License
1
+ The MIT License (MIT)
2
2
 
3
- Copyright (c) 2023 Storybook contributors
3
+ Copyright © 2024 Homa Wong (unional) (homawong@gmail.com)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -9,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
9
  copies of the Software, and to permit persons to whom the Software is
10
10
  furnished to do so, subject to the following conditions:
11
11
 
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
14
 
15
15
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
16
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
17
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
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.
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -1,17 +1,22 @@
1
- import { PixelmatchOptions } from 'pixelmatch';
1
+ import { BrowserPage, CDPSession, BrowserCommands, Platform } from '@vitest/browser/context';
2
2
  import { AsyncExpectationResult } from '@vitest/expect';
3
- import { CDPSession, BrowserCommands, BrowserPage, Platform } from '@vitest/browser/context';
3
+ import { PixelmatchOptions } from 'pixelmatch';
4
4
  import { SerializedConfig } from 'vitest';
5
5
 
6
- type ImageSnapshotOptions = {
6
+ interface ImageSnapshotOptions extends CustomizeSnapshotIdOptions {
7
+ element?: Element;
8
+ timeout?: number | undefined;
9
+ }
10
+ type CustomizeSnapshotIdOptions = {
7
11
  /**
8
- * Customize the filename of the snapshot.
12
+ * Customize the snapshot id. This is used as the filename of the snapshot:
13
+ *
14
+ * `${snapshotId}.png`
9
15
  *
10
16
  * @param id The id of the snapshot.
11
17
  * @param index The index of the snapshot.
12
18
  */
13
- customizeFilename?: (id: string, index: number) => string;
14
- element?: Element;
19
+ customizeSnapshotId?: (id: string, index: number) => string;
15
20
  };
16
21
  type ImageSnapshot = {
17
22
  type: symbol;
@@ -22,6 +27,18 @@ type ImageSnapshot = {
22
27
  base64: string;
23
28
  image: ImageData;
24
29
  };
30
+
31
+ interface HasImageSnapshotAction {
32
+ hasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined): Promise<boolean>;
33
+ }
34
+
35
+ interface ImageSnapshotAction {
36
+ imageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions | undefined): Promise<ImageSnapshot>;
37
+ }
38
+
39
+ interface ImageSnapshotMatcher {
40
+ toMatchImageSnapshot(options?: MatchImageSnapshotOptions): Promise<void>;
41
+ }
25
42
  type MatchImageSnapshotOptions = {
26
43
  /**
27
44
  * Custom options passed to 'pixelmatch'
@@ -35,34 +52,50 @@ type MatchImageSnapshotOptions = {
35
52
  failureThresholdType?: 'pixel' | 'percent' | undefined;
36
53
  failureThreshold?: number | undefined;
37
54
  };
55
+ declare function toMatchImageSnapshot(actual: any, options?: MatchImageSnapshotOptions | undefined): AsyncExpectationResult;
56
+
57
+ interface CopyFileCommand {
58
+ copyFile(src: string, dest: string): Promise<void>;
59
+ }
60
+
61
+ interface ExistDirCommand {
62
+ existDir: (path: string) => Promise<boolean>;
63
+ }
64
+
65
+ interface ExistFileCommand {
66
+ existFile: (path: string) => Promise<boolean>;
67
+ }
68
+
69
+ interface GetSnapshotPlatformCommand {
70
+ /**
71
+ * Get the platform id of the snapshot `{platform}[-ci]`.
72
+ *
73
+ * This is useful to control where the snapshot is stored.
74
+ */
75
+ getSnapshotPlatform: () => Promise<string>;
76
+ }
77
+
78
+ interface IsCICommand {
79
+ isCI: () => Promise<boolean>;
80
+ }
81
+
82
+ interface RmDirCommand {
83
+ rmDir: (path: string) => Promise<void>;
84
+ }
38
85
 
39
86
  declare module '@vitest/browser/context' {
40
- interface BrowserPage {
41
- imageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions): Promise<ImageSnapshot>;
87
+ interface BrowserPage extends ImageSnapshotAction, HasImageSnapshotAction {
42
88
  }
43
- interface BrowserCommands {
44
- existDir: (path: string) => Promise<boolean>;
45
- copyFile: (src: string, dest: string) => Promise<void>;
46
- rmDir: (path: string) => Promise<void>;
47
- isCI: () => Promise<boolean>;
48
- /**
49
- * Get the platform id of the snapshot `{platform}[-ci]`.
50
- *
51
- * This is useful to control where the snapshot is stored.
52
- */
53
- getSnapshotPlatform: () => Promise<string>;
89
+ interface BrowserCommands extends CopyFileCommand, ExistDirCommand, GetSnapshotPlatformCommand, RmDirCommand, IsCICommand, ExistFileCommand {
54
90
  }
55
91
  }
56
92
  declare global {
57
93
  namespace jest {
58
- interface Matchers<R, T> {
59
- toMatchImageSnapshot(options?: MatchImageSnapshotOptions): void;
94
+ interface Matchers<R, T> extends ImageSnapshotMatcher {
60
95
  }
61
96
  }
62
97
  }
63
98
 
64
- declare function toMatchImageSnapshot(actual: any, options?: MatchImageSnapshotOptions | undefined): AsyncExpectationResult;
65
-
66
99
  declare function cdp(): CDPSession;
67
100
  declare const commands: BrowserCommands;
68
101
  declare const page: BrowserPage;
@@ -100,4 +133,4 @@ declare function defineSnapshotParam(snapshot: MatchImageSnapshotOptions): {
100
133
  snapshot: MatchImageSnapshotOptions;
101
134
  };
102
135
 
103
- export { type ImageSnapshot, type ImageSnapshotOptions, type MatchImageSnapshotOptions, cdp, commands, defineSnapshotParam, page, server, toMatchImageSnapshot };
136
+ export { type CustomizeSnapshotIdOptions, type ImageSnapshot, type ImageSnapshotMatcher, type ImageSnapshotOptions, type MatchImageSnapshotOptions, cdp, commands, defineSnapshotParam, page, server, toMatchImageSnapshot };
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
- import F from'dedent';import M from'pixelmatch';import {getByAltText,getByRole,getByTestId,getByText,getByTitle,getByPlaceholderText,getByLabelText}from'@storybook/test';import {join}from'pathe';var g=Symbol.for("storybook-addon-vis/imageSnapshot"),d=Symbol.for("storybook-addon-vis/imageSnapshotStub");function f(t){return new Promise((e,a)=>{let o=new Image;o.src=`data:image/png;base64,${t}`,o.onload=()=>{let r=document.createElement("canvas");r.width=o.width,r.height=o.height;let n=r.getContext("2d");n.drawImage(o,0,0),e(n.getImageData(0,0,r.width,r.height));},o.onerror=()=>{a(new Error("Failed to load image"));};})}async function w(t){let e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").putImageData(t,0,0),new Promise(o=>{e.toBlob(r=>{let n=new FileReader;n.onload=()=>{o(n.result);},n.readAsDataURL(r);});})}var c={name:"",testFilepath:"",taskName:"",snapshot:{}};async function x(t){let e=c.snapshot[c.id].index++,a=t?.customizeFilename?`${t.customizeFilename(c.id,e)}.png`:`${c.id}-${e}.png`,o=join(c.baselineDir,a),r=join(c.resultDir,a),n=join(c.diffDir,a),s=await this.screenshot({base64:!0,path:r,element:t?.element}),i=await f(s.base64);return {type:g,snapshotFilename:a,baselinePath:o,resultPath:r,diffPath:n,base64:s.base64,image:i}}var p;globalThis.__vitest_browser__&&import('@vitest/browser/context').then(t=>{p=t,j.extend({imageSnapshot:x});});function Y(){return p?.cdp()??{}}var u=new Proxy({},{get(t,e){return t[e]??(p?.commands)[e]}}),j=new Proxy({getByAltText:getByAltText,getByRole:getByRole,getByTestId:getByTestId,getByText:getByText,getByTitle:getByTitle,getByPlaceholder:getByPlaceholderText,getByLabelText:getByLabelText},{get(t,e){return t[e]??p?.page?(p?.page)[e]:()=>{if(e==="imageSnapshot")return {type:d};console.info(`\`page.${e.toString()}\` does not exist when running in browser`);}}}),S=new Proxy({},{get(t,e){return t[e]??(p?.server)[e]}});function y(t){return !!t&&t.type===g}function I(t){if(!y(t))throw new Error("Expected subject to be an image snapshot")}var D=({width:t,height:e})=>a=>{if(a.width===t&&a.height===e)return a;let o=(n,s)=>s<=a.height&&n<=a.width,r=new ImageData(t,e,{colorSpace:a.colorSpace});for(let n=0;n<e;n++)for(let s=0;s<t;s++){let i=t*n+s<<2;if(o(s,n)){let m=a.width*n+s<<2;r.data[i]=a.data[m],r.data[i+1]=a.data[m+1],r.data[i+2]=a.data[m+2],r.data[i+3]=a.data[m+3];}else r.data[i]=0,r.data[i+1]=0,r.data[i+2]=0,r.data[i+3]=64;}return r};async function pt(t,e){let a=await t;if(a?.type===d)return l;if(!y(a)){if(a?.path&&a?.base64)return {pass:!1,actual:a,message:()=>"`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?"};if(typeof a!="object")return {pass:!1,actual:a,message:()=>`\`toMatchImageSnapshot()\` expects the subject to be an element, locator, or result of \`page.imageSnapshot()\`, but got: \`${a}\``}}I(a);let o=await A(a.baselinePath);if(!o)return await u.copyFile(a.resultPath,a.baselinePath),l;let r=await f(o),[n,s]=C(a.image,r),{pass:i,diffAmount:m,diffImage:h}=L(s,n,e);return i?l:S.config.snapshotOptions.updateSnapshot==="all"?(await P(`${a.baselinePath}`,n),l):(await P(`${a.diffPath}`,h),{pass:!1,message:()=>F`${e?.failureThreshold?e?.failureThresholdType==="percent"?`Expected image to match within ${e.failureThreshold}% but was differ by ${m}%.`:`Expected image to match within ${e.failureThreshold} pixels but was differ by ${m} pixels.`:`Expected image to match but was differ by ${e?.failureThresholdType==="percent"?`${m}%`:`${m} pixels`}.`}
1
+ import R from'dedent';import j from'pixelmatch';import {getByAltText,getByRole,getByTestId,getByText,getByTitle,getByPlaceholderText,getByLabelText}from'@storybook/test';import {join}from'pathe';var g=Symbol.for("storybook-addon-vis/imageSnapshot"),f=Symbol.for("storybook-addon-vis/imageSnapshotStub");var i={name:"",testFilepath:"",taskName:"",snapshot:{}};async function y(t){let e=i.snapshot[i.id].index,a=t?.customizeSnapshotId?`${t.customizeSnapshotId(i.id,e)}.png`:`${i.id}-${e}.png`,o=join(i.baselineDir,a);return h.existFile(o)}function u(t){return new Promise((e,a)=>{let o=new Image;o.src=`data:image/png;base64,${t}`,o.onload=()=>{let n=document.createElement("canvas");n.width=o.width,n.height=o.height;let s=n.getContext("2d");s.drawImage(o,0,0),e(s.getImageData(0,0,n.width,n.height));},o.onerror=()=>{a(new Error("Failed to load image"));};})}async function b(t){let e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").putImageData(t,0,0),new Promise(o=>{e.toBlob(n=>{let s=new FileReader;s.onload=()=>{o(s.result);},s.readAsDataURL(n);});})}async function I(t){let e=i.snapshot[i.id].index++,a=t?.customizeSnapshotId?`${t.customizeSnapshotId(i.id,e)}.png`:`${i.id}-${e}.png`,o=join(i.baselineDir,a),n=join(i.resultDir,a),s=join(i.diffDir,a),r=await this.screenshot({base64:!0,path:n,element:t?.element,timeout:t?.timeout??3e3}),m=await u(r.base64);return {type:g,snapshotFilename:a,baselinePath:o,resultPath:n,diffPath:s,base64:r.base64,image:m}}var c;globalThis.__vitest_browser__&&import('@vitest/browser/context').then(t=>{c=t,E.extend({imageSnapshot:I,hasImageSnapshot:y});});function st(){return c?.cdp()??{}}var h=new Proxy({},{get(t,e){return t[e]??(c?.commands)[e]}}),E=new Proxy({getByAltText:getByAltText,getByRole:getByRole,getByTestId:getByTestId,getByText:getByText,getByTitle:getByTitle,getByPlaceholder:getByPlaceholderText,getByLabelText:getByLabelText},{get(t,e){return t[e]??c?.page?(c?.page)[e]:()=>{if(e==="imageSnapshot")return {type:f};console.info(`\`page.${e.toString()}\` does not exist when running in browser`);}}}),w=new Proxy({},{get(t,e){return t[e]??(c?.server)[e]}});function x(t){return !!t&&t.type===g}function P(t){if(!x(t))throw new Error("Expected subject to be an image snapshot")}var D=({width:t,height:e})=>a=>{if(a.width===t&&a.height===e)return a;let o=(s,r)=>r<=a.height&&s<=a.width,n=new ImageData(t,e,{colorSpace:a.colorSpace});for(let s=0;s<e;s++)for(let r=0;r<t;r++){let m=t*s+r<<2;if(o(r,s)){let p=a.width*s+r<<2;n.data[m]=a.data[p],n.data[m+1]=a.data[p+1],n.data[m+2]=a.data[p+2],n.data[m+3]=a.data[p+3];}else n.data[m]=0,n.data[m+1]=0,n.data[m+2]=0,n.data[m+3]=64;}return n};async function xt(t,e){let a=await t;if(a?.type===f)return l;if(!x(a)){if(a?.path&&a?.base64)return {pass:!1,actual:a,message:()=>"`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?"};if(typeof a!="object")return {pass:!1,actual:a,message:()=>`\`toMatchImageSnapshot()\` expects the subject to be an element, locator, or result of \`page.imageSnapshot()\`, but got: \`${a}\``}}P(a);let o=await F(a.baselinePath);if(!o)return await h.copyFile(a.resultPath,a.baselinePath),l;let n=await u(o),[s,r]=_(a.image,n),{pass:m,diffAmount:p,diffImage:d}=U(r,s,e);return m?l:w.config.snapshotOptions.updateSnapshot==="all"?(await $(`${a.baselinePath}`,s),l):(await $(`${a.diffPath}`,d),{pass:!1,message:()=>R`Snapshot \`${i.taskName}\` mismatched
2
+
3
+ ${e?.failureThreshold?e?.failureThresholdType==="percent"?`Expected image to match within ${e.failureThreshold}% but was differ by ${p}%.`:`Expected image to match within ${e.failureThreshold} pixels but was differ by ${p} pixels.`:`Expected image to match but was differ by ${e?.failureThresholdType==="percent"?`${p}%`:`${p} pixels`}.`}
2
4
 
3
5
  Expected: '${a.baselinePath}'
4
6
  Actual: '${a.resultPath}'
5
- Difference: '${a.diffPath}'`})}var l={pass:!0,message:()=>""};function A(t){return u.readFile(t,{encoding:"base64"}).catch(()=>{})}async function P(t,e){let a=(await w(e)).split(",")[1];return u.writeFile(t,a,"base64url")}function C(t,e){if(k(t,e))return [t,e];let a=O(t,e),o=D(a);return [o(t),o(e)]}function O(t,e){let a=Math.max(t.width,e.width),o=Math.max(t.height,e.height);return {width:a,height:o}}function k(t,e){return t.width===e.width&&t.height===e.height}function L(t,e,{failureThreshold:a=0,failureThresholdType:o="pixel",diffOptions:r}={}){let{width:n,height:s}=e,i=new ImageData(n,s),m=M(e.data,t.data,i.data,n,s,r),h=_({failureThresholdType:o,width:n,height:s},m);return {pass:h<=a,diffAmount:h,diffImage:i}}function _({failureThresholdType:t,width:e,height:a},o){switch(t){case"pixel":return o;case"percent":return o/(e*a)*100;default:throw new Error(`Invalid failureThresholdType: ${t}`)}}function gt(t){return {snapshot:t}}export{Y as cdp,u as commands,gt as defineSnapshotParam,j as page,S as server,pt as toMatchImageSnapshot};//# sourceMappingURL=index.js.map
7
+ Difference: '${a.diffPath}'`})}var l={pass:!0,message:()=>""};function F(t){return h.readFile(t,{encoding:"base64"}).catch(()=>{})}async function $(t,e){let a=(await b(e)).split(",")[1];return h.writeFile(t,a,"base64url")}function _(t,e){if(L(t,e))return [t,e];let a=k(t,e),o=D(a);return [o(t),o(e)]}function k(t,e){let a=Math.max(t.width,e.width),o=Math.max(t.height,e.height);return {width:a,height:o}}function L(t,e){return t.width===e.width&&t.height===e.height}function U(t,e,{failureThreshold:a=0,failureThresholdType:o="pixel",diffOptions:n}={}){let{width:s,height:r}=e,m=new ImageData(s,r),p=j(e.data,t.data,m.data,s,r,n),d=N({failureThresholdType:o,width:s,height:r},p);return {pass:d<=a,diffAmount:d,diffImage:m}}function N({failureThresholdType:t,width:e,height:a},o){switch(t){case"pixel":return o;case"percent":return o/(e*a)*100;default:throw new Error(`Invalid failureThresholdType: ${t}`)}}function bt(t){return {snapshot:t}}export{st as cdp,h as commands,bt as defineSnapshotParam,E as page,w as server,xt as toMatchImageSnapshot};//# sourceMappingURL=index.js.map
6
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/@vitest/browser/constants.ts","../src/@vitest/browser/context.ts","../src/image_data.ts","../src/state.ts","../src/@vitest/browser/page.image_snapshot.ts","../src/@vitest/browser/image_snapshot.logic.ts","../src/image_resizer.ts","../src/expect.to_match_image_snapshot.ts","../src/param.ts"],"names":["imageSnapshotSymbol","imageSnapshotStubSymbol","toImageData","base64","resolve","reject","img","canvas","ctx","toDataURL","imageData","blob","reader","state","imageSnapshot","options","index","snapshotFilename","baselinePath","join","resultPath","diffPath","screenshot","image","m","page","cdp","commands","target","prop","getByAltText","getByRole","getByTestId","getByText","getByTitle","getByPlaceholderText","getByLabelText","server","isImageSnapshot","subject","assertImageSnapshot","createImageResizer","width","height","inArea","x","y","result","idx","old","toMatchImageSnapshot","actual","success","baseline","tryReadSnapshot","originalImage","resultImage","baselineImage","alignImagesToSameSize","pass","diffAmount","diffImage","compareImage","writeSnapshot","dedent","path","content","image1","image2","isSameSize","size","getMaxSize","resize","failureThreshold","failureThresholdType","diffOptions","pixelDiff","pixelmatch","toThresholdUnit","defineSnapshotParam","snapshot"],"mappings":"mMAAO,IAAMA,EAAsB,MAAO,CAAA,GAAA,CAAI,mCAAmC,CAAA,CAEpEC,EAA0B,MAAO,CAAA,GAAA,CAAI,uCAAuC,CCFzF,CCAO,SAASC,EAAYC,CAAgB,CAAA,CAC3C,OAAO,IAAI,OAAA,CAAmB,CAACC,CAAAA,CAASC,IAAW,CAClD,IAAMC,EAAM,IAAI,KAAA,CAChBA,EAAI,GAAM,CAAA,CAAA,sBAAA,EAAyBH,CAAM,CAEzCG,CAAAA,CAAAA,CAAAA,CAAI,OAAS,IAAM,CAClB,IAAMC,CAAS,CAAA,QAAA,CAAS,cAAc,QAAQ,CAAA,CAC9CA,CAAO,CAAA,KAAA,CAAQD,EAAI,KACnBC,CAAAA,CAAAA,CAAO,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MhB,CAAca,EAAAA,CAAAA,CACpB,UAAAb,CAAAA,CAAAA,CACA,SAAAC,CAAAA,CACD,CACD,CAEA,SAASiB,CAAAA,CACR,CAAE,oBAAA,CAAAJ,CAAsB,CAAA,KAAA,CAAAhC,CAAO,CAAA,MAAA,CAAAC,CAAO,CAAA,CACtCiC,CACS,CAAA,CACT,OAAQF,CAAAA,EACP,IAAK,OACJ,CAAA,OAAOE,CACR,CAAA,IAAK,SACJ,CAAA,OAAQA,CAAalC,EAAAA,CAAAA,CAAQC,CAAW,CAAA,CAAA,GAAA,CACzC,QACC,MAAM,IAAI,KAAA,CAAM,CAAiC+B,8BAAAA,EAAAA,CAAoB,CAAE,CAAA,CACzE,CACD,CCtIO,SAASK,EAAAA,CAAoBC,CAAqC,CAAA,CACxE,OAAO,CAAE,QAAAA,CAAAA,CAAS,CACnB","file":"index.js","sourcesContent":["export const imageSnapshotSymbol = Symbol.for('storybook-addon-vis/imageSnapshot')\n\nexport const imageSnapshotStubSymbol = Symbol.for('storybook-addon-vis/imageSnapshotStub')\n","import {\n\tgetByAltText,\n\tgetByLabelText,\n\tgetByPlaceholderText,\n\tgetByRole,\n\tgetByTestId,\n\tgetByText,\n\tgetByTitle,\n} from '@storybook/test'\nimport type { BrowserCommands, BrowserPage, CDPSession, Platform } from '@vitest/browser/context'\nimport type { SerializedConfig } from 'vitest'\nimport { imageSnapshotStubSymbol } from './constants'\nimport { imageSnapshot } from './page.image_snapshot'\n\nlet ctx: Awaited<typeof import('@vitest/browser/context')>\n\nif ((globalThis as any).__vitest_browser__) {\n\timport('@vitest/browser/context').then((m) => {\n\t\tctx = m\n\t\tpage.extend({ imageSnapshot })\n\t})\n}\n\n// TODO: stub the functions within the `CDPSession`\n// when we better understands the use cases\nexport function cdp(): CDPSession {\n\treturn ctx?.cdp() ?? ({} as any)\n}\n\nexport const commands = new Proxy<BrowserCommands>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.commands as any)[prop]\n\t},\n})\n\nexport const page = new Proxy<BrowserPage>(\n\t{\n\t\tgetByAltText,\n\t\tgetByRole,\n\t\tgetByTestId,\n\t\tgetByText,\n\t\tgetByTitle,\n\t\tgetByPlaceholder: getByPlaceholderText,\n\t\tgetByLabelText,\n\t} as any,\n\t{\n\t\tget(target, prop) {\n\t\t\treturn ((target as any)[prop] ?? ctx?.page)\n\t\t\t\t? (ctx?.page as any)[prop]\n\t\t\t\t: () => {\n\t\t\t\t\t\tif (prop === 'imageSnapshot') {\n\t\t\t\t\t\t\treturn { type: imageSnapshotStubSymbol }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.info(`\\`page.${prop.toString()}\\` does not exist when running in browser`)\n\t\t\t\t\t}\n\t\t},\n\t},\n)\n\nexport const server = new Proxy<{\n\t/**\n\t * Platform the Vitest server is running on.\n\t * The same as calling `process.platform` on the server.\n\t */\n\tplatform: Platform\n\t/**\n\t * Runtime version of the Vitest server.\n\t * The same as calling `process.version` on the server.\n\t */\n\tversion: string\n\t/**\n\t * Name of the browser provider.\n\t */\n\tprovider: string\n\t/**\n\t * Name of the current browser.\n\t */\n\tbrowser: string\n\t/**\n\t * Available commands for the browser.\n\t * @see {@link https://vitest.dev/guide/browser/commands}\n\t */\n\tcommands: BrowserCommands\n\t/**\n\t * Serialized test config.\n\t */\n\tconfig: SerializedConfig\n}>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.server as any)[prop]\n\t},\n})\n","export function toImageData(base64: string) {\n\treturn new Promise<ImageData>((resolve, reject) => {\n\t\tconst img = new Image()\n\t\timg.src = `data:image/png;base64,${base64}`\n\n\t\timg.onload = () => {\n\t\t\tconst canvas = document.createElement('canvas')\n\t\t\tcanvas.width = img.width\n\t\t\tcanvas.height = img.height\n\t\t\tconst ctx = canvas.getContext('2d')!\n\t\t\tctx.drawImage(img, 0, 0)\n\t\t\tresolve(ctx.getImageData(0, 0, canvas.width, canvas.height))\n\t\t}\n\n\t\timg.onerror = () => {\n\t\t\treject(new Error('Failed to load image'))\n\t\t}\n\t})\n}\n\nexport async function toDataURL(imageData: ImageData) {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = imageData.width\n\tcanvas.height = imageData.height\n\tconst ctx = canvas.getContext('2d')!\n\tctx.putImageData(imageData, 0, 0)\n\treturn new Promise<string>((resolve) => {\n\t\tcanvas.toBlob((blob) => {\n\t\t\tconst reader = new FileReader()\n\t\t\treader.onload = () => {\n\t\t\t\tresolve(reader.result as string)\n\t\t\t}\n\t\t\treader.readAsDataURL(blob!)\n\t\t})\n\t})\n}\n","export const state = {\n\tname: '',\n\ttestFilepath: '',\n\ttaskName: '',\n\tsnapshot: {},\n} as {\n\tid: string\n\tname: string\n\ttestFilepath: string\n\ttestFilename: string\n\tprojectDir: string\n\tbaselineDir: string\n\tresultDir: string\n\tdiffDir: string\n\ttaskName: string\n\tsnapshot: Record<string, { index: number }>\n}\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { toImageData } from '../../image_data.js'\nimport { state } from '../../state.js'\nimport { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot, ImageSnapshotOptions } from './types.js'\n\nexport async function imageSnapshot(\n\tthis: BrowserPage,\n\toptions?: ImageSnapshotOptions | undefined,\n): Promise<ImageSnapshot> {\n\tconst index = state.snapshot[state.id]!.index++\n\tconst snapshotFilename = options?.customizeFilename\n\t\t? `${options.customizeFilename(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\tconst resultPath = join(state.resultDir, snapshotFilename)\n\tconst diffPath = join(state.diffDir, snapshotFilename)\n\tconst screenshot = await this.screenshot({\n\t\tbase64: true,\n\t\tpath: resultPath,\n\t\telement: options?.element,\n\t})\n\tconst image = await toImageData(screenshot.base64)\n\n\treturn {\n\t\ttype: imageSnapshotSymbol,\n\t\tsnapshotFilename,\n\t\tbaselinePath,\n\t\tresultPath,\n\t\tdiffPath,\n\t\tbase64: screenshot.base64,\n\t\timage,\n\t}\n}\n","import { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot } from './types.js'\n\nexport function isImageSnapshot(subject: any): subject is ImageSnapshot {\n\treturn !!subject && subject.type === imageSnapshotSymbol\n}\n\nexport function assertImageSnapshot(subject: any): asserts subject is ImageSnapshot {\n\tif (!isImageSnapshot(subject)) {\n\t\tthrow new Error('Expected subject to be an image snapshot')\n\t}\n}\n\nexport function toSnapshotId(taskName: string) {\n\treturn `${taskName.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`\n}\n","export const createImageResizer =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tfor (let x = 0; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (inArea(x, y)) {\n\t\t\t\t\tconst old = (image.width * y + x) << 2\n\t\t\t\t\tresult.data[idx] = image.data[old]\n\t\t\t\t\tresult.data[idx + 1] = image.data[old + 1]\n\t\t\t\t\tresult.data[idx + 2] = image.data[old + 2]\n\t\t\t\t\tresult.data[idx + 3] = image.data[old + 3]\n\t\t\t\t} else {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n// slower\nexport const createImageResizer2 =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tconst copyBytes = image.width * 4\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tresult.data.set(image.data.slice(y * image.width, copyBytes), y * width * 4)\n\t\t\tfor (let x = image.width; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (!inArea(x, y)) {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n","import type { AsyncExpectationResult } from '@vitest/expect'\nimport dedent from 'dedent'\nimport pixelmatch from 'pixelmatch'\nimport { imageSnapshotStubSymbol } from './@vitest/browser/constants.js'\nimport { commands, server } from './@vitest/browser/context.js'\nimport { assertImageSnapshot, isImageSnapshot } from './@vitest/browser/image_snapshot.logic.js'\nimport type { MatchImageSnapshotOptions } from './@vitest/browser/types.js'\nimport { toDataURL, toImageData } from './image_data.js'\nimport { createImageResizer } from './image_resizer.js'\n\nexport async function toMatchImageSnapshot(\n\tactual: any,\n\toptions?: MatchImageSnapshotOptions | undefined,\n): AsyncExpectationResult {\n\tconst subject = await actual\n\tif (subject?.type === imageSnapshotStubSymbol) {\n\t\treturn success\n\t}\n\tif (!isImageSnapshot(subject)) {\n\t\tif (subject?.path && subject?.base64) {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t'`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?',\n\t\t\t}\n\t\t}\n\n\t\tif (typeof subject !== 'object') {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t`\\`toMatchImageSnapshot()\\` expects the subject to be an element, locator, or result of \\`page.imageSnapshot()\\`, but got: \\`${subject}\\``,\n\t\t\t}\n\t\t}\n\t\t// subject = await page.imageSnapshot({ element: actual })\n\t}\n\tassertImageSnapshot(subject)\n\tconst baseline = await tryReadSnapshot(subject.baselinePath)\n\tif (!baseline) {\n\t\tawait commands.copyFile(subject.resultPath, subject.baselinePath)\n\t\treturn success\n\t}\n\n\tconst originalImage = await toImageData(baseline)\n\tconst [resultImage, baselineImage] = alignImagesToSameSize(subject.image, originalImage)\n\n\tconst { pass, diffAmount, diffImage } = compareImage(baselineImage, resultImage, options)\n\tif (!pass) {\n\t\tif (server.config.snapshotOptions.updateSnapshot === 'all') {\n\t\t\tawait writeSnapshot(`${subject.baselinePath}`, resultImage)\n\t\t\treturn success\n\t\t}\n\t\tawait writeSnapshot(`${subject.diffPath}`, diffImage)\n\t\treturn {\n\t\t\tpass: false,\n\t\t\tmessage: () =>\n\t\t\t\tdedent`${\n\t\t\t\t\toptions?.failureThreshold\n\t\t\t\t\t\t? options?.failureThresholdType === 'percent'\n\t\t\t\t\t\t\t? `Expected image to match within ${options.failureThreshold}% but was differ by ${diffAmount}%.`\n\t\t\t\t\t\t\t: `Expected image to match within ${options.failureThreshold} pixels but was differ by ${diffAmount} pixels.`\n\t\t\t\t\t\t: `Expected image to match but was differ by ${options?.failureThresholdType === 'percent' ? `${diffAmount}%` : `${diffAmount} pixels`}.`\n\t\t\t\t}\n\n\t\t\tExpected: '${subject.baselinePath}'\n\t\t\tActual: '${subject.resultPath}'\n\t\t\tDifference: '${subject.diffPath}'`,\n\t\t}\n\t}\n\treturn success\n}\n\nconst success = {\n\tpass: true,\n\tmessage: () => '',\n}\n\nfunction tryReadSnapshot(path: string): Promise<string | undefined> {\n\treturn commands.readFile(path, { encoding: 'base64' }).catch(() => undefined)\n}\nasync function writeSnapshot(path: string, image: ImageData) {\n\tconst content = (await toDataURL(image)).split(',')[1]!\n\treturn commands.writeFile(path, content, 'base64url')\n}\n\nfunction alignImagesToSameSize(image1: ImageData, image2: ImageData): [image1: ImageData, image2: ImageData] {\n\tif (isSameSize(image1, image2)) {\n\t\treturn [image1, image2]\n\t}\n\tconst size = getMaxSize(image1, image2)\n\tconst resize = createImageResizer(size)\n\treturn [resize(image1), resize(image2)]\n}\n\nfunction getMaxSize(image1: ImageData, image2: ImageData) {\n\tconst width = Math.max(image1.width, image2.width)\n\tconst height = Math.max(image1.height, image2.height)\n\treturn { width, height }\n}\n\nfunction isSameSize(image1: ImageData, image2: ImageData) {\n\treturn image1.width === image2.width && image1.height === image2.height\n}\n\nfunction compareImage(\n\tbaselineImage: ImageData,\n\tresultImage: ImageData,\n\t{ failureThreshold = 0, failureThresholdType = 'pixel', diffOptions }: MatchImageSnapshotOptions = {},\n) {\n\tconst { width, height } = resultImage\n\tconst diffImage = new ImageData(width, height)\n\n\tconst pixelDiff = pixelmatch(resultImage.data, baselineImage.data, diffImage.data, width, height, diffOptions)\n\tconst diffAmount = toThresholdUnit({ failureThresholdType, width, height }, pixelDiff)\n\n\treturn {\n\t\tpass: diffAmount <= failureThreshold,\n\t\tdiffAmount,\n\t\tdiffImage,\n\t}\n}\n\nfunction toThresholdUnit(\n\t{ failureThresholdType, width, height }: { failureThresholdType: 'pixel' | 'percent'; width: number; height: number },\n\tpixelDiff: number,\n): number {\n\tswitch (failureThresholdType) {\n\t\tcase 'pixel':\n\t\t\treturn pixelDiff\n\t\tcase 'percent':\n\t\t\treturn (pixelDiff / (width * height)) * 100\n\t\tdefault:\n\t\t\tthrow new Error(`Invalid failureThresholdType: ${failureThresholdType}`)\n\t}\n}\n","import type { MatchImageSnapshotOptions } from './@vitest/browser/types'\n\nexport function defineSnapshotParam(snapshot: MatchImageSnapshotOptions) {\n\treturn { snapshot }\n}\n"]}
1
+ {"version":3,"sources":["../src/@vitest/browser/constants.ts","../src/state.ts","../src/@vitest/browser/page.has_image_snapshot.ts","../src/image_data.ts","../src/@vitest/browser/page.image_snapshot.ts","../src/@vitest/browser/context.ts","../src/@vitest/browser/image_snapshot.logic.ts","../src/image_resizer.ts","../src/expect.to_match_image_snapshot.ts","../src/param.ts"],"names":["imageSnapshotSymbol","imageSnapshotStubSymbol","state","hasImageSnapshot","options","index","snapshotFilename","baselinePath","join","commands","toImageData","base64","resolve","reject","img","canvas","ctx","toDataURL","imageData","blob","reader","imageSnapshot","resultPath","diffPath","screenshot","image","m","page","cdp","target","prop","getByAltText","getByRole","getByTestId","getByText","getByTitle","getByPlaceholderText","getByLabelText","server","isImageSnapshot","subject","assertImageSnapshot","createImageResizer","width","height","inArea","x","y","result","idx","old","toMatchImageSnapshot","actual","success","baseline","tryReadSnapshot","originalImage","resultImage","baselineImage","alignImagesToSameSize","pass","diffAmount","diffImage","compareImage","writeSnapshot","dedent","path","content","image1","image2","isSameSize","size","getMaxSize","resize","failureThreshold","failureThresholdType","diffOptions","pixelDiff","pixelmatch","toThresholdUnit","defineSnapshotParam","snapshot"],"mappings":"mMAAO,IAAMA,EAAsB,MAAO,CAAA,GAAA,CAAI,mCAAmC,CAEpEC,CAAAA,CAAAA,CAA0B,OAAO,GAAI,CAAA,uCAAuC,ECFlF,IAAMC,CAAQ,CAAA,CACpB,KAAM,EACN,CAAA,YAAA,CAAc,GACd,QAAU,CAAA,EAAA,CACV,QAAU,CAAA,EACX,CCQA,CAAA,eAAsBC,EAAoCC,CAAkD,CAAA,CAC3G,IAAMC,CAAQH,CAAAA,CAAAA,CAAM,SAASA,CAAM,CAAA,EAAE,EAAG,KAClCI,CAAAA,CAAAA,CAAmBF,GAAS,mBAC/B,CAAA,CAAA,EAAGA,EAAQ,mBAAoBF,CAAAA,CAAAA,CAAM,GAAIG,CAAK,CAAC,OAC/C,CAAGH,EAAAA,CAAAA,CAAM,EAAE,CAAIG,CAAAA,EAAAA,CAAK,OACjBE,CAAeC,CAAAA,IAAAA,CAAKN,EAAM,WAAaI,CAAAA,CAAgB,EAC7D,OAAOG,CAAAA,CAAS,UAAUF,CAAY,CACvC,CCpBO,SAASG,CAAYC,CAAAA,CAAAA,CAAgB,CAC3C,OAAO,IAAI,QAAmB,CAACC,CAA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AAAA,CAAAA,CAAWrB,CAAY,CAAA,IAAA,CAAMC,CAAc,CAAA,IAAA,CAAMI,CAAU,CAAA,IAAA,CAAMnB,CAAOC,CAAAA,CAAAA,CAAQgC,CAAW,CAAA,CACvGf,CAAakB,CAAAA,CAAAA,CAAgB,CAAE,oBAAA,CAAAJ,CAAsB,CAAA,KAAA,CAAAhC,EAAO,MAAAC,CAAAA,CAAO,CAAGiC,CAAAA,CAAS,CAErF,CAAA,OAAO,CACN,IAAA,CAAMhB,CAAca,EAAAA,CAAAA,CACpB,UAAAb,CAAAA,CAAAA,CACA,SAAAC,CAAAA,CACD,CACD,CAEA,SAASiB,CAAAA,CACR,CAAE,oBAAA,CAAAJ,CAAsB,CAAA,KAAA,CAAAhC,CAAO,CAAA,MAAA,CAAAC,CAAO,CAAA,CACtCiC,CACS,CAAA,CACT,OAAQF,CAAAA,EACP,IAAK,OACJ,CAAA,OAAOE,CACR,CAAA,IAAK,SACJ,CAAA,OAAQA,CAAalC,EAAAA,CAAAA,CAAQC,CAAW,CAAA,CAAA,GAAA,CACzC,QACC,MAAM,IAAI,KAAA,CAAM,CAAiC+B,8BAAAA,EAAAA,CAAoB,CAAE,CAAA,CACzE,CACD,CC1JO,SAASK,EAAAA,CAAoBC,CAAqC,CAAA,CACxE,OAAO,CAAE,QAAAA,CAAAA,CAAS,CACnB","file":"index.js","sourcesContent":["export const imageSnapshotSymbol = Symbol.for('storybook-addon-vis/imageSnapshot')\n\nexport const imageSnapshotStubSymbol = Symbol.for('storybook-addon-vis/imageSnapshotStub')\n","export const state = {\n\tname: '',\n\ttestFilepath: '',\n\ttaskName: '',\n\tsnapshot: {},\n} as {\n\tid: string\n\tname: string\n\ttestFilepath: string\n\ttestFilename: string\n\tprojectDir: string\n\tbaselineDir: string\n\tresultDir: string\n\tdiffDir: string\n\ttaskName: string\n\tsnapshot: Record<string, { index: number }>\n}\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { state } from '../../state'\nimport { commands } from './context'\nimport type { CustomizeSnapshotIdOptions } from './types'\n\nexport interface HasImageSnapshotAction {\n\thasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined): Promise<boolean>\n}\n\n/**\n * Check if the snapshot image exists.\n */\nexport async function hasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined) {\n\tconst index = state.snapshot[state.id]!.index\n\tconst snapshotFilename = options?.customizeSnapshotId\n\t\t? `${options.customizeSnapshotId(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\treturn commands.existFile(baselinePath)\n}\n","export function toImageData(base64: string) {\n\treturn new Promise<ImageData>((resolve, reject) => {\n\t\tconst img = new Image()\n\t\timg.src = `data:image/png;base64,${base64}`\n\n\t\timg.onload = () => {\n\t\t\tconst canvas = document.createElement('canvas')\n\t\t\tcanvas.width = img.width\n\t\t\tcanvas.height = img.height\n\t\t\tconst ctx = canvas.getContext('2d')!\n\t\t\tctx.drawImage(img, 0, 0)\n\t\t\tresolve(ctx.getImageData(0, 0, canvas.width, canvas.height))\n\t\t}\n\n\t\timg.onerror = () => {\n\t\t\treject(new Error('Failed to load image'))\n\t\t}\n\t})\n}\n\nexport async function toDataURL(imageData: ImageData) {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = imageData.width\n\tcanvas.height = imageData.height\n\tconst ctx = canvas.getContext('2d')!\n\tctx.putImageData(imageData, 0, 0)\n\treturn new Promise<string>((resolve) => {\n\t\tcanvas.toBlob((blob) => {\n\t\t\tconst reader = new FileReader()\n\t\t\treader.onload = () => {\n\t\t\t\tresolve(reader.result as string)\n\t\t\t}\n\t\t\treader.readAsDataURL(blob!)\n\t\t})\n\t})\n}\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { toImageData } from '../../image_data.js'\nimport { state } from '../../state.js'\nimport { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot, ImageSnapshotOptions } from './types.js'\n\nexport interface ImageSnapshotAction {\n\timageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions | undefined): Promise<ImageSnapshot>\n}\n\nexport async function imageSnapshot(\n\tthis: BrowserPage,\n\toptions?: ImageSnapshotOptions | undefined,\n): Promise<ImageSnapshot> {\n\tconst index = state.snapshot[state.id]!.index++\n\tconst snapshotFilename = options?.customizeSnapshotId\n\t\t? `${options.customizeSnapshotId(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\tconst resultPath = join(state.resultDir, snapshotFilename)\n\tconst diffPath = join(state.diffDir, snapshotFilename)\n\tconst screenshot = await this.screenshot({\n\t\tbase64: true,\n\t\tpath: resultPath,\n\t\telement: options?.element,\n\t\ttimeout: options?.timeout ?? 3000,\n\t})\n\tconst image = await toImageData(screenshot.base64)\n\n\treturn {\n\t\ttype: imageSnapshotSymbol,\n\t\tsnapshotFilename,\n\t\tbaselinePath,\n\t\tresultPath,\n\t\tdiffPath,\n\t\tbase64: screenshot.base64,\n\t\timage,\n\t}\n}\n","import {\n\tgetByAltText,\n\tgetByLabelText,\n\tgetByPlaceholderText,\n\tgetByRole,\n\tgetByTestId,\n\tgetByText,\n\tgetByTitle,\n} from '@storybook/test'\nimport type { BrowserCommands, BrowserPage, CDPSession, Platform } from '@vitest/browser/context'\nimport type { SerializedConfig } from 'vitest'\nimport { imageSnapshotStubSymbol } from './constants'\nimport { hasImageSnapshot } from './page.has_image_snapshot'\nimport { imageSnapshot } from './page.image_snapshot'\n\nlet ctx: Awaited<typeof import('@vitest/browser/context')>\n\nif ((globalThis as any).__vitest_browser__) {\n\timport('@vitest/browser/context').then((m) => {\n\t\tctx = m\n\t\tpage.extend({ imageSnapshot, hasImageSnapshot })\n\t})\n}\n\n// TODO: stub the functions within the `CDPSession`\n// when we better understands the use cases\nexport function cdp(): CDPSession {\n\treturn ctx?.cdp() ?? ({} as any)\n}\n\nexport const commands = new Proxy<BrowserCommands>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.commands as any)[prop]\n\t},\n})\n\nexport const page = new Proxy<BrowserPage>(\n\t{\n\t\tgetByAltText,\n\t\tgetByRole,\n\t\tgetByTestId,\n\t\tgetByText,\n\t\tgetByTitle,\n\t\tgetByPlaceholder: getByPlaceholderText,\n\t\tgetByLabelText,\n\t} as any,\n\t{\n\t\tget(target, prop) {\n\t\t\treturn ((target as any)[prop] ?? ctx?.page)\n\t\t\t\t? (ctx?.page as any)[prop]\n\t\t\t\t: () => {\n\t\t\t\t\t\tif (prop === 'imageSnapshot') {\n\t\t\t\t\t\t\treturn { type: imageSnapshotStubSymbol }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.info(`\\`page.${prop.toString()}\\` does not exist when running in browser`)\n\t\t\t\t\t}\n\t\t},\n\t},\n)\n\nexport const server = new Proxy<{\n\t/**\n\t * Platform the Vitest server is running on.\n\t * The same as calling `process.platform` on the server.\n\t */\n\tplatform: Platform\n\t/**\n\t * Runtime version of the Vitest server.\n\t * The same as calling `process.version` on the server.\n\t */\n\tversion: string\n\t/**\n\t * Name of the browser provider.\n\t */\n\tprovider: string\n\t/**\n\t * Name of the current browser.\n\t */\n\tbrowser: string\n\t/**\n\t * Available commands for the browser.\n\t * @see {@link https://vitest.dev/guide/browser/commands}\n\t */\n\tcommands: BrowserCommands\n\t/**\n\t * Serialized test config.\n\t */\n\tconfig: SerializedConfig\n}>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.server as any)[prop]\n\t},\n})\n","import { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot } from './types.js'\n\nexport function isImageSnapshot(subject: any): subject is ImageSnapshot {\n\treturn !!subject && subject.type === imageSnapshotSymbol\n}\n\nexport function assertImageSnapshot(subject: any): asserts subject is ImageSnapshot {\n\tif (!isImageSnapshot(subject)) {\n\t\tthrow new Error('Expected subject to be an image snapshot')\n\t}\n}\n\nexport function toSnapshotId(taskName: string) {\n\treturn `${taskName.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`\n}\n","export const createImageResizer =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tfor (let x = 0; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (inArea(x, y)) {\n\t\t\t\t\tconst old = (image.width * y + x) << 2\n\t\t\t\t\tresult.data[idx] = image.data[old]\n\t\t\t\t\tresult.data[idx + 1] = image.data[old + 1]\n\t\t\t\t\tresult.data[idx + 2] = image.data[old + 2]\n\t\t\t\t\tresult.data[idx + 3] = image.data[old + 3]\n\t\t\t\t} else {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n// slower\nexport const createImageResizer2 =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tconst copyBytes = image.width * 4\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tresult.data.set(image.data.slice(y * image.width, copyBytes), y * width * 4)\n\t\t\tfor (let x = image.width; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (!inArea(x, y)) {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n","import type { AsyncExpectationResult } from '@vitest/expect'\nimport dedent from 'dedent'\nimport pixelmatch, { type PixelmatchOptions } from 'pixelmatch'\nimport { imageSnapshotStubSymbol } from './@vitest/browser/constants.js'\nimport { commands, server } from './@vitest/browser/context.js'\nimport { assertImageSnapshot, isImageSnapshot } from './@vitest/browser/image_snapshot.logic.js'\nimport { toDataURL, toImageData } from './image_data.js'\nimport { createImageResizer } from './image_resizer.js'\nimport { state } from './state.js'\n\nexport interface ImageSnapshotMatcher {\n\ttoMatchImageSnapshot(options?: MatchImageSnapshotOptions): Promise<void>\n}\n\nexport type MatchImageSnapshotOptions = {\n\t/**\n\t * Custom options passed to 'pixelmatch'\n\t */\n\tdiffOptions?: PixelmatchOptions | undefined\n\t/**\n\t * Failure threshold should measure in `pixel` or `percent`.\n\t *\n\t * Default is `pixel`.\n\t */\n\tfailureThresholdType?: 'pixel' | 'percent' | undefined\n\tfailureThreshold?: number | undefined\n}\n\nexport async function toMatchImageSnapshot(\n\tactual: any,\n\toptions?: MatchImageSnapshotOptions | undefined,\n): AsyncExpectationResult {\n\tconst subject = await actual\n\tif (subject?.type === imageSnapshotStubSymbol) {\n\t\treturn success\n\t}\n\tif (!isImageSnapshot(subject)) {\n\t\tif (subject?.path && subject?.base64) {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t'`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?',\n\t\t\t}\n\t\t}\n\n\t\tif (typeof subject !== 'object') {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t`\\`toMatchImageSnapshot()\\` expects the subject to be an element, locator, or result of \\`page.imageSnapshot()\\`, but got: \\`${subject}\\``,\n\t\t\t}\n\t\t}\n\t\t// subject = await page.imageSnapshot({ element: actual })\n\t}\n\tassertImageSnapshot(subject)\n\tconst baseline = await tryReadSnapshot(subject.baselinePath)\n\tif (!baseline) {\n\t\tawait commands.copyFile(subject.resultPath, subject.baselinePath)\n\t\treturn success\n\t}\n\n\tconst originalImage = await toImageData(baseline)\n\tconst [resultImage, baselineImage] = alignImagesToSameSize(subject.image, originalImage)\n\n\tconst { pass, diffAmount, diffImage } = compareImage(baselineImage, resultImage, options)\n\tif (!pass) {\n\t\tif (server.config.snapshotOptions.updateSnapshot === 'all') {\n\t\t\tawait writeSnapshot(`${subject.baselinePath}`, resultImage)\n\t\t\treturn success\n\t\t}\n\t\tawait writeSnapshot(`${subject.diffPath}`, diffImage)\n\t\treturn {\n\t\t\tpass: false,\n\t\t\tmessage: () =>\n\t\t\t\tdedent`Snapshot \\`${state.taskName}\\` mismatched\n\n\t\t\t${\n\t\t\t\toptions?.failureThreshold\n\t\t\t\t\t? options?.failureThresholdType === 'percent'\n\t\t\t\t\t\t? `Expected image to match within ${options.failureThreshold}% but was differ by ${diffAmount}%.`\n\t\t\t\t\t\t: `Expected image to match within ${options.failureThreshold} pixels but was differ by ${diffAmount} pixels.`\n\t\t\t\t\t: `Expected image to match but was differ by ${options?.failureThresholdType === 'percent' ? `${diffAmount}%` : `${diffAmount} pixels`}.`\n\t\t\t}\n\n\t\t\tExpected: '${subject.baselinePath}'\n\t\t\tActual: '${subject.resultPath}'\n\t\t\tDifference: '${subject.diffPath}'`,\n\t\t}\n\t}\n\treturn success\n}\n\nconst success = {\n\tpass: true,\n\tmessage: () => '',\n}\n\nfunction tryReadSnapshot(path: string): Promise<string | undefined> {\n\treturn commands.readFile(path, { encoding: 'base64' }).catch(() => undefined)\n}\nasync function writeSnapshot(path: string, image: ImageData) {\n\tconst content = (await toDataURL(image)).split(',')[1]!\n\treturn commands.writeFile(path, content, 'base64url')\n}\n\nfunction alignImagesToSameSize(image1: ImageData, image2: ImageData): [image1: ImageData, image2: ImageData] {\n\tif (isSameSize(image1, image2)) {\n\t\treturn [image1, image2]\n\t}\n\tconst size = getMaxSize(image1, image2)\n\tconst resize = createImageResizer(size)\n\treturn [resize(image1), resize(image2)]\n}\n\nfunction getMaxSize(image1: ImageData, image2: ImageData) {\n\tconst width = Math.max(image1.width, image2.width)\n\tconst height = Math.max(image1.height, image2.height)\n\treturn { width, height }\n}\n\nfunction isSameSize(image1: ImageData, image2: ImageData) {\n\treturn image1.width === image2.width && image1.height === image2.height\n}\n\nfunction compareImage(\n\tbaselineImage: ImageData,\n\tresultImage: ImageData,\n\t{ failureThreshold = 0, failureThresholdType = 'pixel', diffOptions }: MatchImageSnapshotOptions = {},\n) {\n\tconst { width, height } = resultImage\n\tconst diffImage = new ImageData(width, height)\n\n\tconst pixelDiff = pixelmatch(resultImage.data, baselineImage.data, diffImage.data, width, height, diffOptions)\n\tconst diffAmount = toThresholdUnit({ failureThresholdType, width, height }, pixelDiff)\n\n\treturn {\n\t\tpass: diffAmount <= failureThreshold,\n\t\tdiffAmount,\n\t\tdiffImage,\n\t}\n}\n\nfunction toThresholdUnit(\n\t{ failureThresholdType, width, height }: { failureThresholdType: 'pixel' | 'percent'; width: number; height: number },\n\tpixelDiff: number,\n): number {\n\tswitch (failureThresholdType) {\n\t\tcase 'pixel':\n\t\t\treturn pixelDiff\n\t\tcase 'percent':\n\t\t\treturn (pixelDiff / (width * height)) * 100\n\t\tdefault:\n\t\t\tthrow new Error(`Invalid failureThresholdType: ${failureThresholdType}`)\n\t}\n}\n","import type { MatchImageSnapshotOptions } from './expect.to_match_image_snapshot'\n\nexport function defineSnapshotParam(snapshot: MatchImageSnapshotOptions) {\n\treturn { snapshot }\n}\n"]}
@@ -1,15 +1,21 @@
1
1
  import * as vitest_node from 'vitest/node';
2
+ import { BrowserPage } from '@vitest/browser/context';
2
3
  import { PixelmatchOptions } from 'pixelmatch';
3
4
 
4
- type ImageSnapshotOptions = {
5
+ interface ImageSnapshotOptions extends CustomizeSnapshotIdOptions {
6
+ element?: Element;
7
+ timeout?: number | undefined;
8
+ }
9
+ type CustomizeSnapshotIdOptions = {
5
10
  /**
6
- * Customize the filename of the snapshot.
11
+ * Customize the snapshot id. This is used as the filename of the snapshot:
12
+ *
13
+ * `${snapshotId}.png`
7
14
  *
8
15
  * @param id The id of the snapshot.
9
16
  * @param index The index of the snapshot.
10
17
  */
11
- customizeFilename?: (id: string, index: number) => string;
12
- element?: Element;
18
+ customizeSnapshotId?: (id: string, index: number) => string;
13
19
  };
14
20
  type ImageSnapshot = {
15
21
  type: symbol;
@@ -20,6 +26,18 @@ type ImageSnapshot = {
20
26
  base64: string;
21
27
  image: ImageData;
22
28
  };
29
+
30
+ interface HasImageSnapshotAction {
31
+ hasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined): Promise<boolean>;
32
+ }
33
+
34
+ interface ImageSnapshotAction {
35
+ imageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions | undefined): Promise<ImageSnapshot>;
36
+ }
37
+
38
+ interface ImageSnapshotMatcher {
39
+ toMatchImageSnapshot(options?: MatchImageSnapshotOptions): Promise<void>;
40
+ }
23
41
  type MatchImageSnapshotOptions = {
24
42
  /**
25
43
  * Custom options passed to 'pixelmatch'
@@ -34,27 +52,44 @@ type MatchImageSnapshotOptions = {
34
52
  failureThreshold?: number | undefined;
35
53
  };
36
54
 
55
+ interface CopyFileCommand {
56
+ copyFile(src: string, dest: string): Promise<void>;
57
+ }
58
+
59
+ interface ExistDirCommand {
60
+ existDir: (path: string) => Promise<boolean>;
61
+ }
62
+
63
+ interface ExistFileCommand {
64
+ existFile: (path: string) => Promise<boolean>;
65
+ }
66
+
67
+ interface GetSnapshotPlatformCommand {
68
+ /**
69
+ * Get the platform id of the snapshot `{platform}[-ci]`.
70
+ *
71
+ * This is useful to control where the snapshot is stored.
72
+ */
73
+ getSnapshotPlatform: () => Promise<string>;
74
+ }
75
+
76
+ interface IsCICommand {
77
+ isCI: () => Promise<boolean>;
78
+ }
79
+
80
+ interface RmDirCommand {
81
+ rmDir: (path: string) => Promise<void>;
82
+ }
83
+
37
84
  declare module '@vitest/browser/context' {
38
- interface BrowserPage {
39
- imageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions): Promise<ImageSnapshot>;
85
+ interface BrowserPage extends ImageSnapshotAction, HasImageSnapshotAction {
40
86
  }
41
- interface BrowserCommands {
42
- existDir: (path: string) => Promise<boolean>;
43
- copyFile: (src: string, dest: string) => Promise<void>;
44
- rmDir: (path: string) => Promise<void>;
45
- isCI: () => Promise<boolean>;
46
- /**
47
- * Get the platform id of the snapshot `{platform}[-ci]`.
48
- *
49
- * This is useful to control where the snapshot is stored.
50
- */
51
- getSnapshotPlatform: () => Promise<string>;
87
+ interface BrowserCommands extends CopyFileCommand, ExistDirCommand, GetSnapshotPlatformCommand, RmDirCommand, IsCICommand, ExistFileCommand {
52
88
  }
53
89
  }
54
90
  declare global {
55
91
  namespace jest {
56
- interface Matchers<R, T> {
57
- toMatchImageSnapshot(options?: MatchImageSnapshotOptions): void;
92
+ interface Matchers<R, T> extends ImageSnapshotMatcher {
58
93
  }
59
94
  }
60
95
  }
@@ -67,10 +102,11 @@ declare function storybookVis(): {
67
102
  name: string;
68
103
  commands: {
69
104
  existDir: vitest_node.BrowserCommand<[path: string]>;
105
+ existFile: vitest_node.BrowserCommand<[path: string]>;
70
106
  copyFile: vitest_node.BrowserCommand<[src: string, dest: string]>;
71
107
  rmDir: vitest_node.BrowserCommand<[path: string]>;
72
108
  isCI: () => Promise<boolean>;
73
- getSnapshotPlatform: () => Promise<string>;
109
+ getSnapshotPlatform: () => Promise<NodeJS.Platform | "local">;
74
110
  };
75
111
  };
76
112
  };
@@ -1,2 +1,2 @@
1
- import {copyFile,stat}from'node:fs/promises';import {mkdirp}from'mkdirp';import {join,dirname}from'pathe';import u from'is-ci';import {rimraf}from'rimraf';var s=async({testPath:o,provider:r},t,i)=>{if(r.name==="playwright"){let e=join(dirname(o),i),d=dirname(e);return await mkdirp(d),copyFile(join(dirname(o),t),e)}throw new Error(`provider ${r.name} is not supported`)};var p=async({testPath:o,provider:r},t)=>{if(r.name==="playwright")return stat(join(dirname(o),t)).then(i=>i.isDirectory()).catch(()=>!1);throw new Error(`provider ${r.name} is not supported`)};var a=async()=>`${u?process.platform:"local"}`;var f=async()=>u;var c=async({testPath:o,provider:r},t)=>{if(r.name==="playwright")return rimraf(join(dirname(o),t));throw new Error(`provider ${r.name} is not supported`)};function M(){return {name:"vitest:storybook-addon-vis",config(){return {test:{browser:{name:"chromium",commands:{existDir:p,copyFile:s,rmDir:c,isCI:f,getSnapshotPlatform:a}}}}}}}export{M as storybookVis};//# sourceMappingURL=vitest-plugin.js.map
1
+ import {copyFile,stat}from'node:fs/promises';import {mkdirp}from'mkdirp';import {join,dirname}from'pathe';import P from'is-ci';import {rimraf}from'rimraf';var s=async({testPath:o,provider:r},t,i)=>{if(r.name==="playwright"){let m=join(dirname(o),i),l=dirname(m);return await mkdirp(l),copyFile(join(dirname(o),t),m)}throw new Error(`provider ${r.name} is not supported`)};var a=async({testPath:o,provider:r},t)=>{if(r.name==="playwright")return stat(join(dirname(o),t)).then(i=>i.isDirectory()).catch(()=>!1);throw new Error(`provider ${r.name} is not supported`)};var p=async({testPath:o},r)=>stat(join(dirname(o),r)).then(t=>t.isFile()).catch(()=>!1);var f=async()=>P?process.platform:"local";var c=async()=>P;var d=async({testPath:o,provider:r},t)=>{if(r.name==="playwright")return rimraf(join(dirname(o),t));throw new Error(`provider ${r.name} is not supported`)};function X(){return {name:"vitest:storybook-addon-vis",config(){return {test:{browser:{name:"chromium",commands:{existDir:a,existFile:p,copyFile:s,rmDir:d,isCI:c,getSnapshotPlatform:f}}}}}}}export{X as storybookVis};//# sourceMappingURL=vitest-plugin.js.map
2
2
  //# sourceMappingURL=vitest-plugin.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vitest-plugin/commands/copy_file.ts","../src/vitest-plugin/commands/exist_dir.ts","../src/vitest-plugin/commands/get_snapshot_platform.ts","../src/vitest-plugin/commands/is_ci.ts","../src/vitest-plugin/commands/rm_dir.ts","../src/vitest-plugin.ts"],"names":["copyFile","testPath","provider","src","dest","destPath","join","dirname","destDir","mkdirp","copyFileFs","existDir","path","stat","s","getSnapshotPlatform","ci","isCI","rmDir","rimraf","storybookVis"],"mappings":"2JAKO,IAAMA,CAAwD,CAAA,MAAO,CAAE,QAAA,CAAAC,EAAU,QAAAC,CAAAA,CAAS,CAAGC,CAAAA,CAAAA,CAAKC,CAAS,GAAA,CACjH,GAAIF,CAAS,CAAA,IAAA,GAAS,aAAc,CACnC,IAAMG,EAAWC,IAAKC,CAAAA,OAAAA,CAAQN,CAAQ,CAAA,CAAGG,CAAI,CAAA,CACvCI,EAAUD,OAAQF,CAAAA,CAAQ,CAChC,CAAA,OAAA,MAAMI,MAAOD,CAAAA,CAAO,EACbE,QAAWJ,CAAAA,IAAAA,CAAKC,OAAQN,CAAAA,CAAQ,CAAGE,CAAAA,CAAG,EAAGE,CAAQ,CACzD,CAEA,MAAM,IAAI,MAAM,CAAYH,SAAAA,EAAAA,CAAAA,CAAS,IAAI,CAAA,iBAAA,CAAmB,CAC7D,CAAA,CCVO,IAAMS,CAAAA,CAA2C,MAAO,CAAE,SAAAV,CAAU,CAAA,QAAA,CAAAC,CAAS,CAAA,CAAGU,CAAS,GAAA,CAC/F,GAAIV,CAAS,CAAA,IAAA,GAAS,YACrB,CAAA,OAAOW,IAAKP,CAAAA,IAAAA,CAAKC,QAAQN,CAAQ,CAAA,CAAGW,CAAI,CAAC,CACvC,CAAA,IAAA,CAAME,GAAMA,CAAE,CAAA,WAAA,EAAa,CAAA,CAC3B,KAAM,CAAA,IAAM,EAAK,CAGpB,CAAA,MAAM,IAAI,KAAM,CAAA,CAAA,SAAA,EAAYZ,EAAS,IAAI,CAAA,iBAAA,CAAmB,CAC7D,CAAA,CCVO,IAAMa,CAAAA,CAAsB,SAC3B,CAAA,EAAGC,CAAK,CAAA,OAAA,CAAQ,SAAW,OAAO,CAAA,CAAA,CCDnC,IAAMC,EAAO,SAAYD,CAAAA,CCEzB,IAAME,CAAwC,CAAA,MAAO,CAAE,QAAA,CAAAjB,CAAU,CAAA,QAAA,CAAAC,CAAS,CAAGU,CAAAA,CAAAA,GAAS,CAC5F,GAAIV,CAAS,CAAA,IAAA,GAAS,aACrB,OAAOiB,MAAAA,CAAOb,KAAKC,OAAQN,CAAAA,CAAQ,EAAGW,CAAI,CAAC,CAG5C,CAAA,MAAM,IAAI,KAAA,CAAM,YAAYV,CAAS,CAAA,IAAI,CAAmB,iBAAA,CAAA,CAC7D,CCFO,CAAA,SAASkB,GAAe,CAC9B,OAAO,CACN,IAAA,CAAM,4BACN,CAAA,MAAA,EAAS,CACR,OAAO,CACN,IAAM,CAAA,CACL,OAAS,CAAA,CACR,KAAM,UACN,CAAA,QAAA,CAAU,CACT,QAAA,CAAAT,CACA,CAAA,QAAA,CAAAX,EACA,KAAAkB,CAAAA,CAAAA,CACA,IAAAD,CAAAA,CAAAA,CACA,mBAAAF,CAAAA,CACD,CACD,CACD,CACD,CACD,CACD,CACD","file":"vitest-plugin.js","sourcesContent":["import { copyFile as copyFileFs } from 'node:fs/promises'\nimport { mkdirp } from 'mkdirp'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport const copyFile: BrowserCommand<[src: string, dest: string]> = async ({ testPath, provider }, src, dest) => {\n\tif (provider.name === 'playwright') {\n\t\tconst destPath = join(dirname(testPath), dest)\n\t\tconst destDir = dirname(destPath)\n\t\tawait mkdirp(destDir)\n\t\treturn copyFileFs(join(dirname(testPath), src), destPath)\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import { stat } from 'node:fs/promises'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport const existDir: BrowserCommand<[path: string]> = async ({ testPath, provider }, path) => {\n\tif (provider.name === 'playwright') {\n\t\treturn stat(join(dirname(testPath), path))\n\t\t\t.then((s) => s.isDirectory())\n\t\t\t.catch(() => false)\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import ci from 'is-ci'\n\nexport const getSnapshotPlatform = async () => {\n\treturn `${ci ? process.platform : 'local'}`\n}\n","import ci from 'is-ci'\n\nexport const isCI = async () => ci\n","import { dirname, join } from 'pathe'\nimport { rimraf } from 'rimraf'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport const rmDir: BrowserCommand<[path: string]> = async ({ testPath, provider }, path) => {\n\tif (provider.name === 'playwright') {\n\t\treturn rimraf(join(dirname(testPath), path))\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import type { Plugin } from 'vitest/config'\nimport './augment.js'\nimport { copyFile } from './vitest-plugin/commands/copy_file.js'\nimport { existDir } from './vitest-plugin/commands/exist_dir.js'\nimport { getSnapshotPlatform } from './vitest-plugin/commands/get_snapshot_platform.js'\nimport { isCI } from './vitest-plugin/commands/is_ci.js'\nimport { rmDir } from './vitest-plugin/commands/rm_dir.js'\n\nexport function storybookVis() {\n\treturn {\n\t\tname: 'vitest:storybook-addon-vis',\n\t\tconfig() {\n\t\t\treturn {\n\t\t\t\ttest: {\n\t\t\t\t\tbrowser: {\n\t\t\t\t\t\tname: 'chromium',\n\t\t\t\t\t\tcommands: {\n\t\t\t\t\t\t\texistDir,\n\t\t\t\t\t\t\tcopyFile,\n\t\t\t\t\t\t\trmDir,\n\t\t\t\t\t\t\tisCI,\n\t\t\t\t\t\t\tgetSnapshotPlatform,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t} satisfies Plugin\n}\n"]}
1
+ {"version":3,"sources":["../src/vitest-plugin/commands/copy_file.ts","../src/vitest-plugin/commands/exist_dir.ts","../src/vitest-plugin/commands/exist_file.ts","../src/vitest-plugin/commands/get_snapshot_platform.ts","../src/vitest-plugin/commands/is_ci.ts","../src/vitest-plugin/commands/rm_dir.ts","../src/vitest-plugin.ts"],"names":["copyFile","testPath","provider","src","dest","destPath","join","dirname","destDir","mkdirp","copyFileFs","existDir","path","stat","s","existFile","getSnapshotPlatform","ci","isCI","rmDir","rimraf","storybookVis"],"mappings":"2JASO,IAAMA,CAAAA,CAAwD,MAAO,CAAE,QAAAC,CAAAA,CAAAA,CAAU,QAAAC,CAAAA,CAAS,CAAGC,CAAAA,CAAAA,CAAKC,CAAS,GAAA,CACjH,GAAIF,CAAAA,CAAS,IAAS,GAAA,YAAA,CAAc,CACnC,IAAMG,CAAWC,CAAAA,IAAAA,CAAKC,OAAQN,CAAAA,CAAQ,CAAGG,CAAAA,CAAI,CACvCI,CAAAA,CAAAA,CAAUD,OAAQF,CAAAA,CAAQ,CAChC,CAAA,OAAA,MAAMI,MAAOD,CAAAA,CAAO,CACbE,CAAAA,QAAAA,CAAWJ,IAAKC,CAAAA,OAAAA,CAAQN,CAAQ,CAAA,CAAGE,CAAG,CAAA,CAAGE,CAAQ,CACzD,CAEA,MAAM,IAAI,KAAA,CAAM,CAAYH,SAAAA,EAAAA,CAAAA,CAAS,IAAI,CAAA,iBAAA,CAAmB,CAC7D,CAAA,CCVO,IAAMS,CAAAA,CAA2C,MAAO,CAAE,QAAAV,CAAAA,CAAAA,CAAU,QAAAC,CAAAA,CAAS,CAAGU,CAAAA,CAAAA,GAAS,CAC/F,GAAIV,CAAS,CAAA,IAAA,GAAS,YACrB,CAAA,OAAOW,IAAKP,CAAAA,IAAAA,CAAKC,OAAQN,CAAAA,CAAQ,CAAGW,CAAAA,CAAI,CAAC,CAAA,CACvC,IAAME,CAAAA,CAAAA,EAAMA,CAAE,CAAA,WAAA,EAAa,CAAA,CAC3B,KAAM,CAAA,IAAM,CAAK,CAAA,CAAA,CAGpB,MAAM,IAAI,KAAM,CAAA,CAAA,SAAA,EAAYZ,CAAS,CAAA,IAAI,CAAmB,iBAAA,CAAA,CAC7D,CChBA,CAQO,IAAMa,CAAAA,CAA4C,MAAO,CAAE,QAAAd,CAAAA,CAAS,CAAGW,CAAAA,CAAAA,GACtEC,IAAKP,CAAAA,IAAAA,CAAKC,OAAQN,CAAAA,CAAQ,CAAGW,CAAAA,CAAI,CAAC,CAAA,CACvC,IAAME,CAAAA,CAAAA,EAAMA,CAAE,CAAA,MAAA,EAAQ,CAAA,CACtB,KAAM,CAAA,IAAM,CAAK,CAAA,CAAA,CCAb,IAAME,CAAsB,CAAA,SAC3BC,CAAK,CAAA,OAAA,CAAQ,QAAW,CAAA,OAAA,CCNzB,IAAMC,CAAO,CAAA,SAAYD,CCNhC,CAQO,IAAME,CAAwC,CAAA,MAAO,CAAE,QAAA,CAAAlB,CAAU,CAAA,QAAA,CAAAC,CAAS,CAAA,CAAGU,CAAS,GAAA,CAC5F,GAAIV,CAAAA,CAAS,IAAS,GAAA,YAAA,CACrB,OAAOkB,MAAAA,CAAOd,IAAKC,CAAAA,OAAAA,CAAQN,CAAQ,CAAA,CAAGW,CAAI,CAAC,CAG5C,CAAA,MAAM,IAAI,KAAA,CAAM,CAAYV,SAAAA,EAAAA,CAAAA,CAAS,IAAI,CAAA,iBAAA,CAAmB,CAC7D,CAAA,CCLO,SAASmB,CAAAA,EAAe,CAC9B,OAAO,CACN,IAAA,CAAM,4BACN,CAAA,MAAA,EAAS,CACR,OAAO,CACN,IAAA,CAAM,CACL,OAAA,CAAS,CACR,IAAA,CAAM,UACN,CAAA,QAAA,CAAU,CACT,QAAA,CAAAV,CACA,CAAA,SAAA,CAAAI,CACA,CAAA,QAAA,CAAAf,CACA,CAAA,KAAA,CAAAmB,CACA,CAAA,IAAA,CAAAD,CACA,CAAA,mBAAA,CAAAF,CACD,CACD,CACD,CACD,CACD,CACD,CACD","file":"vitest-plugin.js","sourcesContent":["import { copyFile as copyFileFs } from 'node:fs/promises'\nimport { mkdirp } from 'mkdirp'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface CopyFileCommand {\n\tcopyFile(src: string, dest: string): Promise<void>\n}\n\nexport const copyFile: BrowserCommand<[src: string, dest: string]> = async ({ testPath, provider }, src, dest) => {\n\tif (provider.name === 'playwright') {\n\t\tconst destPath = join(dirname(testPath), dest)\n\t\tconst destDir = dirname(destPath)\n\t\tawait mkdirp(destDir)\n\t\treturn copyFileFs(join(dirname(testPath), src), destPath)\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import { stat } from 'node:fs/promises'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface ExistDirCommand {\n\texistDir: (path: string) => Promise<boolean>\n}\n\nexport const existDir: BrowserCommand<[path: string]> = async ({ testPath, provider }, path) => {\n\tif (provider.name === 'playwright') {\n\t\treturn stat(join(dirname(testPath), path))\n\t\t\t.then((s) => s.isDirectory())\n\t\t\t.catch(() => false)\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import { stat } from 'node:fs/promises'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface ExistFileCommand {\n\texistFile: (path: string) => Promise<boolean>\n}\n\nexport const existFile: BrowserCommand<[path: string]> = async ({ testPath }, path) => {\n\treturn stat(join(dirname(testPath), path))\n\t\t.then((s) => s.isFile())\n\t\t.catch(() => false)\n}\n","import ci from 'is-ci'\n\nexport interface GetSnapshotPlatformCommand {\n\t/**\n\t * Get the platform id of the snapshot `{platform}[-ci]`.\n\t *\n\t * This is useful to control where the snapshot is stored.\n\t */\n\tgetSnapshotPlatform: () => Promise<string>\n}\n\nexport const getSnapshotPlatform = async () => {\n\treturn ci ? process.platform : 'local'\n}\n","import ci from 'is-ci'\n\nexport interface IsCICommand {\n\tisCI: () => Promise<boolean>\n}\n\nexport const isCI = async () => ci\n","import { dirname, join } from 'pathe'\nimport { rimraf } from 'rimraf'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface RmDirCommand {\n\trmDir: (path: string) => Promise<void>\n}\n\nexport const rmDir: BrowserCommand<[path: string]> = async ({ testPath, provider }, path) => {\n\tif (provider.name === 'playwright') {\n\t\treturn rimraf(join(dirname(testPath), path))\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import type { Plugin } from 'vitest/config'\nimport './augment.js'\nimport { copyFile } from './vitest-plugin/commands/copy_file.js'\nimport { existDir } from './vitest-plugin/commands/exist_dir.js'\nimport { existFile } from './vitest-plugin/commands/exist_file.js'\nimport { getSnapshotPlatform } from './vitest-plugin/commands/get_snapshot_platform.js'\nimport { isCI } from './vitest-plugin/commands/is_ci.js'\nimport { rmDir } from './vitest-plugin/commands/rm_dir.js'\n\nexport function storybookVis() {\n\treturn {\n\t\tname: 'vitest:storybook-addon-vis',\n\t\tconfig() {\n\t\t\treturn {\n\t\t\t\ttest: {\n\t\t\t\t\tbrowser: {\n\t\t\t\t\t\tname: 'chromium',\n\t\t\t\t\t\tcommands: {\n\t\t\t\t\t\t\texistDir,\n\t\t\t\t\t\t\texistFile,\n\t\t\t\t\t\t\tcopyFile,\n\t\t\t\t\t\t\trmDir,\n\t\t\t\t\t\t\tisCI,\n\t\t\t\t\t\t\tgetSnapshotPlatform,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t} satisfies Plugin\n}\n"]}
@@ -1,17 +1,22 @@
1
+ import { BrowserPage, CDPSession, BrowserCommands, Platform } from '@vitest/browser/context';
2
+ import { AsyncExpectationResult } from '@vitest/expect';
1
3
  import { PixelmatchOptions } from 'pixelmatch';
2
- import { CDPSession, BrowserCommands, BrowserPage, Platform } from '@vitest/browser/context';
3
4
  import { SerializedConfig } from 'vitest';
4
- import { AsyncExpectationResult } from '@vitest/expect';
5
5
 
6
- type ImageSnapshotOptions = {
6
+ interface ImageSnapshotOptions extends CustomizeSnapshotIdOptions {
7
+ element?: Element;
8
+ timeout?: number | undefined;
9
+ }
10
+ type CustomizeSnapshotIdOptions = {
7
11
  /**
8
- * Customize the filename of the snapshot.
12
+ * Customize the snapshot id. This is used as the filename of the snapshot:
13
+ *
14
+ * `${snapshotId}.png`
9
15
  *
10
16
  * @param id The id of the snapshot.
11
17
  * @param index The index of the snapshot.
12
18
  */
13
- customizeFilename?: (id: string, index: number) => string;
14
- element?: Element;
19
+ customizeSnapshotId?: (id: string, index: number) => string;
15
20
  };
16
21
  type ImageSnapshot = {
17
22
  type: symbol;
@@ -22,6 +27,18 @@ type ImageSnapshot = {
22
27
  base64: string;
23
28
  image: ImageData;
24
29
  };
30
+
31
+ interface HasImageSnapshotAction {
32
+ hasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined): Promise<boolean>;
33
+ }
34
+
35
+ interface ImageSnapshotAction {
36
+ imageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions | undefined): Promise<ImageSnapshot>;
37
+ }
38
+
39
+ interface ImageSnapshotMatcher {
40
+ toMatchImageSnapshot(options?: MatchImageSnapshotOptions): Promise<void>;
41
+ }
25
42
  type MatchImageSnapshotOptions = {
26
43
  /**
27
44
  * Custom options passed to 'pixelmatch'
@@ -35,28 +52,46 @@ type MatchImageSnapshotOptions = {
35
52
  failureThresholdType?: 'pixel' | 'percent' | undefined;
36
53
  failureThreshold?: number | undefined;
37
54
  };
55
+ declare function toMatchImageSnapshot(actual: any, options?: MatchImageSnapshotOptions | undefined): AsyncExpectationResult;
56
+
57
+ interface CopyFileCommand {
58
+ copyFile(src: string, dest: string): Promise<void>;
59
+ }
60
+
61
+ interface ExistDirCommand {
62
+ existDir: (path: string) => Promise<boolean>;
63
+ }
64
+
65
+ interface ExistFileCommand {
66
+ existFile: (path: string) => Promise<boolean>;
67
+ }
68
+
69
+ interface GetSnapshotPlatformCommand {
70
+ /**
71
+ * Get the platform id of the snapshot `{platform}[-ci]`.
72
+ *
73
+ * This is useful to control where the snapshot is stored.
74
+ */
75
+ getSnapshotPlatform: () => Promise<string>;
76
+ }
77
+
78
+ interface IsCICommand {
79
+ isCI: () => Promise<boolean>;
80
+ }
81
+
82
+ interface RmDirCommand {
83
+ rmDir: (path: string) => Promise<void>;
84
+ }
38
85
 
39
86
  declare module '@vitest/browser/context' {
40
- interface BrowserPage {
41
- imageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions): Promise<ImageSnapshot>;
87
+ interface BrowserPage extends ImageSnapshotAction, HasImageSnapshotAction {
42
88
  }
43
- interface BrowserCommands {
44
- existDir: (path: string) => Promise<boolean>;
45
- copyFile: (src: string, dest: string) => Promise<void>;
46
- rmDir: (path: string) => Promise<void>;
47
- isCI: () => Promise<boolean>;
48
- /**
49
- * Get the platform id of the snapshot `{platform}[-ci]`.
50
- *
51
- * This is useful to control where the snapshot is stored.
52
- */
53
- getSnapshotPlatform: () => Promise<string>;
89
+ interface BrowserCommands extends CopyFileCommand, ExistDirCommand, GetSnapshotPlatformCommand, RmDirCommand, IsCICommand, ExistFileCommand {
54
90
  }
55
91
  }
56
92
  declare global {
57
93
  namespace jest {
58
- interface Matchers<R, T> {
59
- toMatchImageSnapshot(options?: MatchImageSnapshotOptions): void;
94
+ interface Matchers<R, T> extends ImageSnapshotMatcher {
60
95
  }
61
96
  }
62
97
  }
@@ -94,8 +129,6 @@ declare const server: {
94
129
  config: SerializedConfig;
95
130
  };
96
131
 
97
- declare function toMatchImageSnapshot(actual: any, options?: MatchImageSnapshotOptions | undefined): AsyncExpectationResult;
98
-
99
132
  /**
100
133
  * Determine should snapshot be taken.
101
134
  *
@@ -132,4 +165,4 @@ declare function configureSnapshotBeforeEach(ctx: {
132
165
  };
133
166
  }): void;
134
167
 
135
- export { type VisOptions, cdp, commands, configureSnapshotBeforeAll, configureSnapshotBeforeEach, page, server, shouldTakeSnapshot, toMatchImageSnapshot };
168
+ export { type ImageSnapshotMatcher, type MatchImageSnapshotOptions, type VisOptions, cdp, commands, configureSnapshotBeforeAll, configureSnapshotBeforeEach, page, server, shouldTakeSnapshot, toMatchImageSnapshot };
@@ -1,6 +1,8 @@
1
- import {join,basename,dirname,relative}from'pathe';import {getByAltText,getByRole,getByTestId,getByText,getByTitle,getByPlaceholderText,getByLabelText}from'@storybook/test';import k from'dedent';import C from'pixelmatch';var f=Symbol.for("storybook-addon-vis/imageSnapshot"),g=Symbol.for("storybook-addon-vis/imageSnapshotStub");function d(t){return new Promise((e,a)=>{let n=new Image;n.src=`data:image/png;base64,${t}`,n.onload=()=>{let r=document.createElement("canvas");r.width=n.width,r.height=n.height;let o=r.getContext("2d");o.drawImage(n,0,0),e(o.getImageData(0,0,r.width,r.height));},n.onerror=()=>{a(new Error("Failed to load image"));};})}async function S(t){let e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").putImageData(t,0,0),new Promise(n=>{e.toBlob(r=>{let o=new FileReader;o.onload=()=>{n(o.result);},o.readAsDataURL(r);});})}var s={name:"",testFilepath:"",taskName:"",snapshot:{}};async function I(t){let e=s.snapshot[s.id].index++,a=t?.customizeFilename?`${t.customizeFilename(s.id,e)}.png`:`${s.id}-${e}.png`,n=join(s.baselineDir,a),r=join(s.resultDir,a),o=join(s.diffDir,a),i=await this.screenshot({base64:!0,path:r,element:t?.element}),m=await d(i.base64);return {type:f,snapshotFilename:a,baselinePath:n,resultPath:r,diffPath:o,base64:i.base64,image:m}}var h;globalThis.__vitest_browser__&&import('@vitest/browser/context').then(t=>{h=t,A.extend({imageSnapshot:I});});function st(){return h?.cdp()??{}}var c=new Proxy({},{get(t,e){return t[e]??(h?.commands)[e]}}),A=new Proxy({getByAltText:getByAltText,getByRole:getByRole,getByTestId:getByTestId,getByText:getByText,getByTitle:getByTitle,getByPlaceholder:getByPlaceholderText,getByLabelText:getByLabelText},{get(t,e){return t[e]??h?.page?(h?.page)[e]:()=>{if(e==="imageSnapshot")return {type:g};console.info(`\`page.${e.toString()}\` does not exist when running in browser`);}}}),D=new Proxy({},{get(t,e){return t[e]??(h?.server)[e]}});function x(t){return !!t&&t.type===f}function P(t){if(!x(t))throw new Error("Expected subject to be an image snapshot")}function $(t){return `${t.replace(/[^a-z0-9]/gi,"-").toLowerCase()}`}var v=({width:t,height:e})=>a=>{if(a.width===t&&a.height===e)return a;let n=(o,i)=>i<=a.height&&o<=a.width,r=new ImageData(t,e,{colorSpace:a.colorSpace});for(let o=0;o<e;o++)for(let i=0;i<t;i++){let m=t*o+i<<2;if(n(i,o)){let p=a.width*o+i<<2;r.data[m]=a.data[p],r.data[m+1]=a.data[p+1],r.data[m+2]=a.data[p+2],r.data[m+3]=a.data[p+3];}else r.data[m]=0,r.data[m+1]=0,r.data[m+2]=0,r.data[m+3]=64;}return r};async function dt(t,e){let a=await t;if(a?.type===g)return u;if(!x(a)){if(a?.path&&a?.base64)return {pass:!1,actual:a,message:()=>"`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?"};if(typeof a!="object")return {pass:!1,actual:a,message:()=>`\`toMatchImageSnapshot()\` expects the subject to be an element, locator, or result of \`page.imageSnapshot()\`, but got: \`${a}\``}}P(a);let n=await O(a.baselinePath);if(!n)return await c.copyFile(a.resultPath,a.baselinePath),u;let r=await d(n),[o,i]=M(a.image,r),{pass:m,diffAmount:p,diffImage:l}=U(i,o,e);return m?u:D.config.snapshotOptions.updateSnapshot==="all"?(await B(`${a.baselinePath}`,o),u):(await B(`${a.diffPath}`,l),{pass:!1,message:()=>k`${e?.failureThreshold?e?.failureThresholdType==="percent"?`Expected image to match within ${e.failureThreshold}% but was differ by ${p}%.`:`Expected image to match within ${e.failureThreshold} pixels but was differ by ${p} pixels.`:`Expected image to match but was differ by ${e?.failureThresholdType==="percent"?`${p}%`:`${p} pixels`}.`}
1
+ import {join,basename,dirname,relative}from'pathe';import {getByAltText,getByRole,getByTestId,getByText,getByTitle,getByPlaceholderText,getByLabelText}from'@storybook/test';import R from'dedent';import k from'pixelmatch';var f=Symbol.for("storybook-addon-vis/imageSnapshot"),g=Symbol.for("storybook-addon-vis/imageSnapshotStub");var s={name:"",testFilepath:"",taskName:"",snapshot:{}};async function I(t){let e=s.snapshot[s.id].index,a=t?.customizeSnapshotId?`${t.customizeSnapshotId(s.id,e)}.png`:`${s.id}-${e}.png`,o=join(s.baselineDir,a);return h.existFile(o)}function l(t){return new Promise((e,a)=>{let o=new Image;o.src=`data:image/png;base64,${t}`,o.onload=()=>{let n=document.createElement("canvas");n.width=o.width,n.height=o.height;let r=n.getContext("2d");r.drawImage(o,0,0),e(r.getImageData(0,0,n.width,n.height));},o.onerror=()=>{a(new Error("Failed to load image"));};})}async function w(t){let e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").putImageData(t,0,0),new Promise(o=>{e.toBlob(n=>{let r=new FileReader;r.onload=()=>{o(r.result);},r.readAsDataURL(n);});})}async function D(t){let e=s.snapshot[s.id].index++,a=t?.customizeSnapshotId?`${t.customizeSnapshotId(s.id,e)}.png`:`${s.id}-${e}.png`,o=join(s.baselineDir,a),n=join(s.resultDir,a),r=join(s.diffDir,a),i=await this.screenshot({base64:!0,path:n,element:t?.element,timeout:t?.timeout??3e3}),m=await l(i.base64);return {type:f,snapshotFilename:a,baselinePath:o,resultPath:n,diffPath:r,base64:i.base64,image:m}}var c;globalThis.__vitest_browser__&&import('@vitest/browser/context').then(t=>{c=t,M.extend({imageSnapshot:D,hasImageSnapshot:I});});function ht(){return c?.cdp()??{}}var h=new Proxy({},{get(t,e){return t[e]??(c?.commands)[e]}}),M=new Proxy({getByAltText:getByAltText,getByRole:getByRole,getByTestId:getByTestId,getByText:getByText,getByTitle:getByTitle,getByPlaceholder:getByPlaceholderText,getByLabelText:getByLabelText},{get(t,e){return t[e]??c?.page?(c?.page)[e]:()=>{if(e==="imageSnapshot")return {type:g};console.info(`\`page.${e.toString()}\` does not exist when running in browser`);}}}),P=new Proxy({},{get(t,e){return t[e]??(c?.server)[e]}});function y(t){return !!t&&t.type===f}function $(t){if(!y(t))throw new Error("Expected subject to be an image snapshot")}function B(t){return `${t.replace(/[^a-z0-9]/gi,"-").toLowerCase()}`}var T=({width:t,height:e})=>a=>{if(a.width===t&&a.height===e)return a;let o=(r,i)=>i<=a.height&&r<=a.width,n=new ImageData(t,e,{colorSpace:a.colorSpace});for(let r=0;r<e;r++)for(let i=0;i<t;i++){let m=t*r+i<<2;if(o(i,r)){let p=a.width*r+i<<2;n.data[m]=a.data[p],n.data[m+1]=a.data[p+1],n.data[m+2]=a.data[p+2],n.data[m+3]=a.data[p+3];}else n.data[m]=0,n.data[m+1]=0,n.data[m+2]=0,n.data[m+3]=64;}return n};async function Dt(t,e){let a=await t;if(a?.type===g)return u;if(!y(a)){if(a?.path&&a?.base64)return {pass:!1,actual:a,message:()=>"`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?"};if(typeof a!="object")return {pass:!1,actual:a,message:()=>`\`toMatchImageSnapshot()\` expects the subject to be an element, locator, or result of \`page.imageSnapshot()\`, but got: \`${a}\``}}$(a);let o=await L(a.baselinePath);if(!o)return await h.copyFile(a.resultPath,a.baselinePath),u;let n=await l(o),[r,i]=N(a.image,n),{pass:m,diffAmount:p,diffImage:d}=H(i,r,e);return m?u:P.config.snapshotOptions.updateSnapshot==="all"?(await v(`${a.baselinePath}`,r),u):(await v(`${a.diffPath}`,d),{pass:!1,message:()=>R`Snapshot \`${s.taskName}\` mismatched
2
+
3
+ ${e?.failureThreshold?e?.failureThresholdType==="percent"?`Expected image to match within ${e.failureThreshold}% but was differ by ${p}%.`:`Expected image to match within ${e.failureThreshold} pixels but was differ by ${p} pixels.`:`Expected image to match but was differ by ${e?.failureThresholdType==="percent"?`${p}%`:`${p} pixels`}.`}
2
4
 
3
5
  Expected: '${a.baselinePath}'
4
6
  Actual: '${a.resultPath}'
5
- Difference: '${a.diffPath}'`})}var u={pass:!0,message:()=>""};function O(t){return c.readFile(t,{encoding:"base64"}).catch(()=>{})}async function B(t,e){let a=(await S(e)).split(",")[1];return c.writeFile(t,a,"base64url")}function M(t,e){if(N(t,e))return [t,e];let a=L(t,e),n=v(a);return [n(t),n(e)]}function L(t,e){let a=Math.max(t.width,e.width),n=Math.max(t.height,e.height);return {width:a,height:n}}function N(t,e){return t.width===e.width&&t.height===e.height}function U(t,e,{failureThreshold:a=0,failureThresholdType:n="pixel",diffOptions:r}={}){let{width:o,height:i}=e,m=new ImageData(o,i),p=C(e.data,t.data,m.data,o,i,r),l=V({failureThresholdType:n,width:o,height:i},p);return {pass:l<=a,diffAmount:l,diffImage:m}}function V({failureThresholdType:t,width:e,height:a},n){switch(t){case"pixel":return n;case"percent":return n/(e*a)*100;default:throw new Error(`Invalid failureThresholdType: ${t}`)}}function yt(t){return t.story?.tags?t.story.tags.lastIndexOf("!snapshot")<t.story.tags.lastIndexOf("snapshot"):!1}async function Dt(t,e){s.name=t.name,s.testFilepath=t.file.filepath,s.testFilename=basename(s.testFilepath),s.projectDir=s.testFilepath.slice(0,-s.name.length);let a=join(s.projectDir,e?.snapshotPath??`__snapshots__/${await c.getSnapshotPlatform()}`),n=dirname(s.testFilepath);s.baselineDir=relative(n,join(a,s.testFilename)),s.resultDir=relative(n,join(a,"__results__",s.testFilename)),s.diffDir=relative(n,join(a,"__diff_output__",s.testFilename)),await c.rmDir(s.resultDir),await c.rmDir(s.diffDir);}function Pt(t){s.taskName=t.task.name;let e=s.id=$(s.taskName);s.snapshot[e]=s.snapshot[e]??{index:1};}export{st as cdp,c as commands,Dt as configureSnapshotBeforeAll,Pt as configureSnapshotBeforeEach,A as page,D as server,yt as shouldTakeSnapshot,dt as toMatchImageSnapshot};//# sourceMappingURL=vitest-setup.js.map
7
+ Difference: '${a.diffPath}'`})}var u={pass:!0,message:()=>""};function L(t){return h.readFile(t,{encoding:"base64"}).catch(()=>{})}async function v(t,e){let a=(await w(e)).split(",")[1];return h.writeFile(t,a,"base64url")}function N(t,e){if(V(t,e))return [t,e];let a=U(t,e),o=T(a);return [o(t),o(e)]}function U(t,e){let a=Math.max(t.width,e.width),o=Math.max(t.height,e.height);return {width:a,height:o}}function V(t,e){return t.width===e.width&&t.height===e.height}function H(t,e,{failureThreshold:a=0,failureThresholdType:o="pixel",diffOptions:n}={}){let{width:r,height:i}=e,m=new ImageData(r,i),p=k(e.data,t.data,m.data,r,i,n),d=q({failureThresholdType:o,width:r,height:i},p);return {pass:d<=a,diffAmount:d,diffImage:m}}function q({failureThresholdType:t,width:e,height:a},o){switch(t){case"pixel":return o;case"percent":return o/(e*a)*100;default:throw new Error(`Invalid failureThresholdType: ${t}`)}}function $t(t){return t.story?.tags?t.story.tags.lastIndexOf("!snapshot")<t.story.tags.lastIndexOf("snapshot"):!1}async function Ot(t,e){s.name=t.name,s.testFilepath=t.file.filepath,s.testFilename=basename(s.testFilepath),s.projectDir=s.testFilepath.slice(0,-s.name.length);let a=join(s.projectDir,e?.snapshotPath??`__snapshots__/${await h.getSnapshotPlatform()}`),o=dirname(s.testFilepath);s.baselineDir=relative(o,join(a,s.testFilename)),s.resultDir=relative(o,join(a,"__results__",s.testFilename)),s.diffDir=relative(o,join(a,"__diff_output__",s.testFilename)),await h.rmDir(s.resultDir),await h.rmDir(s.diffDir);}function _t(t){s.taskName=t.task.name;let e=s.id=B(s.taskName);s.snapshot[e]=s.snapshot[e]??{index:1};}export{ht as cdp,h as commands,Ot as configureSnapshotBeforeAll,_t as configureSnapshotBeforeEach,M as page,P as server,$t as shouldTakeSnapshot,Dt as toMatchImageSnapshot};//# sourceMappingURL=vitest-setup.js.map
6
8
  //# sourceMappingURL=vitest-setup.js.map