@tobelabs/chainwright 0.1.0 → 0.2.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/dist/cli/index.js CHANGED
@@ -27,7 +27,7 @@ Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,i=>{let
27
27
  `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ot(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}function He(){if(A.env.NO_COLOR||A.env.FORCE_COLOR==="0"||A.env.FORCE_COLOR==="false")return!1;if(A.env.FORCE_COLOR||A.env.CLICOLOR_FORCE!==void 0)return!0}Ue.Command=Re;Ue.useColor=He});var ut=T(W=>{"use strict";var{Argument:at}=ce(),{Command:Pe}=st(),{CommanderError:wn,InvalidArgumentError:lt}=Q(),{Help:xn}=Le(),{Option:ct}=ve();W.program=new Pe;W.createCommand=o=>new Pe(o);W.createOption=(o,e)=>new ct(o,e);W.createArgument=(o,e)=>new at(o,e);W.Command=Pe;W.Option=ct;W.Argument=at;W.Help=xn;W.CommanderError=wn;W.InvalidArgumentError=lt;W.InvalidOptionArgumentError=lt});var We=T((ui,_t)=>{"use strict";_t.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var de=T(yt=>{"use strict";var Ct={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function qn(o){return function(...e){return e.length&&(o=o.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+o)}}for(let o of Object.keys(Ct))yt[o]=qn(Ct[o])});var At=T((hi,xt)=>{"use strict";var Xn=M("fs"),U=M("path"),Ot=We(),Kn=de(),Yn=typeof process=="object"&&process.platform==="win32",St=o=>typeof o=="object"&&o!==null,wt=new Uint32Array(256).map((o,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function R(o){this.sep=U.sep,this.fs=Xn,St(o)&&St(o.fs)&&typeof o.fs.statSync=="function"&&(this.fs=o.fs)}xt.exports=R;R.prototype.makeDir=function(o){let e=this;function t(n){let r=n.split(e.sep)[0];n.split(e.sep).forEach(function(i){if(!(!i||i.substr(-1,1)===":")){r+=e.sep+i;var a;try{a=e.fs.statSync(r)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(r);else throw c}if(a&&a.isFile())throw Kn.FILE_IN_THE_WAY(`"${r}"`)}})}t(o)};R.prototype.writeFileTo=function(o,e,t,n){let r=this;if(r.fs.existsSync(o)){if(!t)return!1;var i=r.fs.statSync(o);if(i.isDirectory())return!1}var a=U.dirname(o);r.fs.existsSync(a)||r.makeDir(a);var c;try{c=r.fs.openSync(o,"w",438)}catch{r.fs.chmodSync(o,438),c=r.fs.openSync(o,"w",438)}if(c)try{r.fs.writeSync(c,e,0,e.length,0)}finally{r.fs.closeSync(c)}return r.fs.chmodSync(o,n||438),!0};R.prototype.writeFileToAsync=function(o,e,t,n,r){typeof n=="function"&&(r=n,n=void 0);let i=this;i.fs.exists(o,function(a){if(a&&!t)return r(!1);i.fs.stat(o,function(c,d){if(a&&d.isDirectory())return r(!1);var g=U.dirname(o);i.fs.exists(g,function(C){C||i.makeDir(g),i.fs.open(o,"w",438,function(E,S){E?i.fs.chmod(o,438,function(){i.fs.open(o,"w",438,function(l,u){i.fs.write(u,e,0,e.length,0,function(){i.fs.close(u,function(){i.fs.chmod(o,n||438,function(){r(!0)})})})})}):S?i.fs.write(S,e,0,e.length,0,function(){i.fs.close(S,function(){i.fs.chmod(o,n||438,function(){r(!0)})})}):i.fs.chmod(o,n||438,function(){r(!0)})})})})})};R.prototype.findFiles=function(o){let e=this;function t(n,r,i){typeof r=="boolean"&&(i=r,r=void 0);let a=[];return e.fs.readdirSync(n).forEach(function(c){let d=U.join(n,c),g=e.fs.statSync(d);(!r||r.test(d))&&a.push(U.normalize(d)+(g.isDirectory()?e.sep:"")),g.isDirectory()&&i&&(a=a.concat(t(d,r,i)))}),a}return t(o,void 0,!0)};R.prototype.findFilesAsync=function(o,e){let t=this,n=[];t.fs.readdir(o,function(r,i){if(r)return e(r);let a=i.length;if(!a)return e(null,n);i.forEach(function(c){c=U.join(o,c),t.fs.stat(c,function(d,g){if(d)return e(d);g&&(n.push(U.normalize(c)+(g.isDirectory()?t.sep:"")),g.isDirectory()?t.findFilesAsync(c,function(C,E){if(C)return e(C);n=n.concat(E),--a||e(null,n)}):--a||e(null,n))})})})};R.prototype.getAttributes=function(){};R.prototype.setAttributes=function(){};R.crc32update=function(o,e){return wt[(o^e)&255]^o>>>8};R.crc32=function(o){typeof o=="string"&&(o=Buffer.from(o,"utf8"));let e=o.length,t=-1;for(let n=0;n<e;)t=R.crc32update(t,o[n++]);return~t>>>0};R.methodToString=function(o){switch(o){case Ot.STORED:return"STORED ("+o+")";case Ot.DEFLATED:return"DEFLATED ("+o+")";default:return"UNSUPPORTED ("+o+")"}};R.canonical=function(o){if(!o)return"";let e=U.posix.normalize("/"+o.split("\\").join("/"));return U.join(".",e)};R.zipnamefix=function(o){if(!o)return"";let e=U.posix.normalize("/"+o.split("\\").join("/"));return U.posix.join(".",e)};R.findLast=function(o,e){if(!Array.isArray(o))throw new TypeError("arr is not array");let t=o.length>>>0;for(let n=t-1;n>=0;n--)if(e(o[n],n,o))return o[n]};R.sanitize=function(o,e){o=U.resolve(U.normalize(o));for(var t=e.split("/"),n=0,r=t.length;n<r;n++){var i=U.normalize(U.join(o,t.slice(n,r).join(U.sep)));if(i.indexOf(o)===0)return i}return U.normalize(U.join(o,U.basename(e)))};R.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};R.readBigUInt64LE=function(o,e){let t=o.readUInt32LE(e);return o.readUInt32LE(e+4)*4294967296+t};R.fromDOS2Date=function(o){return new Date((o>>25&127)+1980,Math.max((o>>21&15)-1,0),Math.max(o>>16&31,1),o>>11&31,o>>5&63,(o&31)<<1)};R.fromDate2DOS=function(o){let e=0,t=0;return o.getFullYear()>1979&&(e=(o.getFullYear()-1980&127)<<9|o.getMonth()+1<<5|o.getDate(),t=o.getHours()<<11|o.getMinutes()<<5|o.getSeconds()>>1),e<<16|t};R.isWin=Yn;R.crcTable=wt});var Lt=T((di,It)=>{"use strict";var Jn=M("path");It.exports=function(o,{fs:e}){var t=o||"",n=i(),r=null;function i(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(r=e.statSync(t),n.directory=r.isDirectory(),n.mtime=r.mtime,n.atime=r.atime,n.executable=(73&r.mode)!==0,n.readonly=(128&r.mode)===0,n.hidden=Jn.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Nt=T((mi,Dt)=>{"use strict";Dt.exports={efs:!0,encode:o=>Buffer.from(o,"utf8"),decode:o=>o.toString("utf8")}});var Y=T((pi,K)=>{"use strict";K.exports=At();K.exports.Constants=We();K.exports.Errors=de();K.exports.FileAttr=Lt();K.exports.decoder=Nt()});var vt=T((gi,Tt)=>{"use strict";var j=Y(),O=j.Constants;Tt.exports=function(){var o=20,e=10,t=0,n=0,r=0,i=0,a=0,c=0,d=0,g=0,C=0,E=0,S=0,l=0,u=0;o|=j.isWin?2560:768,t|=O.FLG_EFS;let p={extraLen:0},f=s=>Math.max(0,s)>>>0,m=s=>Math.max(0,s)&65535,y=s=>Math.max(0,s)&255;return r=j.fromDate2DOS(new Date),{get made(){return o},set made(s){o=s},get version(){return e},set version(s){e=s},get flags(){return t},set flags(s){t=s},get flags_efs(){return(t&O.FLG_EFS)>0},set flags_efs(s){s?t|=O.FLG_EFS:t&=~O.FLG_EFS},get flags_desc(){return(t&O.FLG_DESC)>0},set flags_desc(s){s?t|=O.FLG_DESC:t&=~O.FLG_DESC},get method(){return n},set method(s){switch(s){case O.STORED:this.version=10;case O.DEFLATED:default:this.version=20}n=s},get time(){return j.fromDOS2Date(this.timeval)},set time(s){s=new Date(s),this.timeval=j.fromDate2DOS(s)},get timeval(){return r},set timeval(s){r=f(s)},get timeHighByte(){return y(r>>>8)},get crc(){return i},set crc(s){i=f(s)},get compressedSize(){return a},set compressedSize(s){a=f(s)},get size(){return c},set size(s){c=f(s)},get fileNameLength(){return d},set fileNameLength(s){d=s},get extraLength(){return g},set extraLength(s){g=s},get extraLocalLength(){return p.extraLen},set extraLocalLength(s){p.extraLen=s},get commentLength(){return C},set commentLength(s){C=s},get diskNumStart(){return E},set diskNumStart(s){E=f(s)},get inAttr(){return S},set inAttr(s){S=f(s)},get attr(){return l},set attr(s){l=f(s)},get fileAttr(){return(l||0)>>16&4095},get offset(){return u},set offset(s){u=f(s)},get encrypted(){return(t&O.FLG_ENC)===O.FLG_ENC},get centralHeaderSize(){return O.CENHDR+d+g+C},get realDataOffset(){return u+O.LOCHDR+p.fnameLen+p.extraLen},get localHeader(){return p},loadLocalHeaderFromBinary:function(s){var h=s.slice(u,u+O.LOCHDR);if(h.readUInt32LE(0)!==O.LOCSIG)throw j.Errors.INVALID_LOC();p.version=h.readUInt16LE(O.LOCVER),p.flags=h.readUInt16LE(O.LOCFLG),p.flags_desc=(p.flags&O.FLG_DESC)>0,p.method=h.readUInt16LE(O.LOCHOW),p.time=h.readUInt32LE(O.LOCTIM),p.crc=h.readUInt32LE(O.LOCCRC),p.compressedSize=h.readUInt32LE(O.LOCSIZ),p.size=h.readUInt32LE(O.LOCLEN),p.fnameLen=h.readUInt16LE(O.LOCNAM),p.extraLen=h.readUInt16LE(O.LOCEXT);let _=u+O.LOCHDR+p.fnameLen,x=_+p.extraLen;return s.slice(_,x)},loadFromBinary:function(s){if(s.length!==O.CENHDR||s.readUInt32LE(0)!==O.CENSIG)throw j.Errors.INVALID_CEN();o=s.readUInt16LE(O.CENVEM),e=s.readUInt16LE(O.CENVER),t=s.readUInt16LE(O.CENFLG),n=s.readUInt16LE(O.CENHOW),r=s.readUInt32LE(O.CENTIM),i=s.readUInt32LE(O.CENCRC),a=s.readUInt32LE(O.CENSIZ),c=s.readUInt32LE(O.CENLEN),d=s.readUInt16LE(O.CENNAM),g=s.readUInt16LE(O.CENEXT),C=s.readUInt16LE(O.CENCOM),E=s.readUInt16LE(O.CENDSK),S=s.readUInt16LE(O.CENATT),l=s.readUInt32LE(O.CENATX),u=s.readUInt32LE(O.CENOFF)},localHeaderToBinary:function(){var s=Buffer.alloc(O.LOCHDR);return s.writeUInt32LE(O.LOCSIG,0),s.writeUInt16LE(e,O.LOCVER),s.writeUInt16LE(t,O.LOCFLG),s.writeUInt16LE(n,O.LOCHOW),s.writeUInt32LE(r,O.LOCTIM),s.writeUInt32LE(i,O.LOCCRC),s.writeUInt32LE(a,O.LOCSIZ),s.writeUInt32LE(c,O.LOCLEN),s.writeUInt16LE(d,O.LOCNAM),s.writeUInt16LE(p.extraLen,O.LOCEXT),s},centralHeaderToBinary:function(){var s=Buffer.alloc(O.CENHDR+d+g+C);return s.writeUInt32LE(O.CENSIG,0),s.writeUInt16LE(o,O.CENVEM),s.writeUInt16LE(e,O.CENVER),s.writeUInt16LE(t,O.CENFLG),s.writeUInt16LE(n,O.CENHOW),s.writeUInt32LE(r,O.CENTIM),s.writeUInt32LE(i,O.CENCRC),s.writeUInt32LE(a,O.CENSIZ),s.writeUInt32LE(c,O.CENLEN),s.writeUInt16LE(d,O.CENNAM),s.writeUInt16LE(g,O.CENEXT),s.writeUInt16LE(C,O.CENCOM),s.writeUInt16LE(E,O.CENDSK),s.writeUInt16LE(S,O.CENATT),s.writeUInt32LE(l,O.CENATX),s.writeUInt32LE(u,O.CENOFF),s},toJSON:function(){let s=function(h){return h+" bytes"};return{made:o,version:e,flags:t,method:j.methodToString(n),time:this.time,crc:"0x"+i.toString(16).toUpperCase(),compressedSize:s(a),size:s(c),fileNameLength:s(d),extraLength:s(g),commentLength:s(C),diskNumStart:E,inAttr:S,attr:l,offset:u,centralHeaderSize:s(O.CENHDR+d+g+C)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var bt=T((Ei,Ft)=>{"use strict";var J=Y(),v=J.Constants;Ft.exports=function(){var o=0,e=0,t=0,n=0,r=0;return{get diskEntries(){return o},set diskEntries(i){o=e=i},get totalEntries(){return e},set totalEntries(i){e=o=i},get size(){return t},set size(i){t=i},get offset(){return n},set offset(i){n=i},get commentLength(){return r},set commentLength(i){r=i},get mainHeaderSize(){return v.ENDHDR+r},loadFromBinary:function(i){if((i.length!==v.ENDHDR||i.readUInt32LE(0)!==v.ENDSIG)&&(i.length<v.ZIP64HDR||i.readUInt32LE(0)!==v.ZIP64SIG))throw J.Errors.INVALID_END();i.readUInt32LE(0)===v.ENDSIG?(o=i.readUInt16LE(v.ENDSUB),e=i.readUInt16LE(v.ENDTOT),t=i.readUInt32LE(v.ENDSIZ),n=i.readUInt32LE(v.ENDOFF),r=i.readUInt16LE(v.ENDCOM)):(o=J.readBigUInt64LE(i,v.ZIP64SUB),e=J.readBigUInt64LE(i,v.ZIP64TOT),t=J.readBigUInt64LE(i,v.ZIP64SIZE),n=J.readBigUInt64LE(i,v.ZIP64OFF),r=0)},toBinary:function(){var i=Buffer.alloc(v.ENDHDR+r);return i.writeUInt32LE(v.ENDSIG,0),i.writeUInt32LE(0,4),i.writeUInt16LE(o,v.ENDSUB),i.writeUInt16LE(e,v.ENDTOT),i.writeUInt32LE(t,v.ENDSIZ),i.writeUInt32LE(n,v.ENDOFF),i.writeUInt16LE(r,v.ENDCOM),i.fill(" ",v.ENDHDR),i},toJSON:function(){let i=function(a,c){let d=a.toString(16).toUpperCase();for(;d.length<c;)d="0"+d;return"0x"+d};return{diskEntries:o,totalEntries:e,size:t+" bytes",offset:i(n,4),commentLength:r}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ke=T(Ve=>{"use strict";Ve.EntryHeader=vt();Ve.MainHeader=bt()});var Ht=T((Ci,Rt)=>{"use strict";Rt.exports=function(o){var e=M("zlib"),t={chunkSize:(parseInt(o.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(o,t)},deflateAsync:function(n){var r=e.createDeflateRaw(t),i=[],a=0;r.on("data",function(c){i.push(c),a+=c.length}),r.on("end",function(){var c=Buffer.alloc(a),d=0;c.fill(0);for(var g=0;g<i.length;g++){var C=i[g];C.copy(c,d),d+=C.length}n&&n(c)}),r.end(o)}}}});var Pt=T((yi,Ut)=>{"use strict";var Qn=+(process.versions?process.versions.node:"").split(".")[0]||0;Ut.exports=function(o,e){var t=M("zlib");let n=Qn>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(o,n)},inflateAsync:function(r){var i=t.createInflateRaw(n),a=[],c=0;i.on("data",function(d){a.push(d),c+=d.length}),i.on("end",function(){var d=Buffer.alloc(c),g=0;d.fill(0);for(var C=0;C<a.length;C++){var E=a[C];E.copy(d,g),g+=E.length}r&&r(d)}),i.end(o)}}}});var Vt=T((Oi,Wt)=>{"use strict";var{randomFillSync:$t}=M("crypto"),er=de(),tr=new Uint32Array(256).map((o,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Mt=(o,e)=>Math.imul(o,e)>>>0,Bt=(o,e)=>tr[(o^e)&255]^o>>>8,ie=()=>typeof $t=="function"?$t(Buffer.alloc(12)):ie.node();ie.node=()=>{let o=Buffer.alloc(12),e=o.length;for(let t=0;t<e;t++)o[t]=Math.random()*256&255;return o};var me={genSalt:ie};function pe(o){let e=Buffer.isBuffer(o)?o:Buffer.from(o);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}pe.prototype.updateKeys=function(o){let e=this.keys;return e[0]=Bt(e[0],o),e[1]+=e[0]&255,e[1]=Mt(e[1],134775813)+1,e[2]=Bt(e[2],e[1]>>>24),o};pe.prototype.next=function(){let o=(this.keys[2]|2)>>>0;return Mt(o,o^1)>>8&255};function nr(o){let e=new pe(o);return function(t){let n=Buffer.alloc(t.length),r=0;for(let i of t)n[r++]=e.updateKeys(i^e.next());return n}}function rr(o){let e=new pe(o);return function(t,n,r=0){n||(n=Buffer.alloc(t.length));for(let i of t){let a=e.next();n[r++]=i^a,e.updateKeys(i)}return n}}function ir(o,e,t){if(!o||!Buffer.isBuffer(o)||o.length<12)return Buffer.alloc(0);let n=nr(t),r=n(o.slice(0,12)),i=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(r[11]!==i)throw er.WRONG_PASSWORD();return n(o.slice(12))}function or(o){Buffer.isBuffer(o)&&o.length>=12?me.genSalt=function(){return o.slice(0,12)}:o==="node"?me.genSalt=ie.node:me.genSalt=ie}function sr(o,e,t,n=!1){o==null&&(o=Buffer.alloc(0)),Buffer.isBuffer(o)||(o=Buffer.from(o.toString()));let r=rr(t),i=me.genSalt();i[11]=e.crc>>>24&255,n&&(i[10]=e.crc>>>16&255);let a=Buffer.alloc(o.length+12);return r(i,a),r(o,a,12)}Wt.exports={decrypt:ir,encrypt:sr,_salter:or}});var kt=T(ge=>{"use strict";ge.Deflater=Ht();ge.Inflater=Pt();ge.ZipCrypto=Vt()});var je=T((wi,Gt)=>{"use strict";var L=Y(),ar=ke(),H=L.Constants,Ge=kt();Gt.exports=function(o,e){var t=new ar.EntryHeader,n=Buffer.alloc(0),r=Buffer.alloc(0),i=!1,a=null,c=Buffer.alloc(0),d=Buffer.alloc(0),g=!0;let C=o,E=typeof C.decoder=="object"?C.decoder:L.decoder;g=E.hasOwnProperty("efs")?E.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(d=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function l(s){if(!t.flags_desc&&!t.localHeader.flags_desc){if(L.crc32(s)!==t.localHeader.crc)return!1}else{let h={},_=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(_)==H.LOCSIG||e.readUInt32LE(_)==H.CENSIG)throw L.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(_)==H.EXTSIG)h.crc=e.readUInt32LE(_+H.EXTCRC),h.compressedSize=e.readUInt32LE(_+H.EXTSIZ),h.size=e.readUInt32LE(_+H.EXTLEN);else if(e.readUInt16LE(_+12)===19280)h.crc=e.readUInt32LE(_+H.EXTCRC-4),h.compressedSize=e.readUInt32LE(_+H.EXTSIZ-4),h.size=e.readUInt32LE(_+H.EXTLEN-4);else throw L.Errors.DESCRIPTOR_UNKNOWN();if(h.compressedSize!==t.compressedSize||h.size!==t.size||h.crc!==t.crc)throw L.Errors.DESCRIPTOR_FAULTY();if(L.crc32(s)!==h.crc)return!1}return!0}function u(s,h,_){if(typeof h>"u"&&typeof s=="string"&&(_=s,s=void 0),i)return s&&h&&h(Buffer.alloc(0),L.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var x=S();if(x.length===0)return s&&h&&h(x),x;if(t.encrypted){if(typeof _!="string"&&!Buffer.isBuffer(_))throw L.Errors.INVALID_PASS_PARAM();x=Ge.ZipCrypto.decrypt(x,t,_)}var w=Buffer.alloc(t.size);switch(t.method){case L.Constants.STORED:if(x.copy(w),l(w))return s&&h&&h(w),w;throw s&&h&&h(w,L.Errors.BAD_CRC()),L.Errors.BAD_CRC();case L.Constants.DEFLATED:var D=new Ge.Inflater(x,t.size);if(s)D.inflateAsync(function(I){I.copy(I,0),h&&(l(I)?h(I):h(I,L.Errors.BAD_CRC()))});else{if(D.inflate(w).copy(w,0),!l(w))throw L.Errors.BAD_CRC(`"${E.decode(n)}"`);return w}break;default:throw s&&h&&h(Buffer.alloc(0),L.Errors.UNKNOWN_METHOD()),L.Errors.UNKNOWN_METHOD()}}function p(s,h){if((!a||!a.length)&&Buffer.isBuffer(e))return s&&h&&h(S()),S();if(a.length&&!i){var _;switch(t.method){case L.Constants.STORED:return t.compressedSize=t.size,_=Buffer.alloc(a.length),a.copy(_),s&&h&&h(_),_;default:case L.Constants.DEFLATED:var x=new Ge.Deflater(a);if(s)x.deflateAsync(function(D){_=Buffer.alloc(D.length),t.compressedSize=D.length,D.copy(_),h&&h(_)});else{var w=x.deflate();return t.compressedSize=w.length,w}x=null;break}}else if(s&&h)h(Buffer.alloc(0));else return Buffer.alloc(0)}function f(s,h){return L.readBigUInt64LE(s,h)}function m(s){try{for(var h=0,_,x,w;h+4<s.length;)_=s.readUInt16LE(h),h+=2,x=s.readUInt16LE(h),h+=2,w=s.slice(h,h+x),h+=x,H.ID_ZIP64===_&&y(w)}catch{throw L.Errors.EXTRA_FIELD_PARSE_ERROR()}}function y(s){var h,_,x,w;s.length>=H.EF_ZIP64_SCOMP&&(h=f(s,H.EF_ZIP64_SUNCOMP),t.size===H.EF_ZIP64_OR_32&&(t.size=h)),s.length>=H.EF_ZIP64_RHO&&(_=f(s,H.EF_ZIP64_SCOMP),t.compressedSize===H.EF_ZIP64_OR_32&&(t.compressedSize=_)),s.length>=H.EF_ZIP64_DSN&&(x=f(s,H.EF_ZIP64_RHO),t.offset===H.EF_ZIP64_OR_32&&(t.offset=x)),s.length>=H.EF_ZIP64_DSN+4&&(w=s.readUInt32LE(H.EF_ZIP64_DSN),t.diskNumStart===H.EF_ZIP64_OR_16&&(t.diskNumStart=w))}return{get entryName(){return E.decode(n)},get rawEntryName(){return n},set entryName(s){n=L.toBuffer(s,E.encode);var h=n[n.length-1];i=h===47||h===92,t.fileNameLength=n.length},get efs(){return typeof g=="function"?g(this.entryName):g},get extra(){return c},set extra(s){c=s,t.extraLength=s.length,m(s)},get comment(){return E.decode(r)},set comment(s){if(r=L.toBuffer(s,E.encode),t.commentLength=r.length,r.length>65535)throw L.Errors.COMMENT_TOO_LONG()},get name(){var s=E.decode(n);return i?s.substr(s.length-1).split("/").pop():s.split("/").pop()},get isDirectory(){return i},getCompressedData:function(){return p(!1,null)},getCompressedDataAsync:function(s){p(!0,s)},setData:function(s){a=L.toBuffer(s,L.decoder.encode),!i&&a.length?(t.size=a.length,t.method=L.Constants.DEFLATED,t.crc=L.crc32(s),t.changed=!0):t.method=L.Constants.STORED},getData:function(s){return t.changed?a:u(!1,null,s)},getDataAsync:function(s,h){t.changed?s(a):u(!0,s,h)},set attr(s){t.attr=s},get attr(){return t.attr},set header(s){t.loadFromBinary(s)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=c.length;var s=t.centralHeaderToBinary(),h=L.Constants.CENHDR;return n.copy(s,h),h+=n.length,c.copy(s,h),h+=t.extraLength,r.copy(s,h),s},packLocalHeader:function(){let s=0;t.flags_efs=this.efs,t.extraLocalLength=d.length;let h=t.localHeaderToBinary(),_=Buffer.alloc(h.length+n.length+t.extraLocalLength);return h.copy(_,s),s+=h.length,n.copy(_,s),s+=n.length,d.copy(_,s),s+=d.length,_},toJSON:function(){let s=function(h){return"<"+(h&&h.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:s(e),data:s(a)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Zt=T((xi,zt)=>{"use strict";var jt=je(),lr=ke(),$=Y();zt.exports=function(o,e){var t=[],n={},r=Buffer.alloc(0),i=new lr.MainHeader,a=!1,c=null;let d=new Set,g=e,{noSort:C,decoder:E}=g;o?u(g.readEntries):a=!0;function S(){let f=new Set;for(let m of Object.keys(n)){let y=m.split("/");if(y.pop(),!!y.length)for(let s=0;s<y.length;s++){let h=y.slice(0,s+1).join("/")+"/";f.add(h)}}for(let m of f)if(!(m in n)){let y=new jt(g);y.entryName=m,y.attr=16,y.temporary=!0,t.push(y),n[y.entryName]=y,d.add(y)}}function l(){if(a=!0,n={},i.diskEntries>(o.length-i.offset)/$.Constants.CENHDR)throw $.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(i.diskEntries);for(var f=i.offset,m=0;m<t.length;m++){var y=f,s=new jt(g,o);s.header=o.slice(y,y+=$.Constants.CENHDR),s.entryName=o.slice(y,y+=s.header.fileNameLength),s.header.extraLength&&(s.extra=o.slice(y,y+=s.header.extraLength)),s.header.commentLength&&(s.comment=o.slice(y,y+s.header.commentLength)),f+=s.header.centralHeaderSize,t[m]=s,n[s.entryName]=s}d.clear(),S()}function u(f){var m=o.length-$.Constants.ENDHDR,y=Math.max(0,m-65535),s=y,h=o.length,_=-1,x=0;for(typeof g.trailingSpace=="boolean"&&g.trailingSpace&&(y=0),m;m>=s;m--)if(o[m]===80){if(o.readUInt32LE(m)===$.Constants.ENDSIG){_=m,x=m,h=m+$.Constants.ENDHDR,s=m-$.Constants.END64HDR;continue}if(o.readUInt32LE(m)===$.Constants.END64SIG){s=y;continue}if(o.readUInt32LE(m)===$.Constants.ZIP64SIG){_=m,h=m+$.readBigUInt64LE(o,m+$.Constants.ZIP64SIZE)+$.Constants.ZIP64LEAD;break}}if(_==-1)throw $.Errors.INVALID_FORMAT();i.loadFromBinary(o.slice(_,h)),i.commentLength&&(r=o.slice(x+$.Constants.ENDHDR)),f&&l()}function p(){t.length>1&&!C&&t.sort((f,m)=>f.entryName.toLowerCase().localeCompare(m.entryName.toLowerCase()))}return{get entries(){return a||l(),t.filter(f=>!d.has(f))},get comment(){return E.decode(r)},set comment(f){r=$.toBuffer(f,E.encode),i.commentLength=r.length},getEntryCount:function(){return a?t.length:i.diskEntries},forEach:function(f){this.entries.forEach(f)},getEntry:function(f){return a||l(),n[f]||null},setEntry:function(f){a||l(),t.push(f),n[f.entryName]=f,i.totalEntries=t.length},deleteFile:function(f,m=!0){a||l();let y=n[f];this.getEntryChildren(y,m).map(h=>h.entryName).forEach(this.deleteEntry)},deleteEntry:function(f){a||l();let m=n[f],y=t.indexOf(m);y>=0&&(t.splice(y,1),delete n[f],i.totalEntries=t.length)},getEntryChildren:function(f,m=!0){if(a||l(),typeof f=="object")if(f.isDirectory&&m){let y=[],s=f.entryName;for(let h of t)h.entryName.startsWith(s)&&y.push(h);return y}else return[f];return[]},getChildCount:function(f){if(f&&f.isDirectory){let m=this.getEntryChildren(f);return m.includes(f)?m.length-1:m.length}return 0},compressToBuffer:function(){a||l(),p();let f=[],m=[],y=0,s=0;i.size=0,i.offset=0;let h=0;for(let w of this.entries){let D=w.getCompressedData();w.header.offset=s;let I=w.packLocalHeader(),P=I.length+D.length;s+=P,f.push(I),f.push(D);let N=w.packCentralHeader();m.push(N),i.size+=N.length,y+=P+N.length,h++}y+=i.mainHeaderSize,i.offset=s,i.totalEntries=h,s=0;let _=Buffer.alloc(y);for(let w of f)w.copy(_,s),s+=w.length;for(let w of m)w.copy(_,s),s+=w.length;let x=i.toBinary();return r&&r.copy(x,$.Constants.ENDHDR),x.copy(_,s),o=_,a=!1,_},toAsyncBuffer:function(f,m,y,s){try{a||l(),p();let h=[],_=[],x=0,w=0,D=0;i.size=0,i.offset=0;let I=function(P){if(P.length>0){let N=P.shift(),k=N.entryName+N.extra.toString();y&&y(k),N.getCompressedDataAsync(function(B){s&&s(k),N.header.offset=w;let ae=N.packLocalHeader(),Ke=ae.length+B.length;w+=Ke,h.push(ae),h.push(B);let ye=N.packCentralHeader();_.push(ye),i.size+=ye.length,x+=Ke+ye.length,D++,I(P)})}else{x+=i.mainHeaderSize,i.offset=w,i.totalEntries=D,w=0;let N=Buffer.alloc(x);h.forEach(function(B){B.copy(N,w),w+=B.length}),_.forEach(function(B){B.copy(N,w),w+=B.length});let k=i.toBinary();r&&r.copy(k,$.Constants.ENDHDR),k.copy(N,w),o=N,a=!1,f(N)}};I(Array.from(this.entries))}catch(h){m(h)}}}}});var Kt=T((Ai,Xt)=>{"use strict";var b=Y(),F=M("path"),cr=je(),ur=Zt(),q=(...o)=>b.findLast(o,e=>typeof e=="boolean"),qt=(...o)=>b.findLast(o,e=>typeof e=="string"),fr=(...o)=>b.findLast(o,e=>typeof e=="function"),hr={noSort:!1,readEntries:!1,method:b.Constants.NONE,fs:null};Xt.exports=function(o,e){let t=null,n=Object.assign(Object.create(null),hr);o&&typeof o=="object"&&(o instanceof Uint8Array||(Object.assign(n,o),o=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(o)&&(t=o,n.method=b.Constants.BUFFER,o=void 0)),Object.assign(n,e);let r=new b(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=b.decoder),o&&typeof o=="string")if(r.fs.existsSync(o))n.method=b.Constants.FILE,n.filename=o,t=r.fs.readFileSync(o);else throw b.Errors.INVALID_FILENAME();let i=new ur(t,n),{canonical:a,sanitize:c,zipnamefix:d}=b;function g(l){if(l&&i){var u;if(typeof l=="string"&&(u=i.getEntry(F.posix.normalize(l))),typeof l=="object"&&typeof l.entryName<"u"&&typeof l.header<"u"&&(u=i.getEntry(l.entryName)),u)return u}return null}function C(l){let{join:u,normalize:p,sep:f}=F.posix;return u(F.isAbsolute(l)?"/":".",p(f+l.split("\\").join(f)+f))}function E(l){return l instanceof RegExp?(function(u){return function(p){return u.test(p)}})(l):typeof l!="function"?()=>!0:l}let S=(l,u)=>{let p=u.slice(-1);return p=p===r.sep?r.sep:"",F.relative(l,u)+p};return{readFile:function(l,u){var p=g(l);return p&&p.getData(u)||null},childCount:function(l){let u=g(l);if(u)return i.getChildCount(u)},readFileAsync:function(l,u){var p=g(l);p?p.getDataAsync(u):u(null,"getEntry failed for:"+l)},readAsText:function(l,u){var p=g(l);if(p){var f=p.getData();if(f&&f.length)return f.toString(u||"utf8")}return""},readAsTextAsync:function(l,u,p){var f=g(l);f?f.getDataAsync(function(m,y){if(y){u(m,y);return}m&&m.length?u(m.toString(p||"utf8")):u("")}):u("")},deleteFile:function(l,u=!0){var p=g(l);p&&i.deleteFile(p.entryName,u)},deleteEntry:function(l){var u=g(l);u&&i.deleteEntry(u.entryName)},addZipComment:function(l){i.comment=l},getZipComment:function(){return i.comment||""},addZipEntryComment:function(l,u){var p=g(l);p&&(p.comment=u)},getZipEntryComment:function(l){var u=g(l);return u&&u.comment||""},updateFile:function(l,u){var p=g(l);p&&p.setData(u)},addLocalFile:function(l,u,p,f){if(r.fs.existsSync(l)){u=u?C(u):"";let m=F.win32.basename(F.win32.normalize(l));u+=p||m;let y=r.fs.statSync(l),s=y.isFile()?r.fs.readFileSync(l):Buffer.alloc(0);y.isDirectory()&&(u+=r.sep),this.addFile(u,s,f,y)}else throw b.Errors.FILE_NOT_FOUND(l)},addLocalFileAsync:function(l,u){l=typeof l=="object"?l:{localPath:l};let p=F.resolve(l.localPath),{comment:f}=l,{zipPath:m,zipName:y}=l,s=this;r.fs.stat(p,function(h,_){if(h)return u(h,!1);m=m?C(m):"";let x=F.win32.basename(F.win32.normalize(p));if(m+=y||x,_.isFile())r.fs.readFile(p,function(w,D){return w?u(w,!1):(s.addFile(m,D,f,_),setImmediate(u,void 0,!0))});else if(_.isDirectory())return m+=r.sep,s.addFile(m,Buffer.alloc(0),f,_),setImmediate(u,void 0,!0)})},addLocalFolder:function(l,u,p){if(p=E(p),u=u?C(u):"",l=F.normalize(l),r.fs.existsSync(l)){let f=r.findFiles(l),m=this;if(f.length)for(let y of f){let s=F.join(u,S(l,y));p(s)&&m.addLocalFile(y,F.dirname(s))}}else throw b.Errors.FILE_NOT_FOUND(l)},addLocalFolderAsync:function(l,u,p,f){f=E(f),p=p?C(p):"",l=F.normalize(l);var m=this;r.fs.open(l,"r",function(y){if(y&&y.code==="ENOENT")u(void 0,b.Errors.FILE_NOT_FOUND(l));else if(y)u(void 0,y);else{var s=r.findFiles(l),h=-1,_=function(){if(h+=1,h<s.length){var x=s[h],w=S(l,x).split("\\").join("/");w=w.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(w)?r.fs.stat(x,function(D,I){D&&u(void 0,D),I.isFile()?r.fs.readFile(x,function(P,N){P?u(void 0,P):(m.addFile(p+w,N,"",I),_())}):(m.addFile(p+w+"/",Buffer.alloc(0),"",I),_())}):process.nextTick(()=>{_()})}else u(!0,void 0)};_()}})},addLocalFolderAsync2:function(l,u){let p=this;l=typeof l=="object"?l:{localPath:l},localPath=F.resolve(C(l.localPath));let{zipPath:f,filter:m,namefix:y}=l;m instanceof RegExp?m=(function(_){return function(x){return _.test(x)}})(m):typeof m!="function"&&(m=function(){return!0}),f=f?C(f):"",y=="latin1"&&(y=_=>_.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof y!="function"&&(y=_=>_);let s=_=>F.join(f,y(S(localPath,_))),h=_=>F.win32.basename(F.win32.normalize(y(_)));r.fs.open(localPath,"r",function(_){_&&_.code==="ENOENT"?u(void 0,b.Errors.FILE_NOT_FOUND(localPath)):_?u(void 0,_):r.findFilesAsync(localPath,function(x,w){if(x)return u(x);w=w.filter(D=>m(s(D))),w.length||u(void 0,!1),setImmediate(w.reverse().reduce(function(D,I){return function(P,N){if(P||N===!1)return setImmediate(D,P,!1);p.addLocalFileAsync({localPath:I,zipPath:F.dirname(s(I)),zipName:h(I)},D)}},u))})})},addLocalFolderPromise:function(l,u){return new Promise((p,f)=>{this.addLocalFolderAsync2(Object.assign({localPath:l},u),(m,y)=>{m&&f(m),y&&p(this)})})},addFile:function(l,u,p,f){l=d(l);let m=g(l),y=m!=null;y||(m=new cr(n),m.entryName=l),m.comment=p||"";let s=typeof f=="object"&&f instanceof r.fs.Stats;s&&(m.header.time=f.mtime);var h=m.isDirectory?16:0;let _=m.isDirectory?16384:32768;return s?_|=4095&f.mode:typeof f=="number"?_|=4095&f:_|=m.isDirectory?493:420,h=(h|_<<16)>>>0,m.attr=h,m.setData(u),y||i.setEntry(m),m},getEntries:function(l){return i.password=l,i?i.entries:[]},getEntry:function(l){return g(l)},getEntryCount:function(){return i.getEntryCount()},forEach:function(l){return i.forEach(l)},extractEntryTo:function(l,u,p,f,m,y){f=q(!1,f),m=q(!1,m),p=q(!0,p),y=qt(m,y);var s=g(l);if(!s)throw b.Errors.NO_ENTRY();var h=a(s.entryName),_=c(u,y&&!s.isDirectory?y:p?h:F.basename(h));if(s.isDirectory){var x=i.getEntryChildren(s);return x.forEach(function(I){if(I.isDirectory)return;var P=I.getData();if(!P)throw b.Errors.CANT_EXTRACT_FILE();var N=a(I.entryName),k=c(u,p?N:F.basename(N));let B=m?I.header.fileAttr:void 0;r.writeFileTo(k,P,f,B)}),!0}var w=s.getData(i.password);if(!w)throw b.Errors.CANT_EXTRACT_FILE();if(r.fs.existsSync(_)&&!f)throw b.Errors.CANT_OVERRIDE();let D=m?l.header.fileAttr:void 0;return r.writeFileTo(_,w,f,D),!0},test:function(l){if(!i)return!1;for(var u in i.entries)try{if(u.isDirectory)continue;var p=i.entries[u].getData(l);if(!p)return!1}catch{return!1}return!0},extractAllTo:function(l,u,p,f){if(p=q(!1,p),f=qt(p,f),u=q(!1,u),!i)throw b.Errors.NO_ZIP();i.entries.forEach(function(m){var y=c(l,a(m.entryName));if(m.isDirectory){r.makeDir(y);return}var s=m.getData(f);if(!s)throw b.Errors.CANT_EXTRACT_FILE();let h=p?m.header.fileAttr:void 0;r.writeFileTo(y,s,u,h);try{r.fs.utimesSync(y,m.header.time,m.header.time)}catch{throw b.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(l,u,p,f){if(f=fr(u,p,f),p=q(!1,p),u=q(!1,u),!f)return new Promise((_,x)=>{this.extractAllToAsync(l,u,p,function(w){w?x(w):_(this)})});if(!i){f(b.Errors.NO_ZIP());return}l=F.resolve(l);let m=_=>c(l,F.normalize(a(_.entryName))),y=(_,x)=>new Error(_+': "'+x+'"'),s=[],h=[];i.entries.forEach(_=>{_.isDirectory?s.push(_):h.push(_)});for(let _ of s){let x=m(_),w=p?_.header.fileAttr:void 0;try{r.makeDir(x),w&&r.fs.chmodSync(x,w),r.fs.utimesSync(x,_.header.time,_.header.time)}catch{f(y("Unable to create folder",x))}}h.reverse().reduce(function(_,x){return function(w){if(w)_(w);else{let D=F.normalize(a(x.entryName)),I=c(l,D);x.getDataAsync(function(P,N){if(N)_(N);else if(!P)_(b.Errors.CANT_EXTRACT_FILE());else{let k=p?x.header.fileAttr:void 0;r.writeFileToAsync(I,P,u,k,function(B){B||_(y("Unable to write file",I)),r.fs.utimes(I,x.header.time,x.header.time,function(ae){ae?_(y("Unable to set times",I)):_()})})}})}}},f)()},writeZip:function(l,u){if(arguments.length===1&&typeof l=="function"&&(u=l,l=""),!l&&n.filename&&(l=n.filename),!!l){var p=i.compressToBuffer();if(p){var f=r.writeFileTo(l,p,!0);typeof u=="function"&&u(f?null:new Error("failed"),"")}}},writeZipPromise:function(l,u){let{overwrite:p,perm:f}=Object.assign({overwrite:!0},u);return new Promise((m,y)=>{!l&&n.filename&&(l=n.filename),l||y("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(s=>{let h=_=>_?m(_):y("ADM-ZIP: Wasn't able to write zip file");r.writeFileToAsync(l,s,p,f,h)},y)})},toBufferPromise:function(){return new Promise((l,u)=>{i.toAsyncBuffer(l,u)})},toBuffer:function(l,u,p,f){return typeof l=="function"?(i.toAsyncBuffer(l,u,p,f),null):i.compressToBuffer()}}}});import Ce from"path";import{fileURLToPath as Or}from"url";import{styleText as V}from"util";import Sr from"@inquirer/checkbox";var ft=Je(ut(),1),{program:Hr,createCommand:Ur,createArgument:Pr,createOption:$r,CommanderError:Br,InvalidArgumentError:Mr,InvalidOptionArgumentError:Wr,Command:ht,Argument:Vr,Option:kr,Help:Gr}=ft.default;import ee from"fs";import dt from"path";import{fileURLToPath as An}from"url";var In=An(import.meta.url),Ln=dt.dirname(In),te=dt.resolve(Ln,"..","..","generated-profile-name.types.ts"),Dn=o=>o.replace(/(^\w)/g,e=>e.toUpperCase());async function mt({walletName:o,profileName:e}){let t=Dn(o),n=`export type ${t}Profiles = "${e}";`;if(ee.existsSync(te)){let r=ee.readFileSync(te,"utf-8"),i=r.match(new RegExp(`export type ${t}Profiles = ("[^"]+"(?:\\s*\\|\\s*"[^"]+")*)`));if(i){let a=i[0];if(!a.includes(`"${e}"`)){let c=a.concat(` | "${e}"`),d=r.replace(a,c);try{ee.writeFileSync(te,d)}catch(g){console.error("Error updating existing profile name type: ",g)}}}else try{ee.appendFileSync(te,`
28
28
  ${n}`,{encoding:"utf-8"})}catch(a){console.error("Error appending new profile name type: ",a)}}else try{ee.writeFileSync(te,n)}catch(r){console.error("Error writing new profile name type: ",r)}}import Tn from"path";import{pathToFileURL as vn}from"url";import{styleText as Fn}from"util";import{glob as bn}from"glob";import Nn from"path";function $e(o){let e=Nn.basename(o),t=e.match(/^([a-z0-9_]+)(?:-[a-z0-9_]+)*\.setup\.(?:ts|js|mjs)$/i);if(!t)throw new Error(`Invalid wallet setup filename: ${e} (expected "<name>[ -variant].setup.{ts,js,mjs}")`);return t[1]}var Rn=o=>o.replace(/\\/g,"/"),Hn=o=>`${Rn(Tn.resolve(o))}/**/*.setup.{ts,js,}`;async function Be({walletSetupDir:o,selectedWallets:e}){let t=Hn(o),n=(await bn(t,{dot:!0,absolute:!0,nodir:!0,windowsPathsNoEscape:!0})).sort(),r=e.length===1?e[0]:e,i=["metamask","solflare","petra","meteor","keplr","phantom"];Array.isArray(r)&&r.forEach(g=>{i.includes(g)||console.warn(Fn("magenta",`Unsupported wallet: "${g}". Supported wallets are: ${i.join(", ")}`,{validateStream:!1}))});let c=(r==="all"?n:Array.isArray(r)?n.filter(g=>r.some(C=>g.includes(C))):n.filter(g=>g.includes(r))).map(g=>({filePath:g,walletName:$e(g)}));if(!c.length||c.length===0)throw new Error([`No wallet setup file found at ${o} for wallet: "${e}".`,'Setup files must use a ".setup.{ts,js,mjs}" extension and include a valid wallet name.','Examples: "metamask.setup.ts", "solflare.setup.ts", "phantom.setup.ts", "metamask-connected.setup.ts"'].join(`
29
29
  `));return await Promise.all(c.map(async({filePath:g,walletName:C})=>{let S=await import(new URL(vn(g)).href).then(f=>f.default),{fn:l,config:u,password:p}=S;return{walletName:C,fileList:c,config:u,walletPassword:p,setupFunction:l}}))}import z from"fs";import _e from"path";import{styleText as Z}from"util";import{chromium as yr}from"@playwright/test";import Me from"path";import{fileURLToPath as Un}from"url";var Pn=Un(import.meta.url),$n=Me.dirname(Pn),Bn=Me.resolve($n,"..","../.wallet-cache");function ne(o){return Me.resolve(`${Bn}/${o}`)}import{z as fe}from"zod";var Mn=fe.object({id:fe.string(),name:fe.string()}),Wn=fe.array(Mn);async function pt(o,e){let t=await o.newPage();await t.goto("chrome://extensions");let n=await t.evaluate("chrome.management.getAll()"),r=Wn.parse(n),i=r.find(a=>a.name.toLowerCase()===e.toLowerCase());if(!i)throw new Error([`[GetExtensionId] Extension with name ${e} not found.`,`Available extensions: ${r.map(a=>a.name).join(", ")}`].join(`
30
- `));return await t.close(),i.id}var Et="wallet-setup",gt="13.22.0",re="https://github.com/amaify/chainwright/releases/download/v0.1.0/",Vn=`https://github.com/MetaMask/metamask-extension/releases/download/v${gt}/metamask-chrome-${gt}.zip`,kn=`${re}solflare-wallet-extension-v2.19.1.zip`,Gn=`${re}petra-wallet-extension-v2.2.2.zip`,jn=`${re}phantom-wallet-extension-v26.10.0.zip`,zn=`${re}meteor-wallet-extension-v0.7.0.zip`,Zn=`${re}keplr-wallet-extension-v0.13.3.zip`,he={metamask:{downloadUrl:Vn,extensionName:"MetaMask"},solflare:{downloadUrl:kn,extensionName:"Solflare Wallet"},petra:{downloadUrl:Gn,extensionName:"Petra Aptos Wallet"},phantom:{downloadUrl:jn,extensionName:"Phantom"},meteor:{downloadUrl:zn,extensionName:"Meteor Wallet"},keplr:{downloadUrl:Zn,extensionName:"Keplr"}};var Qt=Je(Kt(),1);import X from"fs";import Ze from"path";import{styleText as oe}from"util";import{createWriteStream as dr}from"fs";import{Readable as mr}from"stream";import{styleText as ze}from"util";import pr from"cli-progress";var gr=12e4;async function Yt({url:o,destination:e}){let t=new AbortController,n=setTimeout(()=>t.abort(),gr),r=await fetch(o,{redirect:"follow",signal:t.signal});r.ok||(console.error(ze("redBright",`\u274C Download failed: HTTP ${r.status}`,{validateStream:!1})),t.abort(),process.exit(1));let i=parseInt(r.headers.get("content-length")||"0",10),a=0,c=mr.fromWeb(r.body);try{let d=new pr.SingleBar({format:`Downloading ${ze("cyan","{bar}",{validateStream:!1})} {percentage}%`,clearOnComplete:!0,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});d.start(i,0,{speed:"N/A"}),await new Promise((g,C)=>{let E=dr(e);c.pipe(E),c.on("data",S=>{a+=S.length,d.update(a)}),E.on("error",C),E.on("finish",()=>{d.stop(),g(void 0)})})}catch(d){console.error(ze("redBright",`\u274C Download failed: ${d}`,{validateStream:!1})),process.exit(1)}finally{clearTimeout(n)}}var Jt=!1;async function en({downloadUrl:o,name:e,force:t}){let n=ne(e),i=he[e].extensionName,a=Ze.join(n,`${e}-extension.zip`),c=Ze.join(n,`${e}-extension`);if(t&&X.existsSync(n)&&(X.rmSync(n,{recursive:!0}),console.info(oe("magenta",`\u{1F9F9} Removed ${i} because of the force flag`,{validateStream:!1}))),X.existsSync(n)||X.mkdir(n,{recursive:!0},g=>{if(g)throw Error("Failed to create cache directory");console.info(`\u2705 ${i} Cache directory created successfully.`)}),X.existsSync(c)?console.info(`\u2705 ${i} Version is downloaded already.`):(console.info(oe("cyanBright",`\u{1F4E5} Downloading ${i} extension...`,{validateStream:!1})),await Yt({url:o,destination:a}),console.info(oe("green",`\u2705 ${e.toUpperCase()} Extension downloaded successfully.`,{validateStream:!1}))),!X.existsSync(c))console.info("\u{1F4E6} Extracting extension..."),new Qt.default(a).extractAllTo(c,!0),console.info(`\u2705 ${i} Extension extracted successfully.`);else{if(Jt)return console.info(oe("magentaBright",`Using the cached ${i} extension for profile creation.`,{validateStream:!1})),c;console.info(oe("yellow",`\u26A0\uFE0F Skipping ${i} cache creation: Cache already exists at ${c}. Use --force to overwrite.`,{validateStream:!1}))}let d=Ze.join(c,"manifest.json");if(!X.existsSync(d))throw new Error(`\u274C (${i}) Invalid extension: manifest.json not found`);return Jt=!0,c}import{styleText as Er}from"util";function qe(o){return new Promise(e=>setTimeout(e,o))}var Ee=20,_r=6e3,tn=4e3;async function Cr(o){return o.pages().find(n=>{try{return n.url().startsWith("chrome-extension://")}catch(r){return console.error("[WaitForExtensionOnLoadPage] Error checking page URL:",r),!1}})}async function nn(o,e){let t=0,n=null;if(e==="meteor")return await o.newPage();for(console.info(`Waiting ${tn}ms for browser to initialize...`),await qe(tn);t<=Ee;)try{if(console.info(`Looking for extension page (attempt ${t+1}/${Ee})...`),t===Ee)throw new Error("Extension page not found after maximum retries");let r=await Cr(o);if(r){console.info(`Found extension page after ${t+1} polling attempts`),n=r;break}r||(t++,console.info(`Extension page not found, retrying (${t}/${Ee})...`),await qe(_r))}catch(r){throw console.error("Error waiting for extension page:",r instanceof Error?r.message:"Unknown error"),new Error(`Extension failed to load properly after ${t} attempts!`)}return console.info(Er("greenBright","\u2705 Extension page is properly loaded and ready",{validateStream:!1})),n}async function Xe({walletName:o,force:e,config:t,fileList:n,walletPassword:r,setupFunction:i}){let{downloadUrl:a,extensionName:c}=he[o],d=ne(o),g=t?.profileName,C=g?`${g}`:"wallet-data",E=_e.resolve(d,"extension-id.txt"),S=_e.resolve(d,"extension-path.txt"),l=_e.resolve(d,"password.txt"),u=_e.resolve(d,C),p=await en({downloadUrl:a,name:o,force:e}),f=[`--disable-extensions-except=${p}`,`--load-extension=${p}`];if(z.existsSync(u)&&n.length>1)throw Error([Z("yellowBright",[`\u274C ${C} directory already exists for ${c}.`,`
30
+ `));return await t.close(),i.id}var Et="wallet-setup",gt="13.22.0",re="https://github.com/amaify/chainwright/releases/download/v0.1.0/",Vn=`https://github.com/MetaMask/metamask-extension/releases/download/v${gt}/metamask-chrome-${gt}.zip`,kn=`${re}solflare-wallet-extension-v2.19.1.zip`,Gn=`${re}petra-wallet-extension-v2.4.8.zip`,jn=`${re}phantom-wallet-extension-v26.10.0.zip`,zn=`${re}meteor-wallet-extension-v0.7.0.zip`,Zn=`${re}keplr-wallet-extension-v0.13.3.zip`,he={metamask:{downloadUrl:Vn,extensionName:"MetaMask"},solflare:{downloadUrl:kn,extensionName:"Solflare Wallet"},petra:{downloadUrl:Gn,extensionName:"Petra Aptos Wallet"},phantom:{downloadUrl:jn,extensionName:"Phantom"},meteor:{downloadUrl:zn,extensionName:"Meteor Wallet"},keplr:{downloadUrl:Zn,extensionName:"Keplr"}};var Qt=Je(Kt(),1);import X from"fs";import Ze from"path";import{styleText as oe}from"util";import{createWriteStream as dr}from"fs";import{Readable as mr}from"stream";import{styleText as ze}from"util";import pr from"cli-progress";var gr=12e4;async function Yt({url:o,destination:e}){let t=new AbortController,n=setTimeout(()=>t.abort(),gr),r=await fetch(o,{redirect:"follow",signal:t.signal});r.ok||(console.error(ze("redBright",`\u274C Download failed: HTTP ${r.status}`,{validateStream:!1})),t.abort(),process.exit(1));let i=parseInt(r.headers.get("content-length")||"0",10),a=0,c=mr.fromWeb(r.body);try{let d=new pr.SingleBar({format:`Downloading ${ze("cyan","{bar}",{validateStream:!1})} {percentage}%`,clearOnComplete:!0,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});d.start(i,0,{speed:"N/A"}),await new Promise((g,C)=>{let E=dr(e);c.pipe(E),c.on("data",S=>{a+=S.length,d.update(a)}),E.on("error",C),E.on("finish",()=>{d.stop(),g(void 0)})})}catch(d){console.error(ze("redBright",`\u274C Download failed: ${d}`,{validateStream:!1})),process.exit(1)}finally{clearTimeout(n)}}var Jt=!1;async function en({downloadUrl:o,name:e,force:t}){let n=ne(e),i=he[e].extensionName,a=Ze.join(n,`${e}-extension.zip`),c=Ze.join(n,`${e}-extension`);if(t&&X.existsSync(n)&&(X.rmSync(n,{recursive:!0}),console.info(oe("magenta",`\u{1F9F9} Removed ${i} because of the force flag`,{validateStream:!1}))),X.existsSync(n)||X.mkdir(n,{recursive:!0},g=>{if(g)throw Error("Failed to create cache directory");console.info(`\u2705 ${i} Cache directory created successfully.`)}),X.existsSync(c)?console.info(`\u2705 ${i} Version is downloaded already.`):(console.info(oe("cyanBright",`\u{1F4E5} Downloading ${i} extension...`,{validateStream:!1})),await Yt({url:o,destination:a}),console.info(oe("green",`\u2705 ${e.toUpperCase()} Extension downloaded successfully.`,{validateStream:!1}))),!X.existsSync(c))console.info("\u{1F4E6} Extracting extension..."),new Qt.default(a).extractAllTo(c,!0),console.info(`\u2705 ${i} Extension extracted successfully.`);else{if(Jt)return console.info(oe("magentaBright",`Using the cached ${i} extension for profile creation.`,{validateStream:!1})),c;console.info(oe("yellow",`\u26A0\uFE0F Skipping ${i} cache creation: Cache already exists at ${c}. Use --force to overwrite.`,{validateStream:!1}))}let d=Ze.join(c,"manifest.json");if(!X.existsSync(d))throw new Error(`\u274C (${i}) Invalid extension: manifest.json not found`);return Jt=!0,c}import{styleText as Er}from"util";function qe(o){return new Promise(e=>setTimeout(e,o))}var Ee=20,_r=6e3,tn=4e3;async function Cr(o){return o.pages().find(n=>{try{return n.url().startsWith("chrome-extension://")}catch(r){return console.error("[WaitForExtensionOnLoadPage] Error checking page URL:",r),!1}})}async function nn(o,e){let t=0,n=null;if(e==="meteor")return await o.newPage();for(console.info(`Waiting ${tn}ms for browser to initialize...`),await qe(tn);t<=Ee;)try{if(console.info(`Looking for extension page (attempt ${t+1}/${Ee})...`),t===Ee)throw new Error("Extension page not found after maximum retries");let r=await Cr(o);if(r){console.info(`Found extension page after ${t+1} polling attempts`),n=r;break}r||(t++,console.info(`Extension page not found, retrying (${t}/${Ee})...`),await qe(_r))}catch(r){throw console.error("Error waiting for extension page:",r instanceof Error?r.message:"Unknown error"),new Error(`Extension failed to load properly after ${t} attempts!`)}return console.info(Er("greenBright","\u2705 Extension page is properly loaded and ready",{validateStream:!1})),n}async function Xe({walletName:o,force:e,config:t,fileList:n,walletPassword:r,setupFunction:i}){let{downloadUrl:a,extensionName:c}=he[o],d=ne(o),g=t?.profileName,C=g?`${g}`:"wallet-data",E=_e.resolve(d,"extension-id.txt"),S=_e.resolve(d,"extension-path.txt"),l=_e.resolve(d,"password.txt"),u=_e.resolve(d,C),p=await en({downloadUrl:a,name:o,force:e}),f=[`--disable-extensions-except=${p}`,`--load-extension=${p}`];if(z.existsSync(u)&&n.length>1)throw Error([Z("yellowBright",[`\u274C ${C} directory already exists for ${c}.`,`
31
31
  To setup another wallet profile, add a profile name to the wallet setup function.`,Z(["blueBright","italic"],'Example: defineWalletSetup(async ({ context, walletPage }) => { ... }, { profileName: "profile-name" });'),Z("italic","You can also use the --force flag to overwrite the existing cache.")].join(`
32
32
  `),{validateStream:!1})].join(`
33
33
  `));if(z.existsSync(u))return;let m=await yr.launchPersistentContext(u,{headless:!1,args:f,slowMo:t?.slowMo??0});console.info(Z("magentaBright",`\u{1F9E9}\u{1F680} Starting Chrome extension for ${o.toUpperCase()}`,{validateStream:!1}));let y=await nn(m,o);if(!z.existsSync(E)&&!z.existsSync(S)){let s=await pt(m,c);console.info(Z("magentaBright",`\u{1F194} ${c} extension ID: ${s}`,{validateStream:!1})),z.writeFileSync(E,s,"utf-8"),console.info(Z("cyanBright",`\u{1F4BE} Saved extension ID to: ${E}`,{validateStream:!1})),z.writeFileSync(S,p,"utf-8"),console.info(Z("blueBright",`\u{1F4C1} Saved extension Path to: ${S}`,{validateStream:!1})),z.writeFileSync(l,r,"utf-8"),console.info(Z("yellowBright",`\u{1F511} Saved ${o} password to: ${l}`,{validateStream:!1}))}try{await i({context:m,walletPage:y})}catch(s){await m.close(),z.rmSync(d,{force:!0,recursive:!0}),console.error("Error setting up wallet: ",s.message)}await m.close()}var wr=Or(import.meta.url),xr=Ce.dirname(wr),Ar=Ce.join(xr,"..","tests",Et),se=2;async function Ir(){let o=new ht;o.name(V("yellow","Chainwright")).description(V("green","A CLI tool for setting up wallet cache for E2E testing of web3 applications")).version(V("blue","0.0.0")),o.command("chainwright").argument("[dir]","Directory containing the wallet setup functions",Ce.resolve(Ar)).option("--headless","Build cache in the headless browser mode. Alternatively, set the `HEADLESS` env variable to `true`",!1).option("-f, --force","Force the creation of cache even if it already exists",!1).option("-a, --all","Setup all wallets","all").option("--kp, --keplr","Setup Keplr","keplr").option("-m, --metamask","Setup MetaMask","metamask").option("--mt, --meteor","Setup Meteor","meteor").option("--pt, --petra","Setup Petra","petra").option("--ph, --phantom","Setup Phantom","phantom").option("-s, --solflare","Setup Solflare","solflare").option("--wls, --wallets <wallets...>","Specify wallets to setup (e.g., --wallets keplr metamask)").action(async(e,t)=>{let n=["all","metamask","solflare","petra","meteor","keplr","phantom"],r=Object.keys(t).filter(E=>n.includes(E)?t[E]===!0:!1),i=r.length>0,a=t.wallets,c=a||(i?r:await Sr({message:"Select the wallet you want to setup",choices:[{name:"All",value:"all"},{name:"Keplr",value:"keplr"},{name:"MetaMask",value:"metamask"},{name:"Meteor",value:"meteor"},{name:"Petra",value:"petra"},{name:"Phantom",value:"phantom"},{name:"Solflare",value:"solflare"}],validate:E=>{let S=E.map(l=>l.value);return S.includes("all")&&S.length>1?'Select either "All" or specific wallets, not both.':!0},pageSize:10})),d=e,g=o.commands[0]?.args??[];g[0]&&(d=Ce.resolve(process.cwd(),g[0])),t.headless&&(process.env.HEADLESS=!0);let C=await Be({walletSetupDir:d,selectedWallets:c});for(let{walletName:E,config:S,walletPassword:l,setupFunction:u,fileList:p}of C)try{console.info(V("cyanBright",`
@@ -1,7 +1,7 @@
1
- import{expect as $e}from"@playwright/test";function y(t){return new Promise(e=>setTimeout(e,t))}async function M(t){await t.waitForLoadState("load",{timeout:15e3}),await t.waitForLoadState("domcontentloaded",{timeout:15e3})}import _e from"fs";import ua from"path";import xe from"path";import{fileURLToPath as ia}from"url";var ca=ia(import.meta.url),sa=xe.dirname(ca),la=xe.resolve(sa,"..","../.wallet-cache");function x(t){return xe.resolve(`${la}/${t}`)}async function k(t){let e=x(t),a=ua.resolve(e,"password.txt");try{if(!_e.existsSync(a))throw new Error("\u274C password.txt not found. Run setup script first.");return _e.readFileSync(a,"utf-8")}catch(o){throw new Error(`\u274C Failed to get ${t} password from cache: ${o.message}`)}}import{expect as ma}from"@playwright/test";async function D({context:t,path:e,locator:a}){let o;if(await ma.poll(async()=>(o=t.pages().find(n=>n.url().match(e)),!!o),{timeout:3e4}).toBe(!0),!o)throw new Error(`Popup page with path ${e} not found in context.`);return await pa(o,a),await o.setViewportSize({width:360,height:592}),o}async function pa(t,e){await t.waitForLoadState("load",{timeout:4e4}),await t.waitForLoadState("domcontentloaded",{timeout:4e4}),await t.locator(e).first().waitFor({state:"attached",timeout:4e4})}import Ve from"fs";import da from"path";async function U(t){let e=x(t),a=da.resolve(e,"extension-id.txt");try{if(!Ve.existsSync(a))throw new Error("\u274C extension-id.txt not found. Run setup script first.");return Ve.readFileSync(a,"utf-8")}catch(o){throw new Error(`\u274C Failed to get ${t} extension ID from cache: ${o.message}`)}}var H=class{name="keplr";onboardingPath="register.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/sidePanel.html`}async onboardingUrl(){return`chrome-extension://${await this.extensionId()}/${this.onboardingPath}`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[data-simplebar='init']"})}};var j={importExistingWalletButton:"button:has-text('Import an existing wallet')",usePrivateKeyButton:"button:has-text('Use recovery phrase or private key')",privateKeyTabButton:"button:has-text('Private key')",privateKeyInput:"input[type='password']",importButton:"button:has-text('Import')",walletNameInput:"input[name='name']",walletPasswordInput:"input[name='password']",confirmWalletPasswordInput:"input[name='confirmPassword']",nextButton:"button:has-text('Next')",searchNetworkInput:"input[placeholder='Search networks']",saveButton:"button:has-text('Save')",finishButton:"button:has-text('Finish')"};function wa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ht({page:t,privateKey:e,walletName:a,chains:o,mode:n="onboard"}){let r=await k("keplr"),i=new H;if(await t.locator(j.importExistingWalletButton).click(),await t.locator(j.usePrivateKeyButton).click(),await t.getByRole("button",{name:"Private key",exact:!0}).click(),await t.locator(j.privateKeyInput).fill(e),await t.getByRole("button",{name:"Import",exact:!0}).click(),await t.locator(j.walletNameInput).fill(a),n==="onboard"){let C=t.locator(j.walletPasswordInput),R=t.locator(j.confirmWalletPasswordInput);await C.fill(r),await R.fill(r)}await t.locator(j.nextButton).click();let d=t.locator("div:has-text('All Native Chains')").nth(-4),g=t.locator("div[cursor='pointer']:has-text('Cosmos Hub')"),f=await d.locator("input[type='checkbox']").getAttribute("checked"),h=await g.locator("input[type='checkbox']").getAttribute("checked");f!==null&&await d.click(),h!==null&&await g.click();let S=t.locator(j.searchNetworkInput);for(let C of o){await S.fill(C);let V=t.locator("div[class='simplebar-content']").locator("div[cursor] > div").first().locator("div").filter({hasText:new RegExp(`^${wa(C)}$`,"i")}).nth(2).locator("../../../../..");await V.waitFor({state:"visible",timeout:2e4}),await V.locator("input[type='checkbox']").getAttribute("checked")===null&&await V.click()}let A=t.locator(j.saveButton);if(await A.scrollIntoViewIfNeeded(),await A.click(),await y(2e3),n==="onboard"){await t.goto(await i.indexUrl());return}if(n==="add-account-single"){let C=t.locator(j.finishButton);await C.waitFor({state:"visible",timeout:2e4}),await $e(C).toBeEnabled({timeout:2e4}),await C.click()}}async function qt(t){let a=await new H().onboardingUrl();await t.getByRole("link",{name:"Settings",exact:!0}).click(),await t.locator("div[cursor='pointer']").first().click(),await t.getByRole("button",{name:"Add Wallet",exact:!0}).click();let i;if(await $e.poll(async()=>(i=t.context().pages().find(c=>c.url().match(a)),!!i),{timeout:3e4}).toBe(!0).catch(c=>{console.error(`Failed to find onboarding page with URL matching ${a}. Original error: ${c}`)}),!i)throw new Error(`Onboarding page not found. Expected URL: ${a}`);return await M(i),await i.bringToFront(),i}async function Le({page:t,privateKey:e,chains:a,walletName:o,mode:n}){let r=await qt(t);await ht({page:r,privateKey:e,walletName:o,chains:a,mode:n}),await t.locator("div:has(div:has-text('Select Wallet'))").nth(-4).locator("div:has(> div > svg)").first().click(),await t.getByRole("link",{name:"Home",exact:!0}).click()}import{expect as fa}from"@playwright/test";var Yt={approveButton:"button:has-text('Approve')",rejectButton:"button[color='secondary']"};async function Oe(t){let e=t.locator(Yt.approveButton);await fa(e).toBeEnabled({timeout:2e4}),await e.click()}async function De(t){t.getByRole("button",{name:"Approve",exact:!0}).click(),await y(1e3)}import{expect as ga}from"@playwright/test";import G from"zod";var Ue=G.discriminatedUnion("chain",[G.object({chain:G.literal(["Injective","Injective (Testnet)","Polygon"]),walletName:G.string().min(1,"Wallet name cannot be an empty string")}),G.object({chain:G.literal(["Bitcoin","Bitcoin Signet","Bitcoin Testnet"]),chainTag:G.literal(["Taproot","Native Segwit"]),walletName:G.string().min(1,"Wallet name cannot be an empty string")})]),Ke=G.object({currentAccountName:G.string().min(1,"Current account name cannot be an empty string"),newAccountName:G.string().min(1,"New account name cannot be an empty string")});async function He({page:t,...e}){let a=Ue.parse({...e});await t.getByRole("textbox",{name:"Search for asset or chain (i.e. ATOM, Cosmos)",exact:!0}).fill(a.chain);let n=t.locator(`div:has-text("${a.chain}")`).nth(-2).filter({hasNot:t.locator("span")});if(await n.waitFor({state:"attached",timeout:2e4}),!await n.isVisible().catch(()=>!1))throw Error(`Make sure "${a.chain}" is activated.`);let i=await n.locator("div").all();ga(i.length).toBeGreaterThan(0),await t.locator(`div:has(div:has-text('${a.walletName}'))`).nth(-3).locator("div:has(> div > svg)").click();let l=t.locator("div:has(> div[data-simplebar='init'])").last(),m=l.locator("div:has(> div > input)").locator("input");await m.fill(a.chain);let w=await l.locator("div[cursor='pointer']",{hasText:a.chain}).all(),d;for(let f of w){let h;"chainTag"in e&&(h=e.chainTag);let S=f.locator("div",{hasText:a.chain}).last(),A=h?f.locator("div",{hasText:h}).last():null,R=(A?await A?.isVisible().catch(()=>!1):!1)?await A?.textContent():null,V=await S.textContent(),nt=R?`${V} ${R}`:V,et=h?`${a.chain} ${h}`:a.chain;if(nt===et){d=S.locator("xpath=../../../.."),await m.clear();break}}if(!d)throw Error(`Address for ${a.walletName} account on "${a.chain}" chain not found.`);return await d.hover(),await d.scrollIntoViewIfNeeded(),await d.click(),await t.evaluate(async()=>await navigator.clipboard.readText())}var Vt={openSidebarMenuButton:"div[cursor='pointer']:has(> div[cursor='pointer'])",menuPopupContent:"div[id='modal-root-3']",lockWalletButton:"div:has(> div:has-text('Lock Wallet'))",settingsButton:"div:has(a[href='#/settings'])"},Be={unlockButton:"button[type='submit']:has-text('Unlock')",passwordInput:"input[placeholder='Type Your Password']"};async function je(t){await t.locator(Vt.openSidebarMenuButton).click(),await t.locator(Vt.lockWalletButton).nth(-1).click(),await t.getByText("Welcome Back").waitFor({state:"visible",timeout:3e4})}import{styleText as Ge}from"util";import{expect as ha}from"@playwright/test";async function Qt(t,e){let a=t.locator("div[color]").nth(1);if(await a.textContent()===e){console.info(`
1
+ import{expect as $e}from"@playwright/test";function y(t){return new Promise(e=>setTimeout(e,t))}async function M(t){await t.waitForLoadState("load",{timeout:15e3}),await t.waitForLoadState("domcontentloaded",{timeout:15e3})}import _e from"fs";import ua from"path";import xe from"path";import{fileURLToPath as ia}from"url";var ca=ia(import.meta.url),sa=xe.dirname(ca),la=xe.resolve(sa,"..","../.wallet-cache");function x(t){return xe.resolve(`${la}/${t}`)}async function k(t){let e=x(t),a=ua.resolve(e,"password.txt");try{if(!_e.existsSync(a))throw new Error("\u274C password.txt not found. Run setup script first.");return _e.readFileSync(a,"utf-8")}catch(o){throw new Error(`\u274C Failed to get ${t} password from cache: ${o.message}`)}}import{expect as ma}from"@playwright/test";async function D({context:t,path:e,locator:a}){let o;try{await ma.poll(async()=>(o=t.pages().filter(n=>n.url().startsWith("chrome-extension://")).find(n=>n.url().match(e)),!!o),{timeout:3e4}).toBe(!0)}catch{let n=t.pages().filter(r=>r.url().startsWith("chrome-extension://")).map(r=>r.url());throw new Error(`Popup page with path "${e}" not found in context after 30s. Pages in context: ${JSON.stringify(n)}`)}if(!o)throw new Error(`Popup page with path ${e} not found in context.`);return await pa(o,a),await o.setViewportSize({width:360,height:592}),o}async function pa(t,e){await t.waitForLoadState("load",{timeout:4e4}),await t.waitForLoadState("domcontentloaded",{timeout:4e4}),await t.locator(e).first().waitFor({state:"attached",timeout:4e4})}import Ve from"fs";import da from"path";async function U(t){let e=x(t),a=da.resolve(e,"extension-id.txt");try{if(!Ve.existsSync(a))throw new Error("\u274C extension-id.txt not found. Run setup script first.");return Ve.readFileSync(a,"utf-8")}catch(o){throw new Error(`\u274C Failed to get ${t} extension ID from cache: ${o.message}`)}}var H=class{name="keplr";onboardingPath="register.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/sidePanel.html`}async onboardingUrl(){return`chrome-extension://${await this.extensionId()}/${this.onboardingPath}`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[data-simplebar='init']"})}};var j={importExistingWalletButton:"button:has-text('Import an existing wallet')",usePrivateKeyButton:"button:has-text('Use recovery phrase or private key')",privateKeyTabButton:"button:has-text('Private key')",privateKeyInput:"input[type='password']",importButton:"button:has-text('Import')",walletNameInput:"input[name='name']",walletPasswordInput:"input[name='password']",confirmWalletPasswordInput:"input[name='confirmPassword']",nextButton:"button:has-text('Next')",searchNetworkInput:"input[placeholder='Search networks']",saveButton:"button:has-text('Save')",finishButton:"button:has-text('Finish')"};function wa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ht({page:t,privateKey:e,walletName:a,chains:o,mode:n="onboard"}){let r=await k("keplr"),i=new H;if(await t.locator(j.importExistingWalletButton).click(),await t.locator(j.usePrivateKeyButton).click(),await t.getByRole("button",{name:"Private key",exact:!0}).click(),await t.locator(j.privateKeyInput).fill(e),await t.getByRole("button",{name:"Import",exact:!0}).click(),await t.locator(j.walletNameInput).fill(a),n==="onboard"){let C=t.locator(j.walletPasswordInput),R=t.locator(j.confirmWalletPasswordInput);await C.fill(r),await R.fill(r)}await t.locator(j.nextButton).click();let d=t.locator("div:has-text('All Native Chains')").nth(-4),g=t.locator("div[cursor='pointer']:has-text('Cosmos Hub')"),f=await d.locator("input[type='checkbox']").getAttribute("checked"),h=await g.locator("input[type='checkbox']").getAttribute("checked");f!==null&&await d.click(),h!==null&&await g.click();let S=t.locator(j.searchNetworkInput);for(let C of o){await S.fill(C);let V=t.locator("div[class='simplebar-content']").locator("div[cursor] > div").first().locator("div").filter({hasText:new RegExp(`^${wa(C)}$`,"i")}).nth(2).locator("../../../../..");await V.waitFor({state:"visible",timeout:2e4}),await V.locator("input[type='checkbox']").getAttribute("checked")===null&&await V.click()}let A=t.locator(j.saveButton);if(await A.scrollIntoViewIfNeeded(),await A.click(),await y(2e3),n==="onboard"){await t.goto(await i.indexUrl());return}if(n==="add-account-single"){let C=t.locator(j.finishButton);await C.waitFor({state:"visible",timeout:2e4}),await $e(C).toBeEnabled({timeout:2e4}),await C.click()}}async function qt(t){let a=await new H().onboardingUrl();await t.getByRole("link",{name:"Settings",exact:!0}).click(),await t.locator("div[cursor='pointer']").first().click(),await t.getByRole("button",{name:"Add Wallet",exact:!0}).click();let i;if(await $e.poll(async()=>(i=t.context().pages().find(c=>c.url().match(a)),!!i),{timeout:3e4}).toBe(!0).catch(c=>{console.error(`Failed to find onboarding page with URL matching ${a}. Original error: ${c}`)}),!i)throw new Error(`Onboarding page not found. Expected URL: ${a}`);return await M(i),await i.bringToFront(),i}async function Le({page:t,privateKey:e,chains:a,walletName:o,mode:n}){let r=await qt(t);await ht({page:r,privateKey:e,walletName:o,chains:a,mode:n}),await t.locator("div:has(div:has-text('Select Wallet'))").nth(-4).locator("div:has(> div > svg)").first().click(),await t.getByRole("link",{name:"Home",exact:!0}).click()}import{expect as fa}from"@playwright/test";var Yt={approveButton:"button:has-text('Approve')",rejectButton:"button[color='secondary']"};async function Oe(t){let e=t.locator(Yt.approveButton);await fa(e).toBeEnabled({timeout:2e4}),await e.click()}async function De(t){t.getByRole("button",{name:"Approve",exact:!0}).click(),await y(1e3)}import{expect as ga}from"@playwright/test";import G from"zod";var Ue=G.discriminatedUnion("chain",[G.object({chain:G.literal(["Injective","Injective (Testnet)","Polygon"]),walletName:G.string().min(1,"Wallet name cannot be an empty string")}),G.object({chain:G.literal(["Bitcoin","Bitcoin Signet","Bitcoin Testnet"]),chainTag:G.literal(["Taproot","Native Segwit"]),walletName:G.string().min(1,"Wallet name cannot be an empty string")})]),Ke=G.object({currentAccountName:G.string().min(1,"Current account name cannot be an empty string"),newAccountName:G.string().min(1,"New account name cannot be an empty string")});async function He({page:t,...e}){let a=Ue.parse({...e});await t.getByRole("textbox",{name:"Search for asset or chain (i.e. ATOM, Cosmos)",exact:!0}).fill(a.chain);let n=t.locator(`div:has-text("${a.chain}")`).nth(-2).filter({hasNot:t.locator("span")});if(await n.waitFor({state:"attached",timeout:2e4}),!await n.isVisible().catch(()=>!1))throw Error(`Make sure "${a.chain}" is activated.`);let i=await n.locator("div").all();ga(i.length).toBeGreaterThan(0),await t.locator(`div:has(div:has-text('${a.walletName}'))`).nth(-3).locator("div:has(> div > svg)").click();let l=t.locator("div:has(> div[data-simplebar='init'])").last(),m=l.locator("div:has(> div > input)").locator("input");await m.fill(a.chain);let w=await l.locator("div[cursor='pointer']",{hasText:a.chain}).all(),d;for(let f of w){let h;"chainTag"in e&&(h=e.chainTag);let S=f.locator("div",{hasText:a.chain}).last(),A=h?f.locator("div",{hasText:h}).last():null,R=(A?await A?.isVisible().catch(()=>!1):!1)?await A?.textContent():null,V=await S.textContent(),nt=R?`${V} ${R}`:V,et=h?`${a.chain} ${h}`:a.chain;if(nt===et){d=S.locator("xpath=../../../.."),await m.clear();break}}if(!d)throw Error(`Address for ${a.walletName} account on "${a.chain}" chain not found.`);return await d.hover(),await d.scrollIntoViewIfNeeded(),await d.click(),await t.evaluate(async()=>await navigator.clipboard.readText())}var Vt={openSidebarMenuButton:"div[cursor='pointer']:has(> div[cursor='pointer'])",menuPopupContent:"div[id='modal-root-3']",lockWalletButton:"div:has(> div:has-text('Lock Wallet'))",settingsButton:"div:has(a[href='#/settings'])"},Be={unlockButton:"button[type='submit']:has-text('Unlock')",passwordInput:"input[placeholder='Type Your Password']"};async function je(t){await t.locator(Vt.openSidebarMenuButton).click(),await t.locator(Vt.lockWalletButton).nth(-1).click(),await t.getByText("Welcome Back").waitFor({state:"visible",timeout:3e4})}import{styleText as Ge}from"util";import{expect as ha}from"@playwright/test";async function Qt(t,e){let a=t.locator("div[color]").nth(1);if(await a.textContent()===e){console.info(`
2
2
  Already on ${e} account. No need to switch.`);return}await a.click();let n=t.locator("div[class='simplebar-content'] > div").locator("> div",{hasText:e});if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);let i=t.locator("div:has-text('Select Wallet')").last();await n.click(),await i.waitFor({state:"detached",timeout:3e4})}async function ke({page:t,onboard:e}){if(console.info(Ge("yellowBright",`
3
3
  Keplr onboarding started...`,{validateStream:!1})),e.length===1)for(let{privateKey:a,walletName:o,chains:n}of e)await ht({page:t,privateKey:a,walletName:o,chains:n,mode:"onboard"});if(e.length>1){let a=e[0];if(a){let{privateKey:u,walletName:m,chains:p}=a;await ht({page:t,privateKey:u,walletName:m,chains:p,mode:"onboard"})}let o=e.slice(1);for(let{privateKey:u,walletName:m,chains:p}of o){let w=await qt(t);await ht({page:w,privateKey:u,walletName:m,chains:p,mode:"add-account-single"})}await t.locator("div",{hasText:"Select Wallet"}).last().locator("../../..").locator("div > svg").click(),await t.getByRole("link",{name:"Home",exact:!0}).click();let c=t.locator(Vt.openSidebarMenuButton);await ha(c).toBeVisible({timeout:3e4});let s=e.at(-1)?.walletName,l=e[0]?.walletName;s&&l&&await Qt(t,l)}await y(3e3),console.info(Ge("greenBright","\u2728 Keplr onboarding completed successfully",{validateStream:!1}))}async function ze(t){let e=t.locator(Yt.rejectButton);await e.waitFor({state:"visible",timeout:2e4}),await e.click()}async function qe({page:t,currentAccountName:e,newAccountName:a}){let o=Ke.parse({currentAccountName:e,newAccountName:a});await t.getByRole("link",{name:"Settings",exact:!0}).click(),await t.locator("div[cursor='pointer']").first().click();let i=t.locator("div",{hasText:o.currentAccountName}).nth(-4);if(!await i.isVisible().catch(()=>!1))throw Error(`Account with name "${o.currentAccountName}" not found`);await i.locator("div[cursor='pointer'] svg").click(),await t.locator("div > div[cursor='pointer'] > div:has-text('Change Wallet Name')").last().click(),await t.locator("input[name='name']").fill(o.newAccountName),await t.locator("button:has-text('Save')").click()}async function Xt(t){let e=await k("keplr");await t.locator(Be.passwordInput).fill(e),await t.locator(Be.unlockButton).click(),await t.locator("div:has-text('Deposit')").last().waitFor({state:"visible",timeout:3e4})}var st=class extends H{page;constructor(e){super(),this.page=e}async onboard(e){await ke({page:this.page,onboard:e})}async unlock(){await Xt(this.page)}async lock(){await je(this.page)}async renameAccount({currentAccountName:e,newAccountName:a}){await qe({page:this.page,currentAccountName:e,newAccountName:a})}async switchAccount(e){await Qt(this.page,e)}async getAccountAddress({...e}){return await He({page:this.page,...e})}async addAccount({chains:e,privateKey:a,walletName:o,mode:n="add-account-multiple"}){await Le({page:this.page,privateKey:a,walletName:o,chains:e,mode:n})}async connectToApp(){await De(await this.promptPage(this.page.context()))}async confirmTransaction(){await Oe(await this.promptPage(this.page.context()))}async rejectTransaction(){await ze(await this.promptPage(this.page.context()))}};import Xe from"fs";import Sa from"path";import{test as va,chromium as Ia}from"@playwright/test";import be from"path";import{fileURLToPath as ya}from"url";var xa=ya(import.meta.url),Ba=be.dirname(xa),ka=be.resolve(Ba,"..","../.wallet-context");async function v(t){return be.resolve(ka,`${t}`)}import{expect as ba}from"@playwright/test";async function E(t,e){let a=await t.newPage();return await ba(async()=>{await a.goto(e),await M(a)}).toPass(),a}async function $(t,e){let a=await e.newPage();for(let{origin:o,localStorage:n}of t){let r=a.mainFrame();await r.goto(o),await r.evaluate(i=>{i.forEach(({name:c,value:s})=>{window.localStorage.setItem(c,s)})},n)}await a.close()}import Pa from"fs/promises";async function Ye(t){await Pa.rm(t,{maxRetries:50,retryDelay:500,recursive:!0,force:!0})}var Aa=35e3;async function b(t,e){try{await Promise.race([t.close(),new Promise((a,o)=>setTimeout(()=>o(new Error("Context close timed out")),Aa))])}catch(a){console.warn(`Browser context close did not complete cleanly: ${a.message}`)}try{await Ye(e)}catch(a){console.error(`Failed to remove temporary context directory at ${e}. Error:`,a)}}import Qe from"fs";import Ca from"path";async function I(t){try{let e=x(t),a=Ca.resolve(e,"extension-path.txt");if(!Qe.existsSync(a))throw new Error("\u274C extension-path.txt not found. Run setup script first.");let o=Qe.readFileSync(a,"utf-8").trim();if(!o)throw new Error("\u274C extension-path.txt is empty. Run setup script first.");return o}catch(e){throw new Error(`\u274C Failed to get ${t} extension path: ${e.message}`)}}var yt,xi=({slowMo:t=0,profileName:e}={})=>va.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new H,i=x(r.name),c=await I(r.name),s=Sa.resolve(i,e??"wallet-data");if(!Xe.existsSync(s))throw new Error("\u274C Cache for Keplr wallet data not found. Create it first");Xe.cpSync(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await Ia.launchPersistentContext(o,{headless:!1,args:l,slowMo:process.env.HEADLESS?0:t});await u.grantPermissions(["clipboard-read"]);let{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl();yt=u.pages().find(g=>g.url().startsWith(w))||await E(u,w),await M(yt);for(let g of u.pages()){let f=g.url();(f.includes("about:blank")||f.includes(r.onboardingPath))&&await g.close()}await yt.bringToFront(),await Xt(yt),await n(u),await b(u,o)},keplrPage:async({context:a},o)=>{await o(yt)},keplr:async({context:a},o)=>{let n=new st(yt);await o(n)}});import{test as Fa}from"@playwright/test";import Ze from"fs";import Ta from"path";import{chromium as Wa}from"@playwright/test";async function xt({wallet:t,workerInfo:e,profileName:a,slowMo:o}){let n=await v(e.workerIndex.toString()),r=x(t.name),i=Ta.resolve(r,a??"wallet-data");if(!Ze.existsSync(i))throw new Error(`Cache for ${t.name} does not exist. Create it first!`);Ze.cpSync(i,n,{recursive:!0,force:!0});let c=await I(t.name),s=await Wa.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:o}),l=await t.indexUrl(),u=s.pages()[0];return u||(u=await s.newPage()),await u.goto(l),{context:s,walletPage:u,contextPath:n}}var Mi=({slowMo:t,profileName:e,dappUrl:a}={})=>Fa.extend({workerScopeContents:[async({browser:o},n,r)=>{let i=new H,{context:c,contextPath:s,walletPage:l}=await xt({wallet:i,workerInfo:r,profileName:e,slowMo:t});await c.grantPermissions(["clipboard-read"]);for(let m of c.pages())m.url().includes("about:blank")&&await m.close();let u=new st(l);await u.unlock(),await n({wallet:u,walletPage:l,context:c}),await b(c,s)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],keplrPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},keplr:async({workerScopeContents:o},n)=>{let r=new st(o.walletPage);await n(r)}});import{expect as L}from"@playwright/test";import to from"zod";import{test as Na}from"@playwright/test";function Je(t,e){t&&(console.warn(`
4
- \u26A0\uFE0F Skipping test: ${e}`),Na.skip())}var P={buyButton:"eth-overview-buy",swapButton:"eth-overview-swap",sendButton:"eth-overview-send",receiveButton:"eth-overview-receive",openSettingsButton:"account-options-menu-button",accountMenuButton:"account-menu-icon",accountCell:"multichain-account-cell-entropy",openNetworkSelectorButton:"sort-by-networks",accountAddressesButton:"networks-subtitle-test-id",accountAddressesElements:"multichain-address-row",accountAddressQRCode:"multichain-address-row-qr-button"},Bt={lockButton:"global-menu-lock",networksButton:"global-menu-networks"},$t={passwordInput:"unlock-password",unlockButton:"unlock-submit"},ot={accountOptionsMenuButton:"multichain-account-cell-end-accessory",accountDetailsLabel:"Account details",renameAccountLabel:"Rename",addressesLabel:"Addresses",pinToTopLabel:"Pin to top",hideAccountLabel:"Hide account",backButton:"back",addMultichainAccountButton:"add-multichain-account-button",addWalletButton:"account-list-add-wallet-button",importWalletButton:"add-wallet-modal-import-wallet",importAccountButton:"add-wallet-modal-import-account"};var F={createWalletButton:"onboarding-create-wallet",importWalletButton:"onboarding-import-wallet",useSecretRecoveryPhraseButton:"onboarding-create-with-srp-button",createNewPasswordInput:"create-password-new-input",confirmNewPasswordInput:"create-password-confirm-input",confirmPasswordCheckbox:"create-password-terms",createPasswordButton:"create-password-submit",revealSecretRecoveryPhraseButton:"recovery-phrase-reveal",recoveryPhraseRemindMeLaterButton:"recovery-phrase-remind-later",metamaskMetricsIAgreeButton:"metametrics-i-agree",onboardingDoneButton:"onboarding-complete-done",importUsingSecretRecoveryPhraseButton:"onboarding-import-with-srp-button",secretRecoveryPhraseTextAreaInput:"srp-input-import__srp-note",importWalletConfirmButton:"import-srp-confirm",importAccountConfirmButton:"import-account-confirm-button",importSRPError:"bannerAlert"};async function eo({page:t,privateKey:e,accountName:a}){let o=to.string().min(1,"Account name cannot be an empty string").trim().parse(a),n=to.string().min(1,"Private key cannot be an empty string").trim().parse(e),r=t.getByTestId(P.accountMenuButton);await L(r).toBeVisible({timeout:3e4}),await r.click(),await L(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let i=t.getByTestId(ot.addWalletButton),c=await i.textContent();c?.includes("Syncing")&&await L.poll(async()=>(await i.textContent())?.trim()??"",{timeout:12e4}).not.toBe(c),await L(i).toBeEnabled({timeout:6e4}),await i.click();let s=t.getByRole("dialog");await L(s).toContainText(/add wallet/i),await t.getByTestId(ot.importAccountButton).click(),await t.locator("input[id='private-key-box']").fill(n);let m=t.getByTestId(F.importAccountConfirmButton);await L(m).toBeEnabled(),await m.click();let p=t.getByTestId(F.importSRPError),w=await p.isVisible().catch(()=>!1);w&&Je(w,`${(await p.textContent())?.split(".")[0]}`);let d=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])"),g=(await d.textContent())?.split("$")[0];g&&await Ma({page:t,accountName:o,activeAccountLocator:d,activeAccountName:g}),await t.locator("button[aria-label='Back']").first().click()}async function Ma({page:t,accountName:e,activeAccountLocator:a,activeAccountName:o}){let n=a.locator(`div[aria-label='${o} options']`);await L(n).toBeVisible(),await n.click(),await L(t.getByRole("tooltip")).toBeVisible();let r=t.locator(`div[aria-label='${ot.renameAccountLabel}']`);await L(r).toBeVisible(),await r.click();let i=t.getByRole("dialog"),c=i.getByRole("heading",{name:/rename/i});await L(c).toBeVisible();let s=i.getByRole("textbox");await L(s).toBeVisible(),await s.fill(e);let l=i.getByRole("button",{name:/confirm/i});await L(l).toBeEnabled(),await l.click(),await i.waitFor({state:"detached",timeout:2e4});let u=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])");await L(u).toContainText(e)}import{expect as Lt}from"@playwright/test";import kt from"zod";var oo=kt.object({networkName:kt.string().min(1,"Network name cannot be an empty string"),rpcUrl:kt.url(),chainId:kt.number().or(kt.string().includes("0x")),currencySymbol:kt.string().toUpperCase().min(1,"Currency symbol cannot be an empty string")});import{expect as Ea}from"@playwright/test";async function Zt(t){let e=t.locator("div:has(> p[data-testid='notifications-tag-counter__unread-dot'])"),a=t.getByTestId(P.openSettingsButton);await e.isVisible().catch(()=>!1)?await e.click():(await Ea(a).toBeVisible(),await a.click())}async function ao({page:t,...e}){let{chainId:a,currencySymbol:o,networkName:n,rpcUrl:r}=oo.parse({...e},{reportInput:!0});await Zt(t),await t.getByTestId(Bt.networksButton).click();let c=t.locator("section[role='dialog']");await Lt(c).toContainText(/manage networks/i),await t.getByRole("button",{name:/add a custom network/i}).click(),await Lt(c).toContainText(/Add a custom network/i);let l=t.getByTestId("network-form-network-name"),u=t.getByTestId("test-add-rpc-drop-down"),m=t.getByTestId("network-form-chain-id"),p=t.getByTestId("network-form-ticker-input");await l.fill(n),await u.click(),await t.getByRole("tooltip").locator("div:has(> button:has-text('Add RPC URL'))").click(),await Lt(c).toContainText(/Add RPC URL/i);let g=t.getByTestId("rpc-url-input-test"),f=t.getByRole("button",{name:/Add URL/i});await g.fill(r),await f.click(),await Lt(c).toContainText(/Add a custom network/i);let h=t.getByTestId("network-form-chain-id-error");if(await h.isVisible().catch(()=>!1)){let C=await h.textContent();throw Error(`RPC error: ${C}`)}await m.fill(`${a}`),await p.fill(o);let A=t.getByRole("button",{name:/save/i});await Lt(A).toBeEnabled(),await A.click()}import{expect as no}from"@playwright/test";var Jt={confirmButton:"confirm-footer-button",cancelButton:"confirm-footer-cancel-button"};async function ro(t,e){let a=t.getByTestId(Jt.confirmButton);await y(2e3);let n=(await a.textContent())?.includes("Review alert"),r=await a.isDisabled().catch(()=>!1);if(n&&r){await t.getByTestId("edit-gas-fees-row").locator("> div").first().click();let u=t.getByRole("dialog");await no(u).toBeVisible();let m=u.locator("h4",{hasText:"Insufficient funds"}),p=await u.getByTestId("alert-modal__selected-alert").textContent();if(await m.isVisible().catch(()=>!1))throw Error(`${p}`)}if(e){let s=t.getByTestId("edit-gas-fee-icon");if(await s.scrollIntoViewIfNeeded(),await s.click(),e.feeType!=="advanced"&&await t.getByTestId(`gas-option-${e.feeType}`).click(),e.feeType==="advanced"){await t.getByTestId("gas-option-advanced").click();let u=t.getByRole("textbox",{name:"Max base fee"}),m=t.getByRole("textbox",{name:"Priority fee"}),p=t.getByRole("button",{name:"Save",exact:!0});await u.fill(e.maxBaseFee),await m.fill(e.priorityFee),await p.click()}}await no(a).toBeEnabled(),await a.click();let i=t.getByRole("dialog");await i.isVisible().catch(()=>!1)&&await i.locator("h4",{hasText:"Your assets may be at risk"}).isVisible().catch(()=>!1)&&(await i.getByTestId("alert-modal-acknowledge-checkbox").click(),await i.getByTestId("confirm-alert-modal-submit-button").click()),await t.waitForEvent("close",{timeout:15e3})}import{expect as Ra}from"@playwright/test";import{expect as Pe}from"@playwright/test";async function bt({page:t,accountName:e}){let a=t.getByTestId(P.accountMenuButton);if(await a.textContent()===e){console.info(`Can't switch account to "${e}", it is already selected.`);return}await Pe(a).toBeVisible({timeout:15e3}),await a.click(),await Pe(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let n=t.getByTestId(ot.addMultichainAccountButton),r=await n.textContent();r?.includes("Syncing")&&await Pe.poll(async()=>(await n.textContent())?.trim()??"",{timeout:6e4}).not.toBe(r);let i=await t.getByTestId(/^multichain-account-cell-(?:entropy|keyring):/).all(),c=null;for(let s of i)if(await s.scrollIntoViewIfNeeded(),(await s.textContent())?.includes(e)){c=s;break}if(!c)throw Error(`Account with name "${e}" not found.`);await c?.click()}async function io(t,e){e&&await bt({page:t,accountName:e});let a=t.getByRole("button",{name:"Connect",exact:!0});await a.waitFor({state:"visible",timeout:25e3}),await a.click(),await t.getByRole("heading",{name:"Connecting",exact:!0}).waitFor({state:"detached",timeout:3e4});let n;await Ra.poll(async()=>(n=await t.locator("div[class='permissions-connect']").isVisible().catch(()=>!1),n),{timeout:25e3}).toBe(!0).catch(()=>console.error("Notice dialog did not appear within the timeout period."));let r=t.getByTestId("page-container-footer-next");await r.waitFor({state:"visible",timeout:25e3}),await r.click()}async function co(t,e){return await t.getByTestId(P.accountAddressesButton).hover(),await t.getByTestId("multichain-address-rows-list").getByRole("button",{name:/view all/i}).click(),await t.getByRole("searchbox",{name:/search networks/i}).fill(e),await t.locator(`div[data-testid='${P.accountAddressesElements}']:has-text('${e}')`).getByTestId(P.accountAddressQRCode).click(),await t.getByRole("dialog").locator("div > p[data-testid='account-address']").textContent()}import{expect as La}from"@playwright/test";import{errors as _a}from"@playwright/test";var so={loadingOverlay:"loading-overlay",loadingSpinner:"spinner loading-overlay__spinner"};var Va=6e4,$a=async(t,e,a)=>{await M(e);try{await e.locator(`div[class="${t}"]`).waitFor({state:"detached",timeout:a})}catch(o){if(o instanceof _a.TimeoutError)console.info(`Loading indicator '${t}' not found - continuing.`);else throw console.error(`Error while waiting for loading indicator '${t}' to disappear`),o}},te=async t=>{try{await $a(so.loadingSpinner,t,Va)}catch(e){console.warn("Warning during MetaMask load:",e)}return await y(300),t};async function lo(t){if(await t.getByTestId($t.unlockButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already locked");return}await Zt(t);let o=t.getByTestId(Bt.lockButton);await La(o).toBeVisible(),await o.click(),await te(t)}import{styleText as uo}from"util";import{expect as At}from"@playwright/test";var Q=class{name="metamask";onboardingPath="/home.html#onboarding";async indexUrl(){return`chrome-extension://${await this.extensionId()}/home.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[data-testid='multichain-page']"})}};import{expect as Ae}from"@playwright/test";async function Pt({page:t}){await t.locator(`div:has(> button[data-testid='${P.openSettingsButton}'])`).click(),await t.getByTestId(Bt.networksButton).click();let o=t.locator("section[role='dialog']");await Ae(o).toBeVisible(),await Ae(o).toContainText(/manage networks/i);let n="div:has(> p:has-text('Show test networks'))";await o.locator(n).scrollIntoViewIfNeeded();let r=o.locator(n);if(!await r.locator("label[class='toggle-button toggle-button--off']").isVisible().catch(()=>!1)){await o.getByRole("button",{name:/close/i}).click(),console.info("Testnet networks are already visible.");return}await r.locator("label[class='toggle-button toggle-button--off']").click(),await t.getByTestId("Sepolia").scrollIntoViewIfNeeded(),await Ae(t.getByTestId("Sepolia")).toBeVisible(),await o.getByRole("button",{name:/close/i}).click()}async function Ce({page:t,mainAccountName:e,...a}){console.info(uo("yellowBright",`
4
+ \u26A0\uFE0F Skipping test: ${e}`),Na.skip())}var P={buyButton:"eth-overview-buy",swapButton:"eth-overview-swap",sendButton:"eth-overview-send",receiveButton:"eth-overview-receive",openSettingsButton:"account-options-menu-button",accountMenuButton:"account-menu-icon",accountCell:"multichain-account-cell-entropy",openNetworkSelectorButton:"sort-by-networks",accountAddressesButton:"networks-subtitle-test-id",accountAddressesElements:"multichain-address-row",accountAddressQRCode:"multichain-address-row-qr-button"},Bt={lockButton:"global-menu-lock",networksButton:"global-menu-networks"},$t={passwordInput:"unlock-password",unlockButton:"unlock-submit"},ot={accountOptionsMenuButton:"multichain-account-cell-end-accessory",accountDetailsLabel:"Account details",renameAccountLabel:"Rename",addressesLabel:"Addresses",pinToTopLabel:"Pin to top",hideAccountLabel:"Hide account",backButton:"back",addMultichainAccountButton:"add-multichain-account-button",addWalletButton:"account-list-add-wallet-button",importWalletButton:"add-wallet-modal-import-wallet",importAccountButton:"add-wallet-modal-import-account"};var F={createWalletButton:"onboarding-create-wallet",importWalletButton:"onboarding-import-wallet",useSecretRecoveryPhraseButton:"onboarding-create-with-srp-button",createNewPasswordInput:"create-password-new-input",confirmNewPasswordInput:"create-password-confirm-input",confirmPasswordCheckbox:"create-password-terms",createPasswordButton:"create-password-submit",revealSecretRecoveryPhraseButton:"recovery-phrase-reveal",recoveryPhraseRemindMeLaterButton:"recovery-phrase-remind-later",metamaskMetricsIAgreeButton:"metametrics-i-agree",onboardingDoneButton:"onboarding-complete-done",importUsingSecretRecoveryPhraseButton:"onboarding-import-with-srp-button",secretRecoveryPhraseTextAreaInput:"srp-input-import__srp-note",importWalletConfirmButton:"import-srp-confirm",importAccountConfirmButton:"import-account-confirm-button",importSRPError:"bannerAlert"};async function eo({page:t,privateKey:e,accountName:a}){let o=to.string().min(1,"Account name cannot be an empty string").trim().parse(a),n=to.string().min(1,"Private key cannot be an empty string").trim().parse(e),r=t.getByTestId(P.accountMenuButton);await L(r).toBeVisible({timeout:3e4}),await r.click(),await L(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let i=t.getByTestId(ot.addWalletButton),c=await i.textContent();c?.includes("Syncing")&&await L.poll(async()=>(await i.textContent())?.trim()??"",{timeout:12e4}).not.toBe(c),await L(i).toBeEnabled({timeout:6e4}),await i.click();let s=t.getByRole("dialog");await L(s).toContainText(/add wallet/i),await t.getByTestId(ot.importAccountButton).click(),await t.locator("input[id='private-key-box']").fill(n);let m=t.getByTestId(F.importAccountConfirmButton);await L(m).toBeEnabled(),await m.click();let p=t.getByTestId(F.importSRPError),w=await p.isVisible().catch(()=>!1);w&&Je(w,`${(await p.textContent())?.split(".")[0]}`);let d=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])"),g=(await d.textContent())?.split("$")[0];g&&await Ma({page:t,accountName:o,activeAccountLocator:d,activeAccountName:g}),await t.locator("button[aria-label='Back']").first().click()}async function Ma({page:t,accountName:e,activeAccountLocator:a,activeAccountName:o}){let n=a.locator(`div[aria-label='${o} options']`);await L(n).toBeVisible(),await n.click(),await L(t.getByRole("tooltip")).toBeVisible();let r=t.locator(`div[aria-label='${ot.renameAccountLabel}']`);await L(r).toBeVisible(),await r.click();let i=t.getByRole("dialog"),c=i.getByRole("heading",{name:/rename/i});await L(c).toBeVisible();let s=i.getByRole("textbox");await L(s).toBeVisible(),await s.fill(e);let l=i.getByRole("button",{name:/confirm/i});await L(l).toBeEnabled(),await l.click(),await i.waitFor({state:"detached",timeout:2e4});let u=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])");await L(u).toContainText(e)}import{expect as Lt}from"@playwright/test";import kt from"zod";var oo=kt.object({networkName:kt.string().min(1,"Network name cannot be an empty string"),rpcUrl:kt.url(),chainId:kt.number().or(kt.string().includes("0x")),currencySymbol:kt.string().toUpperCase().min(1,"Currency symbol cannot be an empty string")});import{expect as Ea}from"@playwright/test";async function Zt(t){let e=t.locator("div:has(> p[data-testid='notifications-tag-counter__unread-dot'])"),a=t.getByTestId(P.openSettingsButton);await e.isVisible().catch(()=>!1)?await e.click():(await Ea(a).toBeVisible(),await a.click())}async function ao({page:t,...e}){let{chainId:a,currencySymbol:o,networkName:n,rpcUrl:r}=oo.parse({...e},{reportInput:!0});await Zt(t),await t.getByTestId(Bt.networksButton).click();let c=t.locator("section[role='dialog']");await Lt(c).toContainText(/manage networks/i),await t.getByRole("button",{name:/add a custom network/i}).click(),await Lt(c).toContainText(/Add a custom network/i);let l=t.getByTestId("network-form-network-name"),u=t.getByTestId("test-add-rpc-drop-down"),m=t.getByTestId("network-form-chain-id"),p=t.getByTestId("network-form-ticker-input");await l.fill(n),await u.click(),await t.getByRole("tooltip").locator("div:has(> button:has-text('Add RPC URL'))").click(),await Lt(c).toContainText(/Add RPC URL/i);let g=t.getByTestId("rpc-url-input-test"),f=t.getByRole("button",{name:/Add URL/i});await g.fill(r),await f.click(),await Lt(c).toContainText(/Add a custom network/i);let h=t.getByTestId("network-form-chain-id-error");if(await h.isVisible().catch(()=>!1)){let C=await h.textContent();throw Error(`RPC error: ${C}`)}await m.fill(`${a}`),await p.fill(o);let A=t.getByRole("button",{name:/save/i});await Lt(A).toBeEnabled(),await A.click()}import{expect as no}from"@playwright/test";var Jt={confirmButton:"confirm-footer-button",cancelButton:"confirm-footer-cancel-button"};async function ro(t,e){let a=t.getByTestId(Jt.confirmButton);await y(2e3);let n=(await a.textContent())?.includes("Review alert"),r=await a.isDisabled().catch(()=>!1);if(n&&r){await t.getByTestId("edit-gas-fees-row").locator("> div").first().click();let u=t.getByRole("dialog");await no(u).toBeVisible();let m=u.locator("h4",{hasText:"Insufficient funds"}),p=await u.getByTestId("alert-modal__selected-alert").textContent();if(await m.isVisible().catch(()=>!1))throw Error(`${p}`)}if(e){let s=t.getByTestId("edit-gas-fee-icon");if(await s.scrollIntoViewIfNeeded(),await s.click(),e.feeType!=="advanced"&&await t.getByTestId(`gas-option-${e.feeType}`).click(),e.feeType==="advanced"){await t.getByTestId("gas-option-advanced").click();let u=t.getByRole("textbox",{name:"Max base fee"}),m=t.getByRole("textbox",{name:"Priority fee"}),p=t.getByRole("button",{name:"Save",exact:!0});await u.fill(e.maxBaseFee),await m.fill(e.priorityFee),await p.click()}}await no(a).toBeEnabled(),await a.click();let i=t.getByRole("dialog");await i.isVisible().catch(()=>!1)&&await i.locator("h4",{hasText:"Your assets may be at risk"}).isVisible().catch(()=>!1)&&(await i.getByTestId("alert-modal-acknowledge-checkbox").click(),await i.getByTestId("confirm-alert-modal-submit-button").click()),await t.waitForEvent("close",{timeout:15e3})}import{expect as Ra}from"@playwright/test";import{expect as Pe}from"@playwright/test";async function bt({page:t,accountName:e}){let a=t.getByTestId(P.accountMenuButton);if(await a.textContent()===e){console.info(`Can't switch account to "${e}", it is already selected.`);return}await Pe(a).toBeVisible({timeout:15e3}),await a.click(),await Pe(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let n=t.getByTestId(ot.addMultichainAccountButton),r=await n.textContent();r?.includes("Syncing")&&await Pe.poll(async()=>(await n.textContent())?.trim()??"",{timeout:6e4}).not.toBe(r);let i=await t.getByTestId(/^multichain-account-cell-(?:entropy|keyring):/).all(),c=null;for(let s of i)if(await s.scrollIntoViewIfNeeded(),(await s.textContent())?.includes(e)){c=s;break}if(!c)throw Error(`Account with name "${e}" not found.`);await c?.click()}async function io(t,e){e&&await bt({page:t,accountName:e});let a=t.getByRole("button",{name:"Connect",exact:!0});await a.waitFor({state:"visible",timeout:25e3}),await a.click(),await t.getByRole("heading",{name:"Connecting",exact:!0}).waitFor({state:"detached",timeout:3e4});let n;await Ra.poll(async()=>(n=await t.locator("div[class='permissions-connect']").isVisible().catch(()=>!1),n),{timeout:25e3}).toBe(!0).catch(()=>console.error("Notice dialog did not appear within the timeout period."));let r=t.getByTestId("page-container-footer-next");await r.waitFor({state:"visible",timeout:25e3}),await r.click(),await t.waitForEvent("close",{predicate:()=>!0,timeout:25e3}).catch(()=>console.error("Extension popup did not close within the timeout period when connecting to the DApp."))}async function co(t,e){return await t.getByTestId(P.accountAddressesButton).hover(),await t.getByTestId("multichain-address-rows-list").getByRole("button",{name:/view all/i}).click(),await t.getByRole("searchbox",{name:/search networks/i}).fill(e),await t.locator(`div[data-testid='${P.accountAddressesElements}']:has-text('${e}')`).getByTestId(P.accountAddressQRCode).click(),await t.getByRole("dialog").locator("div > p[data-testid='account-address']").textContent()}import{expect as La}from"@playwright/test";import{errors as _a}from"@playwright/test";var so={loadingOverlay:"loading-overlay",loadingSpinner:"spinner loading-overlay__spinner"};var Va=6e4,$a=async(t,e,a)=>{await M(e);try{await e.locator(`div[class="${t}"]`).waitFor({state:"detached",timeout:a})}catch(o){if(o instanceof _a.TimeoutError)console.info(`Loading indicator '${t}' not found - continuing.`);else throw console.error(`Error while waiting for loading indicator '${t}' to disappear`),o}},te=async t=>{try{await $a(so.loadingSpinner,t,Va)}catch(e){console.warn("Warning during MetaMask load:",e)}return await y(300),t};async function lo(t){if(await t.getByTestId($t.unlockButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already locked");return}await Zt(t);let o=t.getByTestId(Bt.lockButton);await La(o).toBeVisible(),await o.click(),await te(t)}import{styleText as uo}from"util";import{expect as At}from"@playwright/test";var Q=class{name="metamask";onboardingPath="/home.html#onboarding";async indexUrl(){return`chrome-extension://${await this.extensionId()}/home.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[data-testid='multichain-page']"})}};import{expect as Ae}from"@playwright/test";async function Pt({page:t}){await t.locator(`div:has(> button[data-testid='${P.openSettingsButton}'])`).click(),await t.getByTestId(Bt.networksButton).click();let o=t.locator("section[role='dialog']");await Ae(o).toBeVisible(),await Ae(o).toContainText(/manage networks/i);let n="div:has(> p:has-text('Show test networks'))";await o.locator(n).scrollIntoViewIfNeeded();let r=o.locator(n);if(!await r.locator("label[class='toggle-button toggle-button--off']").isVisible().catch(()=>!1)){await o.getByRole("button",{name:/close/i}).click(),console.info("Testnet networks are already visible.");return}await r.locator("label[class='toggle-button toggle-button--off']").click(),await t.getByTestId("Sepolia").scrollIntoViewIfNeeded(),await Ae(t.getByTestId("Sepolia")).toBeVisible(),await o.getByRole("button",{name:/close/i}).click()}async function Ce({page:t,mainAccountName:e,...a}){console.info(uo("yellowBright",`
5
5
  \u{1F98A} MetaMask onboarding started...`,{validateStream:!1}));let o=await k("metamask"),n=new Q,r=t.locator("img[class='loading-spinner']"),i=t.getByTestId(F.createWalletButton),c=t.getByTestId(F.importWalletButton),s=t.getByTestId(F.createNewPasswordInput),l=t.getByTestId(F.confirmNewPasswordInput),u=t.getByTestId(F.confirmPasswordCheckbox),m=t.getByTestId(F.createPasswordButton),p=t.getByTestId(F.metamaskMetricsIAgreeButton),w=t.getByTestId(F.onboardingDoneButton);if(await r.waitFor({state:"detached",timeout:3e4}),a.mode==="create"){let A=t.getByTestId(F.useSecretRecoveryPhraseButton);await i.click(),await A.click(),await s.fill(o),await l.fill(o),await u.click(),await m.click(),await t.getByTestId(F.revealSecretRecoveryPhraseButton).click(),await t.getByTestId(F.recoveryPhraseRemindMeLaterButton).click(),await p.click()}if(a.mode==="import"){let{secretRecoveryPhrase:A}=a,C=A.split(" "),R=t.getByTestId(F.importUsingSecretRecoveryPhraseButton);await c.click(),await R.click();let V=t.getByTestId(F.secretRecoveryPhraseTextAreaInput);await V.fill(C[0]),await V.press("Space");for(let Y=1;Y<C.length;Y++){let zt=t.getByTestId(`import-srp__srp-word-${Y}`);await zt.fill(C[Y]),await zt.press("Space")}await t.getByTestId(F.importWalletConfirmButton).click(),await s.fill(o),await l.fill(o),await u.click(),await m.click(),await p.click();let et=t.getByTestId("wallet-ready");await At(et).toContainText(/your wallet is ready/i)}await w.click();let g=`chrome-extension://${await n.extensionId()}/sidepanel.html`,h=await t.context().browser()?.newBrowserCDPSession(),S;await At.poll(async()=>{if(h){let{targetInfos:A}=await h.send("Target.getTargets"),C=A.find(R=>R.url===g);return S=C,!!C}},{timeout:15e3}).toBe(!0),S&&await h?.send("Target.closeTarget",{targetId:S.targetId}),await t.goto(await n.indexUrl()),await r.waitFor({state:"detached",timeout:3e4}),await At(t.getByTestId(P.buyButton)).toBeVisible(),await At(t.getByTestId(P.swapButton)).toBeVisible(),await At(t.getByTestId(P.sendButton)).toBeVisible(),await At(t.getByTestId(P.receiveButton)).toBeVisible(),await Pt({page:t}),e&&await bt({page:t,accountName:e}),await y(5e3),console.info(uo("greenBright","\u2728 MetaMask onboarding completed successfully",{validateStream:!1}))}import{expect as Oa}from"@playwright/test";async function mo(t){let e=t.getByTestId(Jt.cancelButton);await y(1e3),await Oa(e).toBeEnabled(),await e.click()}import{expect as z}from"@playwright/test";async function po({page:t,currentAccountName:e,newAccountName:a}){let o=t.getByTestId(P.accountMenuButton);if(await o.textContent()===a)throw Error(`The account to be renamed "${a}" already exists.`);await z(o).toBeVisible({timeout:15e3}),await o.click(),await z(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let r=t.getByTestId(ot.addMultichainAccountButton),i=await r.textContent();i?.includes("Syncing")&&await z.poll(async()=>(await r.textContent())?.trim()??"",{timeout:6e4}).not.toBe(i);let c=await t.getByTestId(/^multichain-account-cell/).all(),s=null;for(let h of c)if((await h.textContent())?.includes(e)){s=h;break}if(!s)throw Error(`Account with name "${e}" not found.`);if((await s.textContent())?.split("$")[0]===a)throw Error(`The new account name "${a}" is the same as the old account name "${e}".`);let u=t.locator(`div[aria-label='${e} options']`);await z(u).toBeVisible(),await u.click(),await z(t.getByRole("tooltip")).toBeVisible();let m=t.locator(`div[aria-label='${ot.renameAccountLabel}']`);await z(m).toBeVisible(),await m.click();let p=t.getByRole("dialog"),w=p.getByRole("heading",{name:/rename/i});await z(w).toBeVisible();let d=p.getByRole("textbox");await z(d).toBeVisible(),await d.fill(a);let g=p.getByRole("button",{name:/confirm/i});await z(g).toBeEnabled(),await g.click();for(let h of c)if((await h.textContent())?.includes(a)){await z(h).toBeVisible(),await z(h).toContainText(a);break}await t.locator("button[aria-label='Back']").first().click()}import{expect as Se}from"@playwright/test";async function wo({page:t,networkType:e,chainName:a}){let o=t.getByTestId(P.openNetworkSelectorButton);await o.click();let n=t.getByTestId("modal-header-close-button");if(e==="testnet"||e==="custom"){let s=t.getByRole("tab",{name:"Custom"});await s.click(),await t.locator("p:has-text('Testnets')").isVisible().catch(()=>!1)||(await n.click(),await Pt({page:t}),await o.click(),await s.click());let m=t.locator(`div div[data-testid='${a}']`),p=await m.textContent();Se(p).toBe(a),await m.click();return}await t.getByRole("tab",{name:"Popular"}).click();let i=t.locator(`div div[data-testid='${a}']`),c=await i.textContent();Se(c).toBe(a),await i.click(),await Se(o).toContainText(a,{timeout:3e4})}import{expect as fo}from"@playwright/test";async function Ot(t){let e=await k("metamask"),a=t.getByTestId($t.passwordInput);if(await t.getByTestId(P.openNetworkSelectorButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await a.fill(e);let r=t.getByTestId($t.unlockButton);await fo(r).toBeVisible(),await r.click(),await te(t),await fo(t.getByTestId(P.buyButton)).toBeVisible({timeout:3e4})}var lt=class extends Q{page;constructor(e){super(),this.page=e}async onboard(e){await Ce({page:this.page,...e})}async unlock(){await Ot(this.page)}async lock(){await lo(this.page)}async renameAccount({newAccountName:e,currentAccountName:a}){await po({page:this.page,newAccountName:e,currentAccountName:a})}async addAccount({privateKey:e,accountName:a}){await eo({page:this.page,privateKey:e,accountName:a})}async switchAccount({accountName:e}){await bt({page:this.page,accountName:e})}async switchNetwork({...e}){await wo({page:this.page,...e})}async getAccountAddress(e){return await co(this.page,e)}async toggleShowTestnetNetwork(){await Pt({page:this.page})}async addCustomNetwork({chainId:e,currencySymbol:a,networkName:o,rpcUrl:n}){await ao({page:this.page,chainId:e,currencySymbol:a,networkName:o,rpcUrl:n})}async connectToApp(e){await io(await this.promptPage(this.page.context()),e)}async confirmTransaction(e){await ro(await this.promptPage(this.page.context()),e)}async rejectTransaction(){await mo(await this.promptPage(this.page.context()))}};import go from"fs";import Da from"path";import{test as Ua,chromium as Ka}from"@playwright/test";import{Instance as Ha,Pool as ja}from"prool";var Dt,Rs=({slowMo:t=0,profileName:e}={})=>Ua.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new Q,i=x(r.name),c=await I(r.name),s=Da.resolve(i,e??"wallet-data");if(!go.existsSync(s))throw new Error("\u274C Cache for MetaMask wallet data not found. Create it first");go.cpSync(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await Ka.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t}),{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl();await u.waitForEvent("page",{predicate:f=>f.url().startsWith(w),timeout:3e4}),Dt=u.pages().find(f=>f.url().startsWith(w))??await E(u,w);for(let f of u.pages())f.url().includes("about:blank")&&await f.close();await Dt.locator("img[class='loading-spinner']").waitFor({state:"detached"}),await Ot(Dt),await n(u),await b(u,o)},metamaskPage:async({context:a},o)=>{await o(Dt)},metamask:async({context:a},o)=>{let n=new lt(Dt);await o(n)},createAnvilNode:async({context:a},o,n)=>{let r=n.workerIndex,i;await o(async c=>{i=ja.define({instance:Ha.anvil(c)});let s=await i.start(r),l=`http://${s.host}:${s.port}`,m=c?.chainId??31337;return{rpcUrl:l,anvil:s,chainId:m}}),i&&await i.stop(r)},connectToAnvil:async({context:a,metamask:o,createAnvilNode:n},r)=>{await r(async()=>{let{chainId:i,rpcUrl:c}=await n({chainId:2251});await o.addCustomNetwork({chainId:i,currencySymbol:"ETH",networkName:"Anvil Localnet",rpcUrl:c})})}});import{test as qa}from"@playwright/test";import{Instance as Ya,Pool as Qa}from"prool";import ho from"fs";import Ga from"path";import{chromium as za}from"@playwright/test";async function yo({workerInfo:t,profileName:e,slowMo:a}){let o=new Q,n=await v(t.workerIndex.toString()),r=x(o.name),i=Ga.resolve(r,e??"wallet-data");if(!ho.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);ho.cpSync(i,n,{recursive:!0,force:!0});let c=await I(o.name),s=await za.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),l=await o.indexUrl();await s.waitForEvent("page",{predicate:m=>m.url().startsWith(l),timeout:4e4});let u=s.pages().find(m=>m.url().startsWith(l));u||(u=await s.newPage(),await u.goto(l),await M(u));for(let m of s.pages())m.url().includes("about:blank")&&await m.close();return{context:s,walletPage:u,contextPath:n}}var Xs=({profileName:t,dappUrl:e,slowMo:a}={})=>qa.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await yo({workerInfo:r,profileName:t,slowMo:a});await i.grantPermissions(["clipboard-read"]);let l=new lt(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();e&&await i.goto(e),await n(i)},{scope:"worker"}],metamaskPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},metamask:async({workerScopeContents:o},n)=>{let r=new lt(o.walletPage);await n(r)},createAnvilNode:async({context:o},n,r)=>{let i=r.workerIndex,c;await n(async s=>{c=Qa.define({instance:Ya.anvil(s)});let l=await c.start(i),u=`http://${l.host}:${l.port}`,p=s?.chainId??31337;return{rpcUrl:u,anvil:l,chainId:p}}),c&&await c.stop(i)},connectToAnvil:async({context:o,metamask:n,createAnvilNode:r},i)=>{await i(async()=>{let{chainId:c,rpcUrl:s}=await r({chainId:2251});await n.addCustomNetwork({chainId:c,currencySymbol:"ETH",networkName:"Anvil Localnet",rpcUrl:s})})}});var _={openSidebarMenuButton:"button[aria-label='open sidebar']",addWalletButton:"button:has-text('Add Wallet')",settingsButton:"button:has-text('Settings')",settingsMenuBackButton:"button[aria-label='Back']"};var K={importExistingWalletButton:'button:has-text("Import an existing wallet")',switchNetworkButton:"button[id^='menu-button']",privateKeyButton:"button:has-text('Private Key')",findMyAccountButton:"button:has-text('Find my account')"};async function ee(t,e,a){let o=t.locator(K.switchNetworkButton).last();await o.scrollIntoViewIfNeeded();let n=await o.textContent(),r=e.split("net")[0]?.toLowerCase()??"";if(n?.toLowerCase()===r)return console.info(`
6
6
  Already on ${e}, no need to switch network.`),"Exit";await o.click();let c=t.locator(a).last().locator(`> button:has-text('${e}')`);await c.click(),await t.locator("div > h2:has-text('Meteor Community')").isVisible().catch(()=>!1)&&await c.click()}async function Ct({page:t,newAccountName:e}){await t.locator(_.openSidebarMenuButton).click(),await t.locator("div:has(> h2):has(> svg)").click();let n=t.locator("input[placeholder='Ex. My Meteor Wallet']"),r=t.locator("button[type='submit']:has-text('Update')");await n.fill(e),await r.click(),await t.locator("div[id='root'] button[aria-label='Close']").click()}async function oe({page:t,privateKey:e,accountName:a,network:o}){await t.locator(_.openSidebarMenuButton).click(),await t.locator(_.addWalletButton).click(),await ee(t,o,"section[role='dialog'] div[role='menu']"),await t.locator(K.importExistingWalletButton).click(),await t.locator(K.privateKeyButton).click();let s=t.locator('button:has-text("Continue")');await s.scrollIntoViewIfNeeded(),await s.click(),await t.locator("textarea:not([disabled])").fill(e),await t.locator(K.findMyAccountButton).click(),await t.locator("button[type='submit'][data-loading]").waitFor({state:"detached",timeout:25e3}),await t.locator("button:not([aria-label='Back'],[id^='menu-button']):has-text('Account')").click(),await Ct({page:t,newAccountName:a})}var St={approveButton:"button:has-text('Approve')",connectButton:"button:has-text('Connect')",cancelButton:"button:has-text('Cancel')"};async function X(t){let e=await k("meteor"),a=t.locator("input[placeholder='Enter Password']"),o=t.locator('button:has-text("Unlock")');await a.fill(e),await o.click()}async function xo(t){await X(t),await t.locator(St.approveButton).click(),await t.locator("h2:has-text('Executing Transaction')").waitFor({state:"attached"}),await t.waitForEvent("close",{timeout:15e3})}async function vt(t,e){if((await t.locator("div:has(button[type='button'][aria-label='open sidebar'])").nth(-2).locator("div:has(div > h2)").locator("div > h2").textContent())?.toLowerCase()===e.toLowerCase()){console.info(`
7
7
  Switching to the ${e} account aborted. Account is already selected.`);return}await t.locator(_.openSidebarMenuButton).click();let s=await t.locator("div:has(div > button[type='button'][aria-label='Close'])").nth(-2).locator("div").nth(2).locator("> div").nth(1).locator("div").nth(1).locator("div > h2").all(),l=null;for(let u of s)if((await u.textContent())?.toLowerCase()===e.toLowerCase()){l=u;break}if(!l)throw new Error(`Account with name "${e}" not found.`);await l.click()}async function Bo(t,e){await X(t),e&&await vt(t,e);let a=t.getByRole("heading",{name:"Connect Request",exact:!0});await Promise.all([t.locator(St.connectButton).click(),a.waitFor({state:"detached",timeout:3e4})])}async function ko(t){return await t.locator("div:has(button[type='button'][aria-label='open sidebar'])").nth(-2).locator("div:has(div > h2)").locator("div > svg").click(),await t.evaluate(async()=>await navigator.clipboard.readText())}async function bo(t){await t.locator(_.openSidebarMenuButton).click(),await t.locator("button:has-text('Lock Wallet')").click()}import{styleText as ve}from"util";var Z=class{name="meteor";onboardingPath="ext_index_popup.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/ext_index_popup.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/ext_index.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[id='root']"})}};async function It(t){await t.locator(_.openSidebarMenuButton).click(),await t.locator(_.settingsButton).click()}async function ae(t,e){if(await It(t),await ee(t,e,"div[role='menu']")==="Exit"){let r=t.locator(_.settingsMenuBackButton);await r.scrollIntoViewIfNeeded(),await r.click();return}let o=t.locator("p:has-text('Available Balance')");if(await y(1e3),!await o.isVisible().catch(()=>!1))throw new Error([`There is no associated account for the ${e} network in your wallet.`,`Please add an account to the ${e} network in your wallet using the "addAccount" method.`,"NOTE: For the account to be persisted across tests, do this when onboarding the wallet."].join(`
@@ -10,7 +10,7 @@ import{expect as $e}from"@playwright/test";function y(t){return new Promise(e=>s
10
10
  Retrying search for account. ${rt} attempts left`),await y(15e3),await S.click(),await A.waitFor({state:"detached",timeout:2e4}),await t.locator("div:has-text('Import Your Account')").nth(-2).locator("button").isVisible().catch(()=>!1)){gt=!0;break}rt-=1}if(!gt)throw Error(ve("redBright",["No Account Found","Account associated with the private key not found. Please make sure you are trying to import an account on the correct network(Mainnet/Testnet)."].join(`
11
11
  `),{validateStream:!1}))}await t.locator("button:not([aria-label='Back'],[id^='menu-button']):has-text('Account')").click();let Y=t.locator("section[role='dialog']").locator("button:has-text('Close')").first();if(await Y.isVisible().then(()=>!0).catch(()=>!1)&&await Y.click(),await Ct({page:t,newAccountName:o}),n&&n.length>0){for(let{privateKey:Ee,accountName:Re,network:ra}of n)await oe({page:t,privateKey:Ee,accountName:Re,network:ra});await It(t);let rt=t.locator(K.switchNetworkButton).last();await rt.scrollIntoViewIfNeeded();let gt=await rt.textContent(),Me=a.split("net")[0]?.toLowerCase()??"";gt?.toLowerCase()!==Me&&await ae(t,a),await vt(t,o)}await y(3e3),console.info(ve("greenBright","\u2728 Meteor onboarding completed successfully"))}async function Po(t){await X(t),await t.locator(St.cancelButton).click()}var ut=class extends Z{page;constructor(e){super(),this.page=e}async onboard({network:e,privateKey:a,accountName:o,addWallet:n}){await Ie({page:this.page,network:e,privateKey:a,accountName:o,addWallet:n})}async unlock(){await X(this.page)}async lock(){await bo(this.page)}async renameAccount({newAccountName:e}){await Ct({page:this.page,newAccountName:e})}async switchNetwork(e){await ae(this.page,e)}async switchAccount(e){await vt(this.page,e)}async getAccountAddress(){return await ko(this.page)}async addAccount({accountName:e,network:a,privateKey:o}){await oe({page:this.page,accountName:e,network:a,privateKey:o})}async openSettings(){await It(this.page)}async connectToApp(e){await Bo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await xo(await this.promptPage(this.page.context()))}async rejectTransaction(){await Po(await this.promptPage(this.page.context()))}};import Ao from"fs";import Xa from"path";import{test as Za,chromium as Ja}from"@playwright/test";var Ut,Cu=({slowMo:t=0,profileName:e}={})=>Za.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new Z,i=x(r.name),c=await I(r.name),s=Xa.resolve(i,e??"wallet-data");if(!Ao.existsSync(s))throw new Error("\u274C Cache for Meteor wallet data not found. Create it first");Ao.cpSync(s,o,{recursive:!0,force:!0}),process.env.HEADLESS&&t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!");let l=await Ja.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`,`--load-extension=${c}`],slowMo:process.env.HEADLESS?0:t});await l.grantPermissions(["clipboard-read"]);let{cookies:u,origins:m}=await a.storageState();u&&await l.addCookies(u),m&&m.length>0&&$(m,l);let p=await r.indexUrl();Ut=l.pages().find(d=>d.url().startsWith(p))||await E(l,p);for(let d of l.pages())d.url().includes("about:blank")&&await d.close();await Ut.bringToFront(),await X(Ut),await n(l),await b(l,o)},meteorPage:async({context:a},o)=>{await o(Ut)},meteor:async({context:a},o)=>{let n=new ut(Ut);await o(n)}});import{test as tn}from"@playwright/test";var Nu=({slowMo:t,profileName:e,dappUrl:a}={})=>tn.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await xt({workerInfo:r,profileName:e,slowMo:t,wallet:new Z});await i.grantPermissions(["clipboard-read"]);for(let u of i.pages())u.url().includes("about:blank")&&await u.close();let l=new ut(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],meteorPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},meteor:async({workerScopeContents:o},n)=>{let r=new ut(o.walletPage);await n(r)}});import on from"zod";var T={depositButton:"button:has-text('Deposit')",sendButton:"button:has-text('Send')",receiveButton:"button:has-text('Receive')",settingsMenu:"button[aria-label='Settings']",lockButton:"global-menu-lock",accountMenuButton:"button[data-part='trigger']",accountDialog:"div[role='dialog']",backButton:"button[id='back-button']"},Te={networkSection:"a[href='/settings/network']",backButton:"button[id='back-button']"},We={passwordInput:"input[name='password']",unlockButton:"button:has-text('Unlock')"},q={accountOptionsMenuButton:"button[data-scope='popover']",editAccountButton:"button[aria-label='Edit account name']",renameAccountInput:"input[name='name']",saveButton:"button:has-text('Save')",cancelButton:"button:has-text('Cancel')",addAccountButton:"button:has-text('Add accounts')",addAccountWithPrivateKeyButton:"button:has-text('Import private key')",addAccountWithMnemonicButton:"button:has-text('Import mnemonic')"};var W={createWalletButton:"button:has-text('Create an account')",createSeedPhraseButton:"button:has-text('Create a seed phrase wallet')",createNewPasswordInput:"input[name='password']",confirmNewPasswordInput:"input[name='confirmPassword']",confirmPasswordCheckbox:"label>div[data-scope='checkbox']",continueButton:"button:has-text('Continue')",skipCopyRecoveryPhraseButton:"button:has-text('Skip')",getStartedButton:"button:has-text('Get started')",onboardingCompleteText:"h1:has-text('Your wallet is ready, you may close this window')",importWalletButton:"button:has-text('Import an account')",importUsingPrivateKeyButton:"button:has-text('Import private key')",importUsingMnemonicButton:"button:has-text('Import mnemonic')",importButton:"button:has-text('Import')",privateKeyInput:"input[name='privateKey']"};import{expect as Kt}from"@playwright/test";import en from"zod";async function mt({page:t,newAccountName:e}){let a=en.string().min(1,"Account name cannot be an empty string").parse(e);await t.locator(T.settingsMenu).click(),await Kt(t.getByText("Settings").first()).toBeVisible();let n=t.locator(q.editAccountButton);await Kt(n).toBeVisible(),await n.click(),await Kt(t.getByText("Account name").first()).toBeVisible();let r=t.locator(q.renameAccountInput);if(await r.getAttribute("value")===a)throw Error(`The account to be renamed "${a}" already exists.`);await r.fill(a);let c=t.locator(q.saveButton);await Kt(c).toBeEnabled(),await c.click(),await Kt(t.getByText(a).first()).toBeVisible(),await t.locator(T.backButton).click(),await Promise.allSettled([t.locator(T.depositButton).waitFor({state:"visible",timeout:2e4}),t.locator(T.sendButton).waitFor({state:"visible",timeout:2e4})])}async function ne({page:t,accountName:e,mode:a,...o}){let n=on.string().max(14,"For switching accounts reason, account name should not be longer than 14 characters. The reason for this is because the name will be truncated. Hence, it will be difficult to select the account.").parse(e);if(await t.locator(q.accountOptionsMenuButton).first().click(),await t.getByRole("dialog").locator(q.addAccountButton).click(),a==="privateKey"){let s="privateKey"in o?o.privateKey:"";if(await t.locator(q.addAccountWithPrivateKeyButton).click(),await t.locator(W.privateKeyInput).fill(s),await t.locator(W.importButton).click(),(await t.getByRole("status").locator("div[data-part='description']",{hasText:"Account already exists in wallet"}).textContent({timeout:3e3}).catch(()=>null))?.includes("Account already exists in wallet"))throw Error(`Account ${n} already exists in wallet`);await mt({page:t,newAccountName:n})}if(a==="mnemonic"){let l=("mnemonicPhrase"in o?o.mnemonicPhrase:"").split(" ");await t.locator(q.addAccountWithMnemonicButton).click();for(let[g,f]of l.entries())await t.locator(`input[name="mnemonic-${String.fromCharCode(97+g)}"]`).fill(f);if(await t.locator(W.continueButton).click(),(await t.getByRole("status").locator("div[data-part='description']",{hasText:"Account already exists in wallet"}).textContent({timeout:3e3}).catch(()=>null))?.includes("Account already exists in wallet"))throw Error(`Account ${n} already exists in wallet`);await mt({page:t,newAccountName:n})}}var Tt={approveButton:'button:has-text("Approve")',cancelButton:'button:has-text("Cancel")'};var an=/^[A-Z0-9]+(?:_[A-Z0-9]+)+$/;function Co(t){return an.test(t)?t.toLowerCase().replace(/_/g," ").replace(/\b[a-z]/g,e=>e.toUpperCase()):t}async function nn(t,e){for(;;){let o=e();if(o||t.isClosed())break;try{let n=t.locator("div:has(> h2:has-text('Simulation error'))");if(await n.isVisible().catch(()=>!1)){let i=await n.locator("p").textContent();throw new Error(`[Confirm Transaction Error]: ${Co(i||"Unexpected error!")}`)}}catch(n){if(t.isClosed())break;throw n instanceof Error?n:new Error(`[Confirm Transaction Error]: ${n}`)}if(o||t.isClosed())break;await y(300)}}async function So(t){let e=!1;nn(t,()=>e).catch(async n=>{t.isClosed()||console.error(n.message)}),await t.locator(Tt.approveButton).click(),e=!0}import{expect as rn}from"@playwright/test";async function Wt(t,e){let a=t.locator(q.accountOptionsMenuButton).first();if((await a.textContent())?.split("Switch wallet")[1]?.split("0x")[0]?.toLowerCase().trim().includes(e.toLowerCase().trim())){console.info(`
12
12
  Switching to ${e} account aborted because the account is already selected.`);return}await a.click();let r=await t.getByRole("dialog").locator("> div > div > button[type='button']").all(),i=null;for(let c of r)if((await c.textContent())?.toLowerCase()?.trim().includes(e.toLowerCase().trim())){i=c;break}if(!i)throw new Error(`Account with name "${e}" not found.`);await i.click()}async function vo(t,e){e&&await Wt(t,e);let a=t.locator(Tt.approveButton);await rn(a).toBeEnabled({timeout:2e4}),await a.click()}async function Io(t){return await t.getByRole("button",{name:"Copy Address",exact:!0}).click(),await t.evaluate(async()=>await navigator.clipboard.readText())}import{expect as To}from"@playwright/test";async function Wo(t){let e=t.locator(T.settingsMenu);await To(e).toBeVisible(),await e.click(),await To(t.getByText("Settings").first()).toBeVisible()}async function Fo(t){await Wo(t),await t.getByRole("button",{name:/lock wallet/i}).click(),await t.getByRole("heading",{name:/welcome/i}).waitFor({state:"visible",timeout:2e4})}import{styleText as No}from"util";import{expect as at}from"@playwright/test";var J=class{name="petra";onboardingPath="/onboarding.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/index.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/prompt.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[id='prompt']"})}};var Ft=3e4;async function Fe({page:t,...e}){console.info(No("yellowBright",`
13
- Petra onboarding started...`,{validateStream:!1}));let a=new J,o=await k("petra"),n=t.locator(W.createWalletButton),r=t.locator(W.importWalletButton),i=t.locator(W.createNewPasswordInput),c=t.locator(W.confirmNewPasswordInput),s=t.locator(W.confirmPasswordCheckbox),l=t.locator(W.continueButton),u=t.locator(W.getStartedButton),m=t.locator(W.onboardingCompleteText);if(e.mode==="create"){let p=t.locator(W.createSeedPhraseButton);await n.click(),await p.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await t.locator(W.skipCopyRecoveryPhraseButton).click(),await u.click(),await at(m).toBeVisible(),await t.goto(await a.indexUrl()),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(e.mode==="importPrivateKey"){let{privateKey:p}=e,w=t.locator(W.importUsingPrivateKeyButton),d=t.locator(W.privateKeyInput),g=t.locator(W.importButton);await r.click(),await w.click(),await d.fill(p),await g.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await u.click(),await at(m).toBeVisible(),await t.goto(await a.indexUrl()),await M(t),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(e.mode==="importMnemonic"){let{secretRecoveryPhrase:p}=e,w=t.locator(W.importUsingMnemonicButton);await r.click(),await w.click();for(let[d,g]of p.split(" ").entries())await t.locator(`input[name="mnemonic-${String.fromCharCode(97+d)}"]`).fill(g);await l.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await u.click(),await at(m).toBeVisible(),await t.goto(await a.indexUrl()),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(await mt({page:t,newAccountName:e.accountName}),e.addWallet&&e.addWallet.length>0){for(let{...p}of e.addWallet)await ne({page:t,...p});await Wt(t,e.accountName)}await y(3e3),console.info(No("greenBright","\u2728 Petra onboarding completed successfully",{validateStream:!1}))}import{expect as cn}from"@playwright/test";async function Mo(t){let e=t.locator(Tt.cancelButton);await cn(e).toBeEnabled(),await e.click()}async function Eo(t,e){await t.locator(T.settingsMenu).click(),await t.locator(Te.networkSection).click(),await t.locator(`div:has(> span:has-text("${e}"))`).first().click();let r=t.locator(Te.backButton);await r.click(),await r.click()}import{expect as Ro}from"@playwright/test";async function Ht(t){let e=await k("petra"),a=t.locator(We.passwordInput);if(!await a.isVisible().then(()=>!0).catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await Ro(a).toBeVisible({timeout:15e3}),await a.fill(e);let n=t.locator(We.unlockButton);await Ro(n).toBeEnabled(),await n.click(),await Promise.allSettled([t.locator(T.sendButton).waitFor({state:"visible",timeout:2e4}),t.locator(T.receiveButton).waitFor({state:"visible",timeout:2e4})])}var pt=class extends J{page;constructor(e){super(),this.page=e}async onboard(e){await Fe({page:this.page,...e})}async unlock(){await Ht(this.page)}async lock(){await Fo(this.page)}async renameAccount({newAccountName:e}){await mt({page:this.page,newAccountName:e})}async switchNetwork(e){await Eo(this.page,e)}async switchAccount(e){await Wt(this.page,e)}async getAccountAddress(){return await Io(this.page)}async addAccount({accountName:e,...a}){await ne({page:this.page,accountName:e,...a})}async connectToApp(e){await vo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await So(await this.promptPage(this.page.context()))}async rejectTransaction(){await Mo(await this.promptPage(this.page.context()))}};import _o from"fs";import sn from"path";import{test as ln,chromium as un}from"@playwright/test";var jt,sp=({slowMo:t=0,profileName:e}={})=>ln.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new J,i=x(r.name),c=await I(r.name),s=sn.resolve(i,e??"wallet-data");if(!_o.existsSync(s))throw new Error("\u274C Cache for Petra wallet data not found. Create it first");_o.cpSync(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await un.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t});await u.grantPermissions(["clipboard-read"]);let{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl();jt=u.pages().find(g=>g.url().startsWith(w))||await E(u,w);for(let g of u.pages()){let f=g.url();(f.includes("about:blank")||f.includes(r.onboardingPath))&&await g.close()}await jt.bringToFront(),await Ht(jt),await n(u),await b(u,o)},petraPage:async({context:a},o)=>{await o(jt)},petra:async({context:a},o)=>{let n=new pt(jt);await o(n)}});import{test as mn}from"@playwright/test";var fp=({slowMo:t,profileName:e,dappUrl:a}={})=>mn.extend({workerScopeContents:[async({browser:o},n,r)=>{let i=new J,{context:c,contextPath:s,walletPage:l}=await xt({wallet:i,workerInfo:r,profileName:e,slowMo:t});await c.grantPermissions(["clipboard-read"]);for(let m of c.pages())m.url().includes(i.onboardingPath)&&await m.close();let u=new pt(l);await u.unlock(),await n({wallet:u,walletPage:l,context:c}),await b(c,s)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],petraPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},petra:async({workerScopeContents:o},n)=>{let r=new pt(o.walletPage);await n(r)}});var N={openMenuButton:"settings-menu-open-button",settingsButton:"sidebar_menu-button-settings",addAccountButton:"sidebar_menu-button-add_account",unlockWalletButton:"unlock-form-submit-button",manageAccountsButton:"sidebar_menu-button-manage_accounts",homeHeaderAccountName:"home-header-account-name"},O={lockWalletButton:"lock-menu-item",closeMenuButton:"settings-menu-close-button",developerSettingsButton:"settings-item-developer-settings",activeNetworksButton:"settings-item-active-networks"},Vo={accountProfileContainer:"sortable-account-container"};var B={createNewWalletButton:"button:has-text('Create a new wallet')",IAlreadyHaveAWalletButton:"button:has-text('I already have a wallet')",importRecoveryPhraseButton:"button:has-text('Import Recovery Phrase')",importPrivateKeyButton:"button:has-text('Import Private Key')",createSeedPhraseWalletButton:"create-manual-seed-phrase",passwordInput:"onboarding-form-password-input",passwordConfirmInput:"onboarding-form-confirm-password-input",termsCheckBox:"onboarding-form-terms-of-service-checkbox",continueButton:"button:has-text('Continue')",importWalletButton:"button:has-text('Import Wallet')",getStartedButton:"button:has-text('Get Started')",recoveryPhraseSavedCheckbox:"onboarding-form-saved-secret-recovery-phrase-checkbox",recoveryPhraseInput:"secret-recovery-phrase-word-input"};async function re({page:t,privateKey:e,accountName:a,chain:o}){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.addAccountButton).click(),await t.locator(B.importPrivateKeyButton).click();let c=t.locator("span[id^='button--listbox-input--']"),s=await c.textContent(),l=t.locator("input[name='name']"),u=t.locator("textarea[name='privateKey']");s!==o&&(await c.click(),await t.locator("ul[id^='listbox--listbox-input--']").locator(`li[data-label='${o}']`).click()),await l.fill(a),await u.fill(e),await t.locator("button:has-text('Import')").click()}var Nt={confirmButton:"primary-button",cancelButton:"secondary-button"};async function $o(t){let e=t.getByTestId(Nt.confirmButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"});let o=t.getByRole("button",{name:"Confirm anyway",exact:!0});if(await o.isVisible().catch(()=>!1)){await o.click();return}await e.click()}import{expect as dn}from"@playwright/test";import pn from"zod";async function Mt(t,e){let a=pn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(N.openMenuButton).click();let n=null,r=await t.locator("div[data-testid='account-menu'] div[data-testid='tooltip_interactive-wrapper']").all();for(let i of r)if((await i.textContent())?.includes(a)){n=i;break}if(!n)throw new Error(`Account with name "${a}" not found in the account list.`);await n.click()}async function Lo(t,e){e&&await Mt(t,e);let a=t.getByTestId(Nt.confirmButton);await dn(a).toBeEnabled({timeout:15e3}),await a.click()}import wn from"zod";var fn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");async function Oo({page:t,accountName:e,chain:a}){let o=wn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.manageAccountsButton).click(),await t.getByTestId(`manage-accounts-sortable-${o}`).click();let c=t.getByRole("button",{name:/Account Address(?:es)?/i});await c.waitFor({state:"visible",timeout:2e4});let l=await c.locator("div[data-name='row.pair'] > div").last().textContent();if(l&&Number(l)===1){await c.locator("> div > div").last().click(),await t.getByTestId("header--back").click();let p=t.getByTestId(O.closeMenuButton);await p.waitFor({state:"visible",timeout:15e3}),await p.click()}else{await c.click();let m=new RegExp(`${fn(a.network)}`,"i");await t.getByRole("button",{name:m}).locator("> div").last().locator("> div").last().locator("div > button").last().click(),await t.getByRole("button",{name:"Close",exact:!0}).last().click();let h=t.getByTestId("header--back");await h.waitFor({state:"visible",timeout:15e3}),await h.click();let S=t.getByTestId(O.closeMenuButton);await S.waitFor({state:"visible",timeout:15e3}),await S.click()}return await t.evaluate(async()=>await navigator.clipboard.readText())}async function Do(t){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.settingsButton).click(),await t.getByTestId(O.lockWalletButton).click()}import{styleText as Uo}from"util";import{expect as gn}from"@playwright/test";var tt=class{name="phantom";onboardingPath="/onboarding.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[id='root']"})}};async function Et(t,e){let o=!1;for(;!e();){let n=e();if(n||o||t.isClosed())break;try{let r=t.locator("div[id='modal']").locator("div > svg").first();await r.isVisible().catch(()=>!1)&&(await r.click(),o=!0)}catch(r){if(t.isClosed())break;console.error("[autoClosePhantomNotification]: ",r)}if(n||o||t.isClosed())break;await y(300)}}async function ie({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.manageAccountsButton).click();let i=await t.getByTestId(Vo.accountProfileContainer).locator("div[data-testid^='manage-accounts-sortable'] div > p").all(),c=null;for(let w of i)if((await w.textContent())?.toLowerCase()===e.toLowerCase()){c=w;break}if(!c)throw new Error(`Account with name "${e}" not found`);await c.click(),await t.locator("button:has-text('Account Name')").click();let l=t.locator("input[name='name']");await l.clear(),await l.fill(a),await t.getByTestId("primary-button").click(),await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function ce(t){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.settingsButton).click()}async function se({page:t,...e}){await ce(t);let a=t.locator(`button[id='${O.developerSettingsButton}']`);await a.scrollIntoViewIfNeeded(),await a.click();let o=t.getByTestId("toggleTestNetwork"),r=await o.locator("label[data-testid='toggleTestNetwork-switch'] > input[aria-label='Toggle']").isChecked().catch(()=>!1);if(!r&&e.mode==="on"&&await o.click(),r&&e.mode==="off"){await o.click(),await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click();return}if(e.mode==="on"&&e.chain==="Solana"){let{network:s}=e;await t.locator(`button:has-text("${s}")`).click()}if(e.mode==="on"&&e.chain==="Ethereum"){let{network:s}=e;if(!await t.getByText("EVM",{exact:!0}).isVisible().catch(()=>!1))throw new Error(["EVM testnet options are not available. Please ensure Ethereum is enabled in optional chains.","To enable Ethereum, call the 'toggleOptionalChain' action before switching the network.","toggleOptionalChain({ page: page, toggleMode: 'on', supportedChains: ['Ethereum'] })","Tip: For persistence, enable Ethereum in your setup file after the onboarding step completes."].join(`
13
+ Petra onboarding started...`,{validateStream:!1}));let a=new J,o=await k("petra"),n=t.locator(W.createWalletButton),r=t.locator(W.importWalletButton),i=t.locator(W.createNewPasswordInput),c=t.locator(W.confirmNewPasswordInput),s=t.locator(W.confirmPasswordCheckbox),l=t.locator(W.continueButton),u=t.locator(W.getStartedButton),m=t.locator(W.onboardingCompleteText);if(e.mode==="create"){let p=t.locator(W.createSeedPhraseButton);await n.click(),await p.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await t.locator(W.skipCopyRecoveryPhraseButton).click(),await u.click(),await at(m).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(e.mode==="importPrivateKey"){let{privateKey:p}=e,w=t.locator(W.importUsingPrivateKeyButton),d=t.locator(W.privateKeyInput),g=t.locator(W.importButton);await r.click(),await w.click(),await d.fill(p),await g.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await u.click(),await at(m).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await M(t),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(e.mode==="importMnemonic"){let{secretRecoveryPhrase:p}=e,w=t.locator(W.importUsingMnemonicButton);await r.click(),await w.click();for(let[d,g]of p.split(" ").entries())await t.locator(`input[name="mnemonic-${String.fromCharCode(97+d)}"]`).fill(g);await l.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await u.click(),await at(m).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(await mt({page:t,newAccountName:e.accountName}),e.addWallet&&e.addWallet.length>0){for(let{...p}of e.addWallet)await ne({page:t,...p});await Wt(t,e.accountName)}await y(1500),console.info(No("greenBright","\u2728 Petra onboarding completed successfully",{validateStream:!1}))}import{expect as cn}from"@playwright/test";async function Mo(t){let e=t.locator(Tt.cancelButton);await cn(e).toBeEnabled(),await e.click()}async function Eo(t,e){await t.locator(T.settingsMenu).click(),await t.locator(Te.networkSection).click(),await t.locator(`div:has(> span:has-text("${e}"))`).first().click();let r=t.locator(Te.backButton);await r.click(),await r.click()}import{expect as Ro}from"@playwright/test";async function Ht(t){let e=await k("petra"),a=t.locator(We.passwordInput);if(!await a.isVisible().then(()=>!0).catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await Ro(a).toBeVisible({timeout:15e3}),await a.fill(e);let n=t.locator(We.unlockButton);await Ro(n).toBeEnabled(),await n.click(),await Promise.allSettled([t.locator(T.sendButton).waitFor({state:"visible",timeout:2e4}),t.locator(T.receiveButton).waitFor({state:"visible",timeout:2e4})])}var pt=class extends J{page;constructor(e){super(),this.page=e}async onboard(e){await Fe({page:this.page,...e})}async unlock(){await Ht(this.page)}async lock(){await Fo(this.page)}async renameAccount({newAccountName:e}){await mt({page:this.page,newAccountName:e})}async switchNetwork(e){await Eo(this.page,e)}async switchAccount(e){await Wt(this.page,e)}async getAccountAddress(){return await Io(this.page)}async addAccount({accountName:e,...a}){await ne({page:this.page,accountName:e,...a})}async connectToApp(e){await vo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await So(await this.promptPage(this.page.context()))}async rejectTransaction(){await Mo(await this.promptPage(this.page.context()))}};import _o from"fs";import sn from"path";import{test as ln,chromium as un}from"@playwright/test";var jt,sp=({slowMo:t=0,profileName:e}={})=>ln.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new J,i=x(r.name),c=await I(r.name),s=sn.resolve(i,e??"wallet-data");if(!_o.existsSync(s))throw new Error("\u274C Cache for Petra wallet data not found. Create it first");_o.cpSync(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await un.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t});await u.grantPermissions(["clipboard-read"]);let{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl();jt=u.pages().find(g=>g.url().startsWith(w))||await E(u,w);for(let g of u.pages()){let f=g.url();(f.includes("about:blank")||f.includes(r.onboardingPath))&&await g.close()}await jt.bringToFront(),await Ht(jt),await n(u),await b(u,o)},petraPage:async({context:a},o)=>{await o(jt)},petra:async({context:a},o)=>{let n=new pt(jt);await o(n)}});import{test as mn}from"@playwright/test";var fp=({slowMo:t,profileName:e,dappUrl:a}={})=>mn.extend({workerScopeContents:[async({browser:o},n,r)=>{let i=new J,{context:c,contextPath:s,walletPage:l}=await xt({wallet:i,workerInfo:r,profileName:e,slowMo:t});await c.grantPermissions(["clipboard-read"]);for(let m of c.pages())m.url().includes(i.onboardingPath)&&await m.close();let u=new pt(l);await u.unlock(),await n({wallet:u,walletPage:l,context:c}),await b(c,s)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],petraPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},petra:async({workerScopeContents:o},n)=>{let r=new pt(o.walletPage);await n(r)}});var N={openMenuButton:"settings-menu-open-button",settingsButton:"sidebar_menu-button-settings",addAccountButton:"sidebar_menu-button-add_account",unlockWalletButton:"unlock-form-submit-button",manageAccountsButton:"sidebar_menu-button-manage_accounts",homeHeaderAccountName:"home-header-account-name"},O={lockWalletButton:"lock-menu-item",closeMenuButton:"settings-menu-close-button",developerSettingsButton:"settings-item-developer-settings",activeNetworksButton:"settings-item-active-networks"},Vo={accountProfileContainer:"sortable-account-container"};var B={createNewWalletButton:"button:has-text('Create a new wallet')",IAlreadyHaveAWalletButton:"button:has-text('I already have a wallet')",importRecoveryPhraseButton:"button:has-text('Import Recovery Phrase')",importPrivateKeyButton:"button:has-text('Import Private Key')",createSeedPhraseWalletButton:"create-manual-seed-phrase",passwordInput:"onboarding-form-password-input",passwordConfirmInput:"onboarding-form-confirm-password-input",termsCheckBox:"onboarding-form-terms-of-service-checkbox",continueButton:"button:has-text('Continue')",importWalletButton:"button:has-text('Import Wallet')",getStartedButton:"button:has-text('Get Started')",recoveryPhraseSavedCheckbox:"onboarding-form-saved-secret-recovery-phrase-checkbox",recoveryPhraseInput:"secret-recovery-phrase-word-input"};async function re({page:t,privateKey:e,accountName:a,chain:o}){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.addAccountButton).click(),await t.locator(B.importPrivateKeyButton).click();let c=t.locator("span[id^='button--listbox-input--']"),s=await c.textContent(),l=t.locator("input[name='name']"),u=t.locator("textarea[name='privateKey']");s!==o&&(await c.click(),await t.locator("ul[id^='listbox--listbox-input--']").locator(`li[data-label='${o}']`).click()),await l.fill(a),await u.fill(e),await t.locator("button:has-text('Import')").click()}var Nt={confirmButton:"primary-button",cancelButton:"secondary-button"};async function $o(t){let e=t.getByTestId(Nt.confirmButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"});let o=t.getByRole("button",{name:"Confirm anyway",exact:!0});if(await o.isVisible().catch(()=>!1)){await o.click();return}await e.click()}import{expect as dn}from"@playwright/test";import pn from"zod";async function Mt(t,e){let a=pn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(N.openMenuButton).click();let n=null,r=await t.locator("div[data-testid='account-menu'] div[data-testid='tooltip_interactive-wrapper']").all();for(let i of r)if((await i.textContent())?.includes(a)){n=i;break}if(!n)throw new Error(`Account with name "${a}" not found in the account list.`);await n.click()}async function Lo(t,e){e&&await Mt(t,e);let a=t.getByTestId(Nt.confirmButton);await dn(a).toBeEnabled({timeout:15e3}),await a.click()}import wn from"zod";var fn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");async function Oo({page:t,accountName:e,chain:a}){let o=wn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.manageAccountsButton).click(),await t.getByTestId(`manage-accounts-sortable-${o}`).click();let c=t.getByRole("button",{name:/Account Address(?:es)?/i});await c.waitFor({state:"visible",timeout:2e4});let l=await c.locator("div[data-name='row.pair'] > div").last().textContent();if(l&&Number(l)===1){await c.locator("> div > div").last().click(),await t.getByTestId("header--back").click();let p=t.getByTestId(O.closeMenuButton);await p.waitFor({state:"visible",timeout:15e3}),await p.click()}else{await c.click();let m=new RegExp(`${fn(a.network)}`,"i");await t.getByRole("button",{name:m}).locator("> div").last().locator("> div").last().locator("div > button").last().click(),await t.getByRole("button",{name:"Close",exact:!0}).last().click();let h=t.getByTestId("header--back");await h.waitFor({state:"visible",timeout:15e3}),await h.click();let S=t.getByTestId(O.closeMenuButton);await S.waitFor({state:"visible",timeout:15e3}),await S.click()}return await t.evaluate(async()=>await navigator.clipboard.readText())}async function Do(t){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.settingsButton).click(),await t.getByTestId(O.lockWalletButton).click()}import{styleText as Uo}from"util";import{expect as gn}from"@playwright/test";var tt=class{name="phantom";onboardingPath="/onboarding.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[id='root']"})}};async function Et(t,e){let o=!1;for(;!e();){let n=e();if(n||o||t.isClosed())break;try{let r=t.locator("div[id='modal']").locator("div > svg").first();await r.isVisible().catch(()=>!1)&&(await r.click(),o=!0)}catch(r){if(t.isClosed())break;console.error("[autoClosePhantomNotification]: ",r)}if(n||o||t.isClosed())break;await y(300)}}async function ie({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.manageAccountsButton).click();let i=await t.getByTestId(Vo.accountProfileContainer).locator("div[data-testid^='manage-accounts-sortable'] div > p").all(),c=null;for(let w of i)if((await w.textContent())?.toLowerCase()===e.toLowerCase()){c=w;break}if(!c)throw new Error(`Account with name "${e}" not found`);await c.click(),await t.locator("button:has-text('Account Name')").click();let l=t.locator("input[name='name']");await l.clear(),await l.fill(a),await t.getByTestId("primary-button").click(),await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function ce(t){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.settingsButton).click()}async function se({page:t,...e}){await ce(t);let a=t.locator(`button[id='${O.developerSettingsButton}']`);await a.scrollIntoViewIfNeeded(),await a.click();let o=t.getByTestId("toggleTestNetwork"),r=await o.locator("label[data-testid='toggleTestNetwork-switch'] > input[aria-label='Toggle']").isChecked().catch(()=>!1);if(!r&&e.mode==="on"&&await o.click(),r&&e.mode==="off"){await o.click(),await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click();return}if(e.mode==="on"&&e.chain==="Solana"){let{network:s}=e;await t.locator(`button:has-text("${s}")`).click()}if(e.mode==="on"&&e.chain==="Ethereum"){let{network:s}=e;if(!await t.getByText("EVM",{exact:!0}).isVisible().catch(()=>!1))throw new Error(["EVM testnet options are not available. Please ensure Ethereum is enabled in optional chains.","To enable Ethereum, call the 'toggleOptionalChain' action before switching the network.","toggleOptionalChain({ page: page, toggleMode: 'on', supportedChains: ['Ethereum'] })","Tip: For persistence, enable Ethereum in your setup file after the onboarding step completes."].join(`
14
14
  `));await t.locator(`button:has-text("${s}")`).click()}await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function Ne({page:t,addWallet:e,...a}){console.info(Uo("yellowBright",`
15
- Phantom onboarding started...`,{validateStream:!1}));let o=await k("phantom");if(a.mode==="create"){await t.locator(B.createNewWalletButton).click(),await t.getByTestId(B.createSeedPhraseWalletButton).click();let w=t.getByTestId(B.passwordInput),d=t.getByTestId(B.passwordConfirmInput),g=t.getByTestId(B.termsCheckBox),f=t.locator(B.continueButton);await w.fill(o),await d.fill(o),await g.click(),await f.click(),await f.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.getByTestId(B.recoveryPhraseSavedCheckbox).click(),await f.click(),await y(1e3),await f.click(),await t.locator(B.getStartedButton).last().click()}if(a.mode==="recovery phrase"){let p=a.secretRecoveryPhrase.split(" ");await t.locator(B.IAlreadyHaveAWalletButton).click(),await t.locator(B.importRecoveryPhraseButton).click();for(let[nt,et]of Object.entries(p))await t.getByTestId(`${B.recoveryPhraseInput}-${nt}`).fill(et);await t.locator(B.importWalletButton).click(),await t.locator("p:has-text('Finding accounts with activity')").waitFor({state:"detached",timeout:6e4});let h=t.locator(B.continueButton);await h.click();let S=t.getByTestId(B.passwordInput),A=t.getByTestId(B.passwordConfirmInput),C=t.getByTestId(B.termsCheckBox);await S.fill(o),await A.fill(o),await C.click(),await h.click(),await h.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(B.getStartedButton).last().click()}if(a.mode==="private key"){await t.locator(B.IAlreadyHaveAWalletButton).click();let{privateKey:p,chain:w,accountName:d}=a;await t.locator(B.importPrivateKeyButton).click();let f=t.locator("span[id='button--listbox-input--1']"),h=await f.textContent(),S=t.locator("input[name='name']"),A=t.locator("textarea[name='privateKey']");h!==w&&(await f.click(),await t.locator("ul[id='listbox--listbox-input--1']").locator(`li[data-label='${w}']`).click()),await S.fill(d),await A.fill(p),await t.locator("button:has-text('Import')").click();let R=t.getByTestId(B.passwordInput),V=t.getByTestId(B.passwordConfirmInput),nt=t.getByTestId(B.termsCheckBox);await R.fill(o),await V.fill(o),await nt.click();let et=t.locator(B.continueButton);await et.click(),await et.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(B.getStartedButton).last().click()}let n=await t.context().newPage(),r=await new tt().indexUrl();await n.goto(r);let c=await t.context().browser()?.newBrowserCDPSession(),s;await gn.poll(async()=>{if(c){let{targetInfos:m}=await c.send("Target.getTargets"),w=m.filter(d=>d.title==="Phantom Wallet").find(d=>!d.attached&&d.url===r);return s=w,!!w}},{timeout:2e4}).toBe(!0),s&&await c?.send("Target.closeTarget",{targetId:s.targetId});let l=await n.getByTestId("home-header-account-name").textContent();if(a.mode==="create"){let{accountName:m}=a;await ie({page:n,newAccountName:m,currentAccountName:"Account 1"})}if(e&&e.length>0){let m=!1;Et(n,()=>m).catch(d=>console.error({error:d}));for(let{accountName:d,chain:g,privateKey:f}of e)await re({page:n,privateKey:f,accountName:d,chain:g}),m=!0;let w=a.mode==="create"?a.accountName:l;w&&await Mt(n,w)}a.toggleNetworkMode&&await se({page:n,...a.toggleNetworkMode}),await y(3e3),console.info(Uo("greenBright","\u2728 Phantom onboarding completed successfully",{validateStream:!1}))}async function Ko(t){let e=t.getByTestId(Nt.cancelButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"}),await e.click()}async function Ho({page:t,supportedChains:e,toggleMode:a="off"}){if(await ce(t),await t.locator("button[id='settings-item-active-networks']").click(),e.length===0)throw Error("Supported chains array cannot be empty for toggle mode other than 'onboard'");for(let i of e){let c=t.locator(`button[id='toggle-${i.toLowerCase()}']`),l=await c.locator(`label[data-testid='toggle-${i.toLowerCase()}-switch'] > input[aria-label='Toggle']`).isChecked().catch(()=>!1);a==="off"&&l&&await c.click(),a==="on"&&!l&&await c.click()}await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function le(t){let e=await k("phantom"),a=t.locator("input[name='password']"),o=t.getByTestId("unlock-form-submit-button");await a.fill(e),await o.click(),await o.waitFor({state:"detached"})}var dt=class extends tt{page;constructor(e){super(),this.page=e}async onboard({...e}){await Ne({page:this.page,...e})}async unlock(){await le(this.page)}async lock(){await Do(this.page)}async renameAccount({...e}){await ie({page:this.page,...e})}async switchAccount(e){await Mt(this.page,e)}async getAccountAddress({accountName:e,chain:a}){return await Oo({page:this.page,accountName:e,chain:a})}async addAccount({...e}){await re({page:this.page,...e})}async toggleOptionalChains({toggleMode:e,supportedChains:a}){await Ho({page:this.page,supportedChains:a,toggleMode:e})}async switchNetwork({...e}){await se({page:this.page,...e})}async connectToApp(e){await Lo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await $o(await this.promptPage(this.page.context()))}async rejectTransaction(){await Ko(await this.promptPage(this.page.context()))}};import jo from"fs";import hn from"path";import{test as yn,chromium as xn}from"@playwright/test";var Rt,jd=({slowMo:t=0,profileName:e}={})=>yn.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new tt,i=x(r.name),c=await I(r.name),s=hn.resolve(i,e??"wallet-data");if(!jo.existsSync(s))throw new Error("\u274C Cache for Phantom wallet data not found. Create it first");jo.cpSync(s,o,{recursive:!0,force:!0}),process.env.HEADLESS&&t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!");let l=await xn.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`,`--load-extension=${c}`],slowMo:process.env.HEADLESS?0:t});await l.grantPermissions(["clipboard-read"]);let{cookies:u,origins:m}=await a.storageState();u&&await l.addCookies(u),m&&m.length>0&&await $(m,l);let p=await r.indexUrl();Rt=l.pages().find(d=>d.url().startsWith(p))||await E(l,p);for(let d of l.pages())d.url().includes("about:blank")&&await d.close();await Rt.bringToFront(),await le(Rt),await n(l),await b(l,o)},phantomPage:async({context:a},o)=>{await o(Rt)},phantom:async({context:a},o)=>{let n=new dt(Rt);await o(n)},autoCloseNotification:[async({context:a},o)=>{let n=!1,i=Et(Rt,()=>n);await o(void 0),n=!0,await i.catch(c=>{console.error(`Auto close notification error: ${c.message}`)})},{auto:!0}]});import{test as bn}from"@playwright/test";import Go from"fs";import Bn from"path";import{chromium as kn}from"@playwright/test";async function zo({workerInfo:t,profileName:e,slowMo:a}){let o=new tt,n=await v(t.workerIndex.toString()),r=x(o.name),i=Bn.resolve(r,e??"wallet-data");if(!Go.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);Go.cpSync(i,n,{recursive:!0,force:!0});let c=await I(o.name),s=await kn.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),l=await o.indexUrl(),u=await E(s,l);return{context:s,walletPage:u,contextPath:n}}var cw=({slowMo:t,profileName:e,dappUrl:a}={})=>bn.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await zo({workerInfo:r,profileName:e,slowMo:t});await i.grantPermissions(["clipboard-read"]);for(let u of i.pages())u.url().includes("about:blank")&&await u.close();let l=new dt(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],phantomPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},phantom:async({workerScopeContents:o},n)=>{let r=new dt(o.walletPage);await n(r)},autoCloseNotification:[async({workerScopeContents:o},n)=>{let r=!1,i=()=>r,c=Et(o.walletPage,i);await n(void 0),r=!0,await c.catch(s=>{console.error(`Auto close notification error: ${s.message}`)})},{auto:!0}]});var wt={networkSettings:"li-settings-network",selectNetwork:"select-network",confirmModal:"modal-confirm",confifmButton:"btn-confirm",securityAndPrivacyButton:"nav-item-security-and-privacy",lockButton:"btn-lock"},_t={portfolioButton:"nav-item-portfolio",walletSelectorButton:"icon-section-wallet-picker-arrow-right"};import ue from"zod";var qo=ue.object({walletName:ue.string().min(1,"Wallet name cannot be an empty string"),privateKey:ue.array(ue.number()).length(64)});async function me({page:t,privateKey:e,walletName:a}){let o=qo.parse({privateKey:e,walletName:a});await t.getByTestId(_t.walletSelectorButton).click(),await t.getByTestId("icon-btn-add").click(),await t.getByTestId("li-add-wallet-privateKey-add").click();let c=t.getByTestId("input-name"),s=t.getByTestId("input-private-key");await c.fill(o.walletName),await s.fill(`${o.privateKey}`),await t.getByTestId("btn-import").click(),await t.locator("span:has-text('My wallets')").waitFor({state:"attached"}),await t.getByRole("dialog").getByTestId("icon-btn-close").click()}import{expect as Pn}from"@playwright/test";var pe={approveButton:"btn-approve",rejectButton:"btn-reject"};async function Yo(t){let e=t.getByTestId(pe.approveButton);await t.getByTestId("section-network-fee").waitFor({state:"attached",timeout:4e4});let o=t.locator("div[data-id='control-label']");await o.isVisible().catch(()=>!1)&&await o.click(),await Pn(e).toBeEnabled(),await e.click()}async function de(t,e){await t.getByTestId("icon-section-wallet-picker-arrow-right").click();let o=t.getByTestId("list-item-m-title").filter({hasText:e}).locator("xpath=../..");if(!await o.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);await o.click()}async function Qo(t,e){e&&await de(t,e),await t.getByRole("button",{name:"Connect",exact:!0}).click()}async function Xo(t){return await t.getByTestId("icon-section-wallet-picker-copy").click(),await t.evaluate(async()=>await navigator.clipboard.readText())}async function we(t){let e=t.getByRole("button",{name:"settings",exact:!0});await e.waitFor({state:"attached",timeout:3e4}),await e.click()}async function Zo(t){await we(t),await t.getByTestId(wt.securityAndPrivacyButton).click(),await t.getByTestId("li-settings-lock").getByTestId(wt.lockButton).click()}import{styleText as Jo}from"util";var it={alreadyHaveAWalletButton:"btn-already-have-wallet",recoveryPhraseInput:"input-recovery-phrase",continueButton:"btn-continue",passwordInput:"input-new-password",repeatPasswordInput:"input-repeat-password",quickSetupButton:"btn-quick-setup",IAgreeButton:"btn-explore"};async function fe({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(_t.walletSelectorButton).click();let n=t.locator(`button[data-testid^='li-wallets']:has-text('${e}')`);if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is available.`);await n.hover({timeout:2e4}),await n.getByTestId("icon-btn-three-dots").click({timeout:2e4});let c=t.getByTestId("li-manage-wallet-rename-wallet");await c.click();let s=t.getByTestId("input-name");await s.clear(),await s.fill(a),await t.getByTestId("btn-save").click(),await c.waitFor({state:"attached",timeout:15e3}),await t.getByTestId("icon-btn-close").click()}async function ge(t,e){await we(t);let o=t.getByTestId("li-settings-network").getByRole("combobox");await o.locator(" > p").textContent()!==e?(await o.click(),await t.getByTestId(wt.selectNetwork).getByRole("option",{name:e,exact:!0}).click(),(e==="Devnet"||e==="Testnet")&&await t.getByTestId(wt.confirmModal).getByTestId(wt.confifmButton).click()):console.info(`Network is already set to ${e}`),await t.getByTestId(_t.portfolioButton).click()}async function ta({page:t,recoveryPhrase:e,network:a,walletName:o,addWallet:n}){console.info(Jo("yellowBright",`
15
+ Phantom onboarding started...`,{validateStream:!1}));let o=await k("phantom");if(a.mode==="create"){await t.locator(B.createNewWalletButton).click(),await t.getByTestId(B.createSeedPhraseWalletButton).click();let w=t.getByTestId(B.passwordInput),d=t.getByTestId(B.passwordConfirmInput),g=t.getByTestId(B.termsCheckBox),f=t.locator(B.continueButton);await w.fill(o),await d.fill(o),await g.click(),await f.click(),await f.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.getByTestId(B.recoveryPhraseSavedCheckbox).click(),await f.click(),await y(1e3),await f.click(),await t.locator(B.getStartedButton).last().click()}if(a.mode==="recovery phrase"){let p=a.secretRecoveryPhrase.split(" ");await t.locator(B.IAlreadyHaveAWalletButton).click(),await t.locator(B.importRecoveryPhraseButton).click();for(let[nt,et]of Object.entries(p))await t.getByTestId(`${B.recoveryPhraseInput}-${nt}`).fill(et);await t.locator(B.importWalletButton).click(),await t.locator("p:has-text('Finding accounts with activity')").waitFor({state:"detached",timeout:6e4});let h=t.locator(B.continueButton);await h.click();let S=t.getByTestId(B.passwordInput),A=t.getByTestId(B.passwordConfirmInput),C=t.getByTestId(B.termsCheckBox);await S.fill(o),await A.fill(o),await C.click(),await h.click(),await h.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(B.getStartedButton).last().click()}if(a.mode==="private key"){await t.locator(B.IAlreadyHaveAWalletButton).click();let{privateKey:p,chain:w,accountName:d}=a;await t.locator(B.importPrivateKeyButton).click();let f=t.locator("span[id='button--listbox-input--1']"),h=await f.textContent(),S=t.locator("input[name='name']"),A=t.locator("textarea[name='privateKey']");h!==w&&(await f.click(),await t.locator("ul[id='listbox--listbox-input--1']").locator(`li[data-label='${w}']`).click()),await S.fill(d),await A.fill(p),await t.locator("button:has-text('Import')").click();let R=t.getByTestId(B.passwordInput),V=t.getByTestId(B.passwordConfirmInput),nt=t.getByTestId(B.termsCheckBox);await R.fill(o),await V.fill(o),await nt.click();let et=t.locator(B.continueButton);await et.click(),await et.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(B.getStartedButton).last().click()}let n=await t.context().newPage(),r=await new tt().indexUrl();await n.goto(r);let c=await t.context().browser()?.newBrowserCDPSession(),s;await gn.poll(async()=>{if(c){let{targetInfos:m}=await c.send("Target.getTargets"),w=m.filter(d=>d.title==="Phantom Wallet").find(d=>!d.attached&&d.url===r);return s=w,!!w}},{timeout:2e4}).toBe(!0),s&&await c?.send("Target.closeTarget",{targetId:s.targetId});let l=await n.getByTestId("home-header-account-name").textContent();if(a.mode==="create"){let{accountName:m}=a;await ie({page:n,newAccountName:m,currentAccountName:"Account 1"})}if(e&&e.length>0){let m=!1;Et(n,()=>m).catch(d=>console.error({error:d}));for(let{accountName:d,chain:g,privateKey:f}of e)await re({page:n,privateKey:f,accountName:d,chain:g}),m=!0;let w=a.mode==="create"?a.accountName:l;w&&await Mt(n,w)}a.toggleNetworkMode&&await se({page:n,...a.toggleNetworkMode}),await y(3e3),console.info(Uo("greenBright","\u2728 Phantom onboarding completed successfully",{validateStream:!1}))}async function Ko(t){let e=t.getByTestId(Nt.cancelButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"}),await e.click()}async function Ho({page:t,supportedChains:e,toggleMode:a="off"}){if(await ce(t),await t.locator("button[id='settings-item-active-networks']").click(),e.length===0)throw Error("Supported chains array cannot be empty for toggle mode other than 'onboard'");for(let i of e){let c=t.locator(`button[id='toggle-${i.toLowerCase()}']`),l=await c.locator(`label[data-testid='toggle-${i.toLowerCase()}-switch'] > input[aria-label='Toggle']`).isChecked().catch(()=>!1);a==="off"&&l&&await c.click(),a==="on"&&!l&&await c.click()}await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function le(t){let e=await k("phantom"),a=t.locator("input[name='password']"),o=t.getByTestId("unlock-form-submit-button");await a.fill(e),await o.click(),await o.waitFor({state:"detached"})}var dt=class extends tt{page;constructor(e){super(),this.page=e}async onboard({...e}){await Ne({page:this.page,...e})}async unlock(){await le(this.page)}async lock(){await Do(this.page)}async renameAccount({...e}){await ie({page:this.page,...e})}async switchAccount(e){await Mt(this.page,e)}async getAccountAddress({accountName:e,chain:a}){return await Oo({page:this.page,accountName:e,chain:a})}async addAccount({...e}){await re({page:this.page,...e})}async toggleOptionalChains({toggleMode:e,supportedChains:a}){await Ho({page:this.page,supportedChains:a,toggleMode:e})}async switchNetwork({...e}){await se({page:this.page,...e})}async connectToApp(e){await Lo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await $o(await this.promptPage(this.page.context()))}async rejectTransaction(){await Ko(await this.promptPage(this.page.context()))}};import jo from"fs";import hn from"path";import{test as yn,chromium as xn}from"@playwright/test";var Rt,jd=({slowMo:t=0,profileName:e}={})=>yn.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new tt,i=x(r.name),c=await I(r.name),s=hn.resolve(i,e??"wallet-data");if(!jo.existsSync(s))throw new Error("\u274C Cache for Phantom wallet data not found. Create it first");jo.cpSync(s,o,{recursive:!0,force:!0}),process.env.HEADLESS&&t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!");let l=await xn.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`,`--load-extension=${c}`],slowMo:process.env.HEADLESS?0:t});await l.grantPermissions(["clipboard-read"]);let{cookies:u,origins:m}=await a.storageState();u&&await l.addCookies(u),m&&m.length>0&&await $(m,l);let p=await r.indexUrl();Rt=l.pages().find(d=>d.url().startsWith(p))||await E(l,p);for(let d of l.pages())d.url().includes("about:blank")&&await d.close();await Rt.bringToFront(),await le(Rt),await n(l),await b(l,o)},phantomPage:async({context:a},o)=>{await o(Rt)},phantom:async({context:a},o)=>{let n=new dt(Rt);await o(n)},autoCloseNotification:[async({context:a},o)=>{let n=!1,i=Et(Rt,()=>n);await o(void 0),n=!0,await i.catch(c=>{console.error(`Auto close notification error: ${c.message}`)})},{auto:!0}]});import{test as bn}from"@playwright/test";import Go from"fs";import Bn from"path";import{chromium as kn}from"@playwright/test";async function zo({workerInfo:t,profileName:e,slowMo:a}){let o=new tt,n=await v(t.workerIndex.toString()),r=x(o.name),i=Bn.resolve(r,e??"wallet-data");if(!Go.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);Go.cpSync(i,n,{recursive:!0,force:!0});let c=await I(o.name),s=await kn.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),l=await o.indexUrl(),u=await E(s,l);return{context:s,walletPage:u,contextPath:n}}var cw=({slowMo:t,profileName:e,dappUrl:a}={})=>bn.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await zo({workerInfo:r,profileName:e,slowMo:t});await i.grantPermissions(["clipboard-read"]);for(let u of i.pages())u.url().includes("about:blank")&&await u.close();let l=new dt(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],phantomPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},phantom:async({workerScopeContents:o},n)=>{let r=new dt(o.walletPage);await n(r)},autoCloseNotification:[async({workerScopeContents:o},n)=>{let r=!1,i=()=>r,c=Et(o.walletPage,i);await n(void 0),r=!0,await c.catch(s=>{console.error(`Auto close notification error: ${s.message}`)})},{auto:!0}]});var wt={networkSettings:"li-settings-network",selectNetwork:"select-network",confirmModal:"modal-confirm",confifmButton:"btn-confirm",securityAndPrivacyButton:"nav-item-security-and-privacy",lockButton:"btn-lock"},_t={portfolioButton:"nav-item-portfolio",walletSelectorButton:"icon-section-wallet-picker-arrow-right"};import ue from"zod";var qo=ue.object({walletName:ue.string().min(1,"Wallet name cannot be an empty string"),privateKey:ue.array(ue.number()).length(64)});async function me({page:t,privateKey:e,walletName:a}){let o=qo.parse({privateKey:e,walletName:a});await t.getByTestId(_t.walletSelectorButton).click(),await t.getByTestId("icon-btn-add").click(),await t.getByTestId("li-add-wallet-privateKey-add").click();let c=t.getByTestId("input-name"),s=t.getByTestId("input-private-key");await c.fill(o.walletName),await s.fill(`${o.privateKey}`),await t.getByTestId("btn-import").click(),await t.locator("span:has-text('My wallets')").waitFor({state:"attached"}),await t.getByRole("dialog").getByTestId("icon-btn-close").click()}import{expect as Pn}from"@playwright/test";var pe={approveButton:"btn-approve",rejectButton:"btn-reject"};async function Yo(t){let e=t.getByTestId(pe.approveButton);await t.getByTestId("section-network-fee").waitFor({state:"attached",timeout:3e4}).catch(async()=>{console.error("Network fee section did not appear within the timeout period, which may indicate that the transaction confirmation popup did not load correctly."),await t.getByText("Network mismatch",{exact:!0}).isVisible().catch(()=>!1)&&(await t.getByRole("button",{name:"Close",exact:!0}).click(),console.error("A 'Network mismatch' error was detected in the popup. Closing the popup and aborting the transaction confirmation process."))});let o=t.locator("div[data-id='control-label']");await o.isVisible().catch(()=>!1)&&await o.click(),await Pn(e).toBeEnabled(),await e.click()}async function de(t,e){await t.getByTestId("icon-section-wallet-picker-arrow-right").click();let o=t.getByTestId("list-item-m-title").filter({hasText:e}).locator("xpath=../..");if(!await o.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);await o.click()}async function Qo(t,e){e&&await de(t,e),await t.getByRole("button",{name:"Connect",exact:!0}).click()}async function Xo(t){return await t.getByTestId("icon-section-wallet-picker-copy").click(),await t.evaluate(async()=>await navigator.clipboard.readText())}async function we(t){let e=t.getByRole("button",{name:"settings",exact:!0});await e.waitFor({state:"attached",timeout:3e4}),await e.click()}async function Zo(t){await we(t),await t.getByTestId(wt.securityAndPrivacyButton).click(),await t.getByTestId("li-settings-lock").getByTestId(wt.lockButton).click()}import{styleText as Jo}from"util";var it={alreadyHaveAWalletButton:"btn-already-have-wallet",recoveryPhraseInput:"input-recovery-phrase",continueButton:"btn-continue",passwordInput:"input-new-password",repeatPasswordInput:"input-repeat-password",quickSetupButton:"btn-quick-setup",IAgreeButton:"btn-explore"};async function fe({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(_t.walletSelectorButton).click();let n=t.locator(`button[data-testid^='li-wallets']:has-text('${e}')`);if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is available.`);await n.hover({timeout:2e4}),await n.getByTestId("icon-btn-three-dots").click({timeout:2e4});let c=t.getByTestId("li-manage-wallet-rename-wallet");await c.click();let s=t.getByTestId("input-name");await s.clear(),await s.fill(a),await t.getByTestId("btn-save").click(),await c.waitFor({state:"attached",timeout:15e3}),await t.getByTestId("icon-btn-close").click()}async function ge(t,e){await we(t);let o=t.getByTestId("li-settings-network").getByRole("combobox");await o.locator(" > p").textContent()!==e?(await o.click(),await t.getByTestId(wt.selectNetwork).getByRole("option",{name:e,exact:!0}).click(),(e==="Devnet"||e==="Testnet")&&await t.getByTestId(wt.confirmModal).getByTestId(wt.confifmButton).click()):console.info(`Network is already set to ${e}`),await t.getByTestId(_t.portfolioButton).click()}async function ta({page:t,recoveryPhrase:e,network:a,walletName:o,addWallet:n}){console.info(Jo("yellowBright",`
16
16
  Solflare onboarding started...`,{validateStream:!1}));let r=await k("solflare");await t.getByTestId(it.alreadyHaveAWalletButton).click();let c=e.split(" ");for(let[g,f]of Object.entries(c))await t.getByTestId(`${it.recoveryPhraseInput}-${Number(g)+1}`).fill(f);let s=t.getByTestId(it.continueButton);await s.click();let l=t.getByTestId(it.passwordInput),u=t.getByTestId(it.repeatPasswordInput);if(await l.fill(r),await u.fill(r),await s.click(),await t.locator("div",{hasText:"Detecting your existing accounts. This process can take up to a minute."}).waitFor({state:"detached"}),await t.getByTestId(it.quickSetupButton).click(),await t.getByTestId(it.IAgreeButton).click(),await fe({page:t,currentAccountName:"Main Wallet",newAccountName:o}),a&&await ge(t,a),n&&n?.length>0)for(let{privateKey:g,walletName:f}of n)await me({page:t,privateKey:g,walletName:f});console.info(Jo("greenBright","\u2728 Solflare onboarding completed successfully",{validateStream:!1}))}async function ea(t){await t.getByTestId(pe.rejectButton).click()}async function he(t){let e=await k("solflare");await t.getByTestId("input-password").fill(e),await t.getByTestId("btn-unlock").click(),await t.getByTestId("nav-main").waitFor({state:"attached",timeout:3e4})}var ct=class{name="solflare";onboardingPath="wallet.html#/onboard";async indexUrl(){return`chrome-extension://${await this.extensionId()}/wallet.html#/portfolio`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/confirm_popup.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[data-testid='page-dapp-connect'], div[data-testid='page-tx-sign']"})}};var ft=class extends ct{page;constructor(e){super(),this.page=e}async onboard({recoveryPhrase:e,network:a,addWallet:o,walletName:n}){await ta({page:this.page,recoveryPhrase:e,network:a,addWallet:o,walletName:n})}async unlock(){await he(this.page)}async lock(){await Zo(this.page)}async renameAccount({currentAccountName:e,newAccountName:a}){await fe({page:this.page,currentAccountName:e,newAccountName:a})}async switchNetwork(e){await ge(this.page,e)}async switchAccount(e){await de(this.page,e)}async getAccountAddress(){return await Xo(this.page)}async addAccount({privateKey:e,walletName:a}){await me({page:this.page,privateKey:e,walletName:a})}async connectToApp(e){await Qo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await Yo(await this.promptPage(this.page.context()))}async rejectTransaction(){await ea(await this.promptPage(this.page.context()))}};import oa from"fs";import An from"path";import{test as Cn,chromium as Sn}from"@playwright/test";async function ye(t,e){let o=!1;for(;!e();){let n=e();if(n||o||t.isClosed())break;try{let r=t.locator("div[role='dialog']").locator("button[data-testid='icon-btn-whats-new-modal-close']");await r.isVisible().catch(()=>!1)&&(await r.click(),o=!0)}catch(r){console.error("[autoCloseSolflareNotification]: ",r)}if(n||o||t.isClosed())break;await y(150)}}var Gt,Sf=({slowMo:t=0,profileName:e}={})=>Cn.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new ct,i=x(r.name),c=await I(r.name),s=An.resolve(i,e??"wallet-data");if(!oa.existsSync(s))throw new Error("\u274C Cache for Solflare wallet data not found. Create it first");await oa.promises.cp(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await Sn.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t});await u.grantPermissions(["clipboard-read"]);let{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl(),d=w.split("#")[0]??"";await u.waitForEvent("page",{predicate:f=>f.url().includes(d),timeout:15e3}),Gt=u.pages().find(f=>f.url().startsWith(d))||await E(u,w);for(let f of u.pages())f.url().includes("about:blank")&&await f.close();await he(Gt),await n(u),await b(u,o)},solflarePage:async({context:a},o)=>{await o(Gt)},solflare:async({context:a},o)=>{let n=new ft(Gt);await o(n)},autoCloseNotification:[async({context:a},o)=>{let n=!1,i=ye(Gt,()=>n);await o(void 0),n=!0,await i.catch(c=>{console.error(`Auto close notification error: ${c.message}`)})},{auto:!0}]});import{test as Tn}from"@playwright/test";import aa from"fs";import vn from"path";import{chromium as In}from"@playwright/test";async function na({workerInfo:t,profileName:e,slowMo:a}){let o=new ct,n=await v(t.workerIndex.toString()),r=x(o.name),i=vn.resolve(r,e??"wallet-data");if(!aa.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);aa.cpSync(i,n,{recursive:!0,force:!0});let c=await I(o.name),s=await In.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),l=await o.indexUrl(),u=l.split("#")[0]??"";await s.waitForEvent("page",{predicate:p=>p.url().includes(u),timeout:15e3});let m=s.pages().find(p=>p.url().startsWith(u));m||(m=await s.newPage(),await m.goto(l),await M(m));for(let p of s.pages())p.url().includes("about:blank")&&await p.close();return{context:s,walletPage:m,contextPath:n}}var Uf=({slowMo:t,profileName:e,dappUrl:a}={})=>Tn.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await na({workerInfo:r,profileName:e,slowMo:t});await i.grantPermissions(["clipboard-read"]);let l=new ft(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],solflarePage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},solflare:async({workerScopeContents:o},n)=>{let r=new ft(o.walletPage);await n(r)},autoCloseNotification:[async({workerScopeContents:o},n)=>{let r=!1,i=()=>r,c=ye(o.walletPage,i);await n(void 0),r=!0,await c.catch(s=>{console.error(`Auto close notification error: ${s.message}`)})},{auto:!0}]});export{st as Keplr,lt as Metamask,ut as Meteor,pt as Petra,dt as Phantom,ft as Solflare,xi as keplrFixture,Mi as keplrWorkerScopeFixture,Rs as metamaskFixture,Xs as metamaskWorkerScopeFixture,Cu as meteorFixture,Nu as meteorWorkerScopeFixture,sp as petraFixture,fp as petraWorkerScopeFixture,jd as phantomFixture,cw as phantomWorkerScopeFixture,Sf as solflareFixture,Uf as solflareWorkerScopeFixture};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tobelabs/chainwright",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "An end-to-end testing framework built on top of Playwright for Web3 wallet interactions",
5
5
  "type": "module",
6
6
  "license": "MIT",