@buoy-gg/mcp 7.0.77 → 7.0.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/SyncClient-gqMRmB79.d.mts +374 -0
- package/dist/SyncClient-gqMRmB79.d.ts +374 -0
- package/dist/{chunk-LF3VF3PO.mjs → chunk-3FTJ74HL.mjs} +1 -1
- package/dist/{chunk-XA74T4JN.mjs → chunk-5XATNNKY.mjs} +2 -2
- package/dist/{chunk-ODGXMS2O.mjs → chunk-FYJWWTAC.mjs} +5 -4
- package/dist/chunk-HZEASQD3.mjs +980 -0
- package/dist/{chunk-ZMFF6TOQ.mjs → chunk-MR4NVULE.mjs} +1 -1
- package/dist/{chunk-3O76SJJM.mjs → chunk-SGVMY5TU.mjs} +1 -1
- package/dist/chunk-TMN3LXKB.mjs +42 -0
- package/dist/cli.js +285 -222
- package/dist/cli.mjs +12 -12
- package/dist/flowRun-4VU3KXYX.mjs +2 -0
- package/dist/index.d.mts +9 -370
- package/dist/index.d.ts +9 -370
- package/dist/index.js +231 -168
- package/dist/index.mjs +1 -1
- package/dist/{init-VRHZTW2F.mjs → init-6ANI6DIF.mjs} +1 -1
- package/dist/{main-NJB22OCH.mjs → main-XP2I2BCD.mjs} +2 -2
- package/dist/nativeProfiler.d.mts +184 -0
- package/dist/nativeProfiler.d.ts +184 -0
- package/dist/nativeProfiler.js +157 -0
- package/dist/nativeProfiler.mjs +1 -0
- package/dist/{simFarm-R4P6QXRK.mjs → simFarm-AWVHVU6A.mjs} +1 -1
- package/dist/{src-R7ICMP6Q.mjs → src-HRUK7GEE.mjs} +1 -1
- package/package.json +16 -5
- package/dist/chunk-OG34S7G6.mjs +0 -959
- package/dist/flowRun-XKE2FG3B.mjs +0 -2
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(e,t)=>function r(){return t||(0,e[__getOwnPropNames(e)[0]])((t={exports:{}}).exports,t),t.exports};var __export=(e,t)=>{for(var r in t)__defProp(e,r,{get:t[r],enumerable:true})};var __copyProps=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let a of __getOwnPropNames(t))if(!__hasOwnProp.call(e,a)&&a!==r)__defProp(e,a,{get:()=>t[a],enumerable:!(o=__getOwnPropDesc(t,a))||o.enumerable})}return e};var __toESM=(e,t,r)=>(r=e!=null?__create(__getProtoOf(e)):{},__copyProps(t||!e||!e.__esModule?__defProp(r,"default",{value:e,enumerable:true}):r,e));var __toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:true}),e);var require_chunkstream=__commonJS({"../../node_modules/pngjs/lib/chunkstream.js"(e,t){"use strict";var r=require("util");var o=require("stream");var a=t.exports=function(){o.call(this);this._buffers=[];this._buffered=0;this._reads=[];this._paused=false;this._encoding="utf8";this.writable=true};r.inherits(a,o);a.prototype.read=function(i,n){this._reads.push({length:Math.abs(i),allowLess:i<0,func:n});process.nextTick(function(){this._process();if(this._paused&&this._reads&&this._reads.length>0){this._paused=false;this.emit("drain")}}.bind(this))};a.prototype.write=function(i,n){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let s;if(Buffer.isBuffer(i)){s=i}else{s=Buffer.from(i,n||this._encoding)}this._buffers.push(s);this._buffered+=s.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};a.prototype.end=function(i,n){if(i){this.write(i,n)}this.writable=false;if(!this._buffers){return}if(this._buffers.length===0){this._end()}else{this._buffers.push(null);this._process()}};a.prototype.destroySoon=a.prototype.end;a.prototype._end=function(){if(this._reads.length>0){this.emit("error",new Error("Unexpected end of input"))}this.destroy()};a.prototype.destroy=function(){if(!this._buffers){return}this.writable=false;this._reads=null;this._buffers=null;this.emit("close")};a.prototype._processReadAllowingLess=function(i){this._reads.shift();let n=this._buffers[0];if(n.length>i.length){this._buffered-=i.length;this._buffers[0]=n.slice(i.length);i.func.call(this,n.slice(0,i.length))}else{this._buffered-=n.length;this._buffers.shift();i.func.call(this,n)}};a.prototype._processRead=function(i){this._reads.shift();let n=0;let s=0;let c=Buffer.alloc(i.length);while(n<i.length){let l=this._buffers[s++];let h=Math.min(l.length,i.length-n);l.copy(c,n,0,h);n+=h;if(h!==l.length){this._buffers[--s]=l.slice(h)}}if(s>0){this._buffers.splice(0,s)}this._buffered-=i.length;i.func.call(this,c)};a.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let i=this._reads[0];if(i.allowLess){this._processReadAllowingLess(i)}else if(this._buffered>=i.length){this._processRead(i)}else{break}}if(this._buffers&&!this.writable){this._end()}}catch(i){this.emit("error",i)}}}});var require_interlace=__commonJS({"../../node_modules/pngjs/lib/interlace.js"(e){"use strict";var t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(r,o){let a=[];let i=r%8;let n=o%8;let s=(r-i)/8;let c=(o-n)/8;for(let l=0;l<t.length;l++){let h=t[l];let u=s*h.x.length;let d=c*h.y.length;for(let f=0;f<h.x.length;f++){if(h.x[f]<i){u++}else{break}}for(let f=0;f<h.y.length;f++){if(h.y[f]<n){d++}else{break}}if(u>0&&d>0){a.push({width:u,height:d,index:l})}}return a};e.getInterlaceIterator=function(r){return function(o,a,i){let n=o%t[i].x.length;let s=(o-n)/t[i].x.length*8+t[i].x[n];let c=a%t[i].y.length;let l=(a-c)/t[i].y.length*8+t[i].y[c];return s*4+l*r*4}}}});var require_paeth_predictor=__commonJS({"../../node_modules/pngjs/lib/paeth-predictor.js"(e,t){"use strict";t.exports=function r(o,a,i){let n=o+a-i;let s=Math.abs(n-o);let c=Math.abs(n-a);let l=Math.abs(n-i);if(s<=c&&s<=l){return o}if(c<=l){return a}return i}}});var require_filter_parse=__commonJS({"../../node_modules/pngjs/lib/filter-parse.js"(e,t){"use strict";var r=require_interlace();var o=require_paeth_predictor();function a(n,s,c){let l=n*s;if(c!==8){l=Math.ceil(l/(8/c))}return l}var i=t.exports=function(n,s){let c=n.width;let l=n.height;let h=n.interlace;let u=n.bpp;let d=n.depth;this.read=s.read;this.write=s.write;this.complete=s.complete;this._imageIndex=0;this._images=[];if(h){let f=r.getImagePasses(c,l);for(let _=0;_<f.length;_++){this._images.push({byteWidth:a(f[_].width,u,d),height:f[_].height,lineIndex:0})}}else{this._images.push({byteWidth:a(c,u,d),height:l,lineIndex:0})}if(d===8){this._xComparison=u}else if(d===16){this._xComparison=u*2}else{this._xComparison=1}};i.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};i.prototype._unFilterType1=function(n,s,c){let l=this._xComparison;let h=l-1;for(let u=0;u<c;u++){let d=n[1+u];let f=u>h?s[u-l]:0;s[u]=d+f}};i.prototype._unFilterType2=function(n,s,c){let l=this._lastLine;for(let h=0;h<c;h++){let u=n[1+h];let d=l?l[h]:0;s[h]=u+d}};i.prototype._unFilterType3=function(n,s,c){let l=this._xComparison;let h=l-1;let u=this._lastLine;for(let d=0;d<c;d++){let f=n[1+d];let _=u?u[d]:0;let p=d>h?s[d-l]:0;let m=Math.floor((p+_)/2);s[d]=f+m}};i.prototype._unFilterType4=function(n,s,c){let l=this._xComparison;let h=l-1;let u=this._lastLine;for(let d=0;d<c;d++){let f=n[1+d];let _=u?u[d]:0;let p=d>h?s[d-l]:0;let m=d>h&&u?u[d-l]:0;let g=o(p,_,m);s[d]=f+g}};i.prototype._reverseFilterLine=function(n){let s=n[0];let c;let l=this._images[this._imageIndex];let h=l.byteWidth;if(s===0){c=n.slice(1,h+1)}else{c=Buffer.alloc(h);switch(s){case 1:this._unFilterType1(n,c,h);break;case 2:this._unFilterType2(n,c,h);break;case 3:this._unFilterType3(n,c,h);break;case 4:this._unFilterType4(n,c,h);break;default:throw new Error("Unrecognised filter type - "+s)}}this.write(c);l.lineIndex++;if(l.lineIndex>=l.height){this._lastLine=null;this._imageIndex++;l=this._images[this._imageIndex]}else{this._lastLine=c}if(l){this.read(l.byteWidth+1,this._reverseFilterLine.bind(this))}else{this._lastLine=null;this.complete()}}}});var require_filter_parse_async=__commonJS({"../../node_modules/pngjs/lib/filter-parse-async.js"(e,t){"use strict";var r=require("util");var o=require_chunkstream();var a=require_filter_parse();var i=t.exports=function(n){o.call(this);let s=[];let c=this;this._filter=new a(n,{read:this.read.bind(this),write:function(l){s.push(l)},complete:function(){c.emit("complete",Buffer.concat(s))}});this._filter.start()};r.inherits(i,o)}});var require_constants=__commonJS({"../../node_modules/pngjs/lib/constants.js"(e,t){"use strict";t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}}});var require_crc=__commonJS({"../../node_modules/pngjs/lib/crc.js"(e,t){"use strict";var r=[];(function(){for(let a=0;a<256;a++){let i=a;for(let n=0;n<8;n++){if(i&1){i=3988292384^i>>>1}else{i=i>>>1}}r[a]=i}})();var o=t.exports=function(){this._crc=-1};o.prototype.write=function(a){for(let i=0;i<a.length;i++){this._crc=r[(this._crc^a[i])&255]^this._crc>>>8}return true};o.prototype.crc32=function(){return this._crc^-1};o.crc32=function(a){let i=-1;for(let n=0;n<a.length;n++){i=r[(i^a[n])&255]^i>>>8}return i^-1}}});var require_parser=__commonJS({"../../node_modules/pngjs/lib/parser.js"(e,t){"use strict";var r=require_constants();var o=require_crc();var a=t.exports=function(i,n){this._options=i;i.checkCRC=i.checkCRC!==false;this._hasIHDR=false;this._hasIEND=false;this._emittedHeadersFinished=false;this._palette=[];this._colorType=0;this._chunks={};this._chunks[r.TYPE_IHDR]=this._handleIHDR.bind(this);this._chunks[r.TYPE_IEND]=this._handleIEND.bind(this);this._chunks[r.TYPE_IDAT]=this._handleIDAT.bind(this);this._chunks[r.TYPE_PLTE]=this._handlePLTE.bind(this);this._chunks[r.TYPE_tRNS]=this._handleTRNS.bind(this);this._chunks[r.TYPE_gAMA]=this._handleGAMA.bind(this);this.read=n.read;this.error=n.error;this.metadata=n.metadata;this.gamma=n.gamma;this.transColor=n.transColor;this.palette=n.palette;this.parsed=n.parsed;this.inflateData=n.inflateData;this.finished=n.finished;this.simpleTransparency=n.simpleTransparency;this.headersFinished=n.headersFinished||function(){}};a.prototype.start=function(){this.read(r.PNG_SIGNATURE.length,this._parseSignature.bind(this))};a.prototype._parseSignature=function(i){let n=r.PNG_SIGNATURE;for(let s=0;s<n.length;s++){if(i[s]!==n[s]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};a.prototype._parseChunkBegin=function(i){let n=i.readUInt32BE(0);let s=i.readUInt32BE(4);let c="";for(let h=4;h<8;h++){c+=String.fromCharCode(i[h])}let l=Boolean(i[4]&32);if(!this._hasIHDR&&s!==r.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}this._crc=new o;this._crc.write(Buffer.from(c));if(this._chunks[s]){return this._chunks[s](n)}if(!l){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(n+4,this._skipChunk.bind(this))};a.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};a.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};a.prototype._parseChunkEnd=function(i){let n=i.readInt32BE(0);let s=this._crc.crc32();if(this._options.checkCRC&&s!==n){this.error(new Error("Crc error - "+n+" - "+s));return}if(!this._hasIEND){this.read(8,this._parseChunkBegin.bind(this))}};a.prototype._handleIHDR=function(i){this.read(i,this._parseIHDR.bind(this))};a.prototype._parseIHDR=function(i){this._crc.write(i);let n=i.readUInt32BE(0);let s=i.readUInt32BE(4);let c=i[8];let l=i[9];let h=i[10];let u=i[11];let d=i[12];if(c!==8&&c!==4&&c!==2&&c!==1&&c!==16){this.error(new Error("Unsupported bit depth "+c));return}if(!(l in r.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(h!==0){this.error(new Error("Unsupported compression method"));return}if(u!==0){this.error(new Error("Unsupported filter method"));return}if(d!==0&&d!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=l;let f=r.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:n,height:s,depth:c,interlace:Boolean(d),palette:Boolean(l&r.COLORTYPE_PALETTE),color:Boolean(l&r.COLORTYPE_COLOR),alpha:Boolean(l&r.COLORTYPE_ALPHA),bpp:f,colorType:l});this._handleChunkEnd()};a.prototype._handlePLTE=function(i){this.read(i,this._parsePLTE.bind(this))};a.prototype._parsePLTE=function(i){this._crc.write(i);let n=Math.floor(i.length/3);for(let s=0;s<n;s++){this._palette.push([i[s*3],i[s*3+1],i[s*3+2],255])}this.palette(this._palette);this._handleChunkEnd()};a.prototype._handleTRNS=function(i){this.simpleTransparency();this.read(i,this._parseTRNS.bind(this))};a.prototype._parseTRNS=function(i){this._crc.write(i);if(this._colorType===r.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(i.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let n=0;n<i.length;n++){this._palette[n][3]=i[n]}this.palette(this._palette)}if(this._colorType===r.COLORTYPE_GRAYSCALE){this.transColor([i.readUInt16BE(0)])}if(this._colorType===r.COLORTYPE_COLOR){this.transColor([i.readUInt16BE(0),i.readUInt16BE(2),i.readUInt16BE(4)])}this._handleChunkEnd()};a.prototype._handleGAMA=function(i){this.read(i,this._parseGAMA.bind(this))};a.prototype._parseGAMA=function(i){this._crc.write(i);this.gamma(i.readUInt32BE(0)/r.GAMMA_DIVISION);this._handleChunkEnd()};a.prototype._handleIDAT=function(i){if(!this._emittedHeadersFinished){this._emittedHeadersFinished=true;this.headersFinished()}this.read(-i,this._parseIDAT.bind(this,i))};a.prototype._parseIDAT=function(i,n){this._crc.write(n);if(this._colorType===r.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(n);let s=i-n.length;if(s>0){this._handleIDAT(s)}else{this._handleChunkEnd()}};a.prototype._handleIEND=function(i){this.read(i,this._parseIEND.bind(this))};a.prototype._parseIEND=function(i){this._crc.write(i);this._hasIEND=true;this._handleChunkEnd();if(this.finished){this.finished()}}}});var require_bitmapper=__commonJS({"../../node_modules/pngjs/lib/bitmapper.js"(e){"use strict";var t=require_interlace();var r=[function(){},function(s,c,l,h){if(h===c.length){throw new Error("Ran out of data")}let u=c[h];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=255},function(s,c,l,h){if(h+1>=c.length){throw new Error("Ran out of data")}let u=c[h];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=c[h+1]},function(s,c,l,h){if(h+2>=c.length){throw new Error("Ran out of data")}s[l]=c[h];s[l+1]=c[h+1];s[l+2]=c[h+2];s[l+3]=255},function(s,c,l,h){if(h+3>=c.length){throw new Error("Ran out of data")}s[l]=c[h];s[l+1]=c[h+1];s[l+2]=c[h+2];s[l+3]=c[h+3]}];var o=[function(){},function(s,c,l,h){let u=c[0];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=h},function(s,c,l){let h=c[0];s[l]=h;s[l+1]=h;s[l+2]=h;s[l+3]=c[1]},function(s,c,l,h){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=h},function(s,c,l){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=c[3]}];function a(s,c){let l=[];let h=0;function u(){if(h===s.length){throw new Error("Ran out of data")}let d=s[h];h++;let f,_,p,m,g,v,y,w;switch(c){default:throw new Error("unrecognised depth");case 16:y=s[h];h++;l.push((d<<8)+y);break;case 4:y=d&15;w=d>>4;l.push(w,y);break;case 2:g=d&3;v=d>>2&3;y=d>>4&3;w=d>>6&3;l.push(w,y,v,g);break;case 1:f=d&1;_=d>>1&1;p=d>>2&1;m=d>>3&1;g=d>>4&1;v=d>>5&1;y=d>>6&1;w=d>>7&1;l.push(w,y,v,g,m,p,_,f);break}}return{get:function(d){while(l.length<d){u()}let f=l.slice(0,d);l=l.slice(d);return f},resetAfterLine:function(){l.length=0},end:function(){if(h!==s.length){throw new Error("extra data found")}}}}function i(s,c,l,h,u,d){let f=s.width;let _=s.height;let p=s.index;for(let m=0;m<_;m++){for(let g=0;g<f;g++){let v=l(g,m,p);r[h](c,u,v,d);d+=h}}return d}function n(s,c,l,h,u,d){let f=s.width;let _=s.height;let p=s.index;for(let m=0;m<_;m++){for(let g=0;g<f;g++){let v=u.get(h);let y=l(g,m,p);o[h](c,v,y,d)}u.resetAfterLine()}}e.dataToBitMap=function(s,c){let l=c.width;let h=c.height;let u=c.depth;let d=c.bpp;let f=c.interlace;let _;if(u!==8){_=a(s,u)}let p;if(u<=8){p=Buffer.alloc(l*h*4)}else{p=new Uint16Array(l*h*4)}let m=Math.pow(2,u)-1;let g=0;let v;let y;if(f){v=t.getImagePasses(l,h);y=t.getInterlaceIterator(l,h)}else{let w=0;y=function(){let b=w;w+=4;return b};v=[{width:l,height:h}]}for(let w=0;w<v.length;w++){if(u===8){g=i(v[w],p,y,d,s,g)}else{n(v[w],p,y,d,_,m)}}if(u===8){if(g!==s.length){throw new Error("extra data found")}}else{_.end()}return p}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,t){"use strict";function r(i,n,s,c,l){let h=0;for(let u=0;u<c;u++){for(let d=0;d<s;d++){let f=l[i[h]];if(!f){throw new Error("index "+i[h]+" not in palette")}for(let _=0;_<4;_++){n[h+_]=f[_]}h+=4}}}function o(i,n,s,c,l){let h=0;for(let u=0;u<c;u++){for(let d=0;d<s;d++){let f=false;if(l.length===1){if(l[0]===i[h]){f=true}}else if(l[0]===i[h]&&l[1]===i[h+1]&&l[2]===i[h+2]){f=true}if(f){for(let _=0;_<4;_++){n[h+_]=0}}h+=4}}}function a(i,n,s,c,l){let h=255;let u=Math.pow(2,l)-1;let d=0;for(let f=0;f<c;f++){for(let _=0;_<s;_++){for(let p=0;p<4;p++){n[d+p]=Math.floor(i[d+p]*h/u+.5)}d+=4}}}t.exports=function(i,n,s=false){let c=n.depth;let l=n.width;let h=n.height;let u=n.colorType;let d=n.transColor;let f=n.palette;let _=i;if(u===3){r(i,_,l,h,f)}else{if(d){o(i,_,l,h,d)}if(c!==8&&!s){if(c===16){_=Buffer.alloc(l*h*4)}a(i,_,l,h,c)}}return _}}});var require_parser_async=__commonJS({"../../node_modules/pngjs/lib/parser-async.js"(e,t){"use strict";var r=require("util");var o=require("zlib");var a=require_chunkstream();var i=require_filter_parse_async();var n=require_parser();var s=require_bitmapper();var c=require_format_normaliser();var l=t.exports=function(h){a.call(this);this._parser=new n(h,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)});this._options=h;this.writable=true;this._parser.start()};r.inherits(l,a);l.prototype._handleError=function(h){this.emit("error",h);this.writable=false;this.destroy();if(this._inflate&&this._inflate.destroy){this._inflate.destroy()}if(this._filter){this._filter.destroy();this._filter.on("error",function(){})}this.errord=true};l.prototype._inflateData=function(h){if(!this._inflate){if(this._bitmapInfo.interlace){this._inflate=o.createInflate();this._inflate.on("error",this.emit.bind(this,"error"));this._filter.on("complete",this._complete.bind(this));this._inflate.pipe(this._filter)}else{let u=(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1;let d=u*this._bitmapInfo.height;let f=Math.max(d,o.Z_MIN_CHUNK);this._inflate=o.createInflate({chunkSize:f});let _=d;let p=this.emit.bind(this,"error");this._inflate.on("error",function(g){if(!_){return}p(g)});this._filter.on("complete",this._complete.bind(this));let m=this._filter.write.bind(this._filter);this._inflate.on("data",function(g){if(!_){return}if(g.length>_){g=g.slice(0,_)}_-=g.length;m(g)});this._inflate.on("end",this._filter.end.bind(this._filter))}}this._inflate.write(h)};l.prototype._handleMetaData=function(h){this._metaData=h;this._bitmapInfo=Object.create(h);this._filter=new i(this._bitmapInfo)};l.prototype._handleTransColor=function(h){this._bitmapInfo.transColor=h};l.prototype._handlePalette=function(h){this._bitmapInfo.palette=h};l.prototype._simpleTransparency=function(){this._metaData.alpha=true};l.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};l.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}};l.prototype._complete=function(h){if(this.errord){return}let u;try{let d=s.dataToBitMap(h,this._bitmapInfo);u=c(d,this._bitmapInfo,this._options.skipRescale);d=null}catch(d){this._handleError(d);return}this.emit("parsed",u)}}});var require_bitpacker=__commonJS({"../../node_modules/pngjs/lib/bitpacker.js"(e,t){"use strict";var r=require_constants();t.exports=function(o,a,i,n){let s=[r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let g=(function(){let v=new ArrayBuffer(2);new DataView(v).setInt16(0,256,true);return new Int16Array(v)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&g){return o}}let c=n.bitDepth!==16?o:new Uint16Array(o.buffer);let l=255;let h=r.COLORTYPE_TO_BPP_MAP[n.inputColorType];if(h===4&&!n.inputHasAlpha){h=3}let u=r.COLORTYPE_TO_BPP_MAP[n.colorType];if(n.bitDepth===16){l=65535;u*=2}let d=Buffer.alloc(a*i*u);let f=0;let _=0;let p=n.bgColor||{};if(p.red===void 0){p.red=l}if(p.green===void 0){p.green=l}if(p.blue===void 0){p.blue=l}function m(){let g;let v;let y;let w=l;switch(n.inputColorType){case r.COLORTYPE_COLOR_ALPHA:w=c[f+3];g=c[f];v=c[f+1];y=c[f+2];break;case r.COLORTYPE_COLOR:g=c[f];v=c[f+1];y=c[f+2];break;case r.COLORTYPE_ALPHA:w=c[f+1];g=c[f];v=g;y=g;break;case r.COLORTYPE_GRAYSCALE:g=c[f];v=g;y=g;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}if(n.inputHasAlpha){if(!s){w/=l;g=Math.min(Math.max(Math.round((1-w)*p.red+w*g),0),l);v=Math.min(Math.max(Math.round((1-w)*p.green+w*v),0),l);y=Math.min(Math.max(Math.round((1-w)*p.blue+w*y),0),l)}}return{red:g,green:v,blue:y,alpha:w}}for(let g=0;g<i;g++){for(let v=0;v<a;v++){let y=m(c,f);switch(n.colorType){case r.COLORTYPE_COLOR_ALPHA:case r.COLORTYPE_COLOR:if(n.bitDepth===8){d[_]=y.red;d[_+1]=y.green;d[_+2]=y.blue;if(s){d[_+3]=y.alpha}}else{d.writeUInt16BE(y.red,_);d.writeUInt16BE(y.green,_+2);d.writeUInt16BE(y.blue,_+4);if(s){d.writeUInt16BE(y.alpha,_+6)}}break;case r.COLORTYPE_ALPHA:case r.COLORTYPE_GRAYSCALE:{let w=(y.red+y.green+y.blue)/3;if(n.bitDepth===8){d[_]=w;if(s){d[_+1]=y.alpha}}else{d.writeUInt16BE(w,_);if(s){d.writeUInt16BE(y.alpha,_+2)}}break}default:throw new Error("unrecognised color Type "+n.colorType)}f+=h;_+=u}}return d}}});var require_filter_pack=__commonJS({"../../node_modules/pngjs/lib/filter-pack.js"(e,t){"use strict";var r=require_paeth_predictor();function o(p,m,g,v,y){for(let w=0;w<g;w++){v[y+w]=p[m+w]}}function a(p,m,g){let v=0;let y=m+g;for(let w=m;w<y;w++){v+=Math.abs(p[w])}return v}function i(p,m,g,v,y,w){for(let b=0;b<g;b++){let E=b>=w?p[m+b-w]:0;let k=p[m+b]-E;v[y+b]=k}}function n(p,m,g,v){let y=0;for(let w=0;w<g;w++){let b=w>=v?p[m+w-v]:0;let E=p[m+w]-b;y+=Math.abs(E)}return y}function s(p,m,g,v,y){for(let w=0;w<g;w++){let b=m>0?p[m+w-g]:0;let E=p[m+w]-b;v[y+w]=E}}function c(p,m,g){let v=0;let y=m+g;for(let w=m;w<y;w++){let b=m>0?p[w-g]:0;let E=p[w]-b;v+=Math.abs(E)}return v}function l(p,m,g,v,y,w){for(let b=0;b<g;b++){let E=b>=w?p[m+b-w]:0;let k=m>0?p[m+b-g]:0;let O=p[m+b]-(E+k>>1);v[y+b]=O}}function h(p,m,g,v){let y=0;for(let w=0;w<g;w++){let b=w>=v?p[m+w-v]:0;let E=m>0?p[m+w-g]:0;let k=p[m+w]-(b+E>>1);y+=Math.abs(k)}return y}function u(p,m,g,v,y,w){for(let b=0;b<g;b++){let E=b>=w?p[m+b-w]:0;let k=m>0?p[m+b-g]:0;let O=m>0&&b>=w?p[m+b-(g+w)]:0;let T=p[m+b]-r(E,k,O);v[y+b]=T}}function d(p,m,g,v){let y=0;for(let w=0;w<g;w++){let b=w>=v?p[m+w-v]:0;let E=m>0?p[m+w-g]:0;let k=m>0&&w>=v?p[m+w-(g+v)]:0;let O=p[m+w]-r(b,E,k);y+=Math.abs(O)}return y}var f={0:o,1:i,2:s,3:l,4:u};var _={0:a,1:n,2:c,3:h,4:d};t.exports=function(p,m,g,v,y){let w;if(!("filterType"in v)||v.filterType===-1){w=[0,1,2,3,4]}else if(typeof v.filterType==="number"){w=[v.filterType]}else{throw new Error("unrecognised filter types")}if(v.bitDepth===16){y*=2}let b=m*y;let E=0;let k=0;let O=Buffer.alloc((b+1)*g);let T=w[0];for(let C=0;C<g;C++){if(w.length>1){let A=Infinity;for(let S=0;S<w.length;S++){let I=_[w[S]](p,k,b,y);if(I<A){T=w[S];A=I}}}O[E]=T;E++;f[T](p,k,b,O,E,y);E+=b;k+=b}return O}}});var require_packer=__commonJS({"../../node_modules/pngjs/lib/packer.js"(e,t){"use strict";var r=require_constants();var o=require_crc();var a=require_bitpacker();var i=require_filter_pack();var n=require("zlib");var s=t.exports=function(c){this._options=c;c.deflateChunkSize=c.deflateChunkSize||32*1024;c.deflateLevel=c.deflateLevel!=null?c.deflateLevel:9;c.deflateStrategy=c.deflateStrategy!=null?c.deflateStrategy:3;c.inputHasAlpha=c.inputHasAlpha!=null?c.inputHasAlpha:true;c.deflateFactory=c.deflateFactory||n.createDeflate;c.bitDepth=c.bitDepth||8;c.colorType=typeof c.colorType==="number"?c.colorType:r.COLORTYPE_COLOR_ALPHA;c.inputColorType=typeof c.inputColorType==="number"?c.inputColorType:r.COLORTYPE_COLOR_ALPHA;if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(c.colorType)===-1){throw new Error("option color type:"+c.colorType+" is not supported at present")}if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(c.inputColorType)===-1){throw new Error("option input color type:"+c.inputColorType+" is not supported at present")}if(c.bitDepth!==8&&c.bitDepth!==16){throw new Error("option bit depth:"+c.bitDepth+" is not supported at present")}};s.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};s.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};s.prototype.filterData=function(c,l,h){let u=a(c,l,h,this._options);let d=r.COLORTYPE_TO_BPP_MAP[this._options.colorType];let f=i(u,l,h,this._options,d);return f};s.prototype._packChunk=function(c,l){let h=l?l.length:0;let u=Buffer.alloc(h+12);u.writeUInt32BE(h,0);u.writeUInt32BE(c,4);if(l){l.copy(u,8)}u.writeInt32BE(o.crc32(u.slice(4,u.length-4)),u.length-4);return u};s.prototype.packGAMA=function(c){let l=Buffer.alloc(4);l.writeUInt32BE(Math.floor(c*r.GAMMA_DIVISION),0);return this._packChunk(r.TYPE_gAMA,l)};s.prototype.packIHDR=function(c,l){let h=Buffer.alloc(13);h.writeUInt32BE(c,0);h.writeUInt32BE(l,4);h[8]=this._options.bitDepth;h[9]=this._options.colorType;h[10]=0;h[11]=0;h[12]=0;return this._packChunk(r.TYPE_IHDR,h)};s.prototype.packIDAT=function(c){return this._packChunk(r.TYPE_IDAT,c)};s.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}}});var require_packer_async=__commonJS({"../../node_modules/pngjs/lib/packer-async.js"(e,t){"use strict";var r=require("util");var o=require("stream");var a=require_constants();var i=require_packer();var n=t.exports=function(s){o.call(this);let c=s||{};this._packer=new i(c);this._deflate=this._packer.createDeflate();this.readable=true};r.inherits(n,o);n.prototype.pack=function(s,c,l,h){this.emit("data",Buffer.from(a.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,l));if(h){this.emit("data",this._packer.packGAMA(h))}let u=this._packer.filterData(s,c,l);this._deflate.on("error",this.emit.bind(this,"error"));this._deflate.on("data",function(d){this.emit("data",this._packer.packIDAT(d))}.bind(this));this._deflate.on("end",function(){this.emit("data",this._packer.packIEND());this.emit("end")}.bind(this));this._deflate.end(u)}}});var require_sync_inflate=__commonJS({"../../node_modules/pngjs/lib/sync-inflate.js"(e,t){"use strict";var r=require("assert").ok;var o=require("zlib");var a=require("util");var i=require("buffer").kMaxLength;function n(u){if(!(this instanceof n)){return new n(u)}if(u&&u.chunkSize<o.Z_MIN_CHUNK){u.chunkSize=o.Z_MIN_CHUNK}o.Inflate.call(this,u);this._offset=this._offset===void 0?this._outOffset:this._offset;this._buffer=this._buffer||this._outBuffer;if(u&&u.maxLength!=null){this._maxLength=u.maxLength}}function s(u){return new n(u)}function c(u,d){if(d){process.nextTick(d)}if(!u._handle){return}u._handle.close();u._handle=null}n.prototype._processChunk=function(u,d,f){if(typeof f==="function"){return o.Inflate._processChunk.call(this,u,d,f)}let _=this;let p=u&&u.length;let m=this._chunkSize-this._offset;let g=this._maxLength;let v=0;let y=[];let w=0;let b;this.on("error",function(T){b=T});function E(T,C){if(_._hadError){return}let A=m-C;r(A>=0,"have should not go down");if(A>0){let S=_._buffer.slice(_._offset,_._offset+A);_._offset+=A;if(S.length>g){S=S.slice(0,g)}y.push(S);w+=S.length;g-=S.length;if(g===0){return false}}if(C===0||_._offset>=_._chunkSize){m=_._chunkSize;_._offset=0;_._buffer=Buffer.allocUnsafe(_._chunkSize)}if(C===0){v+=p-T;p=T;return true}return false}r(this._handle,"zlib binding closed");let k;do{k=this._handle.writeSync(d,u,v,p,this._buffer,this._offset,m);k=k||this._writeState}while(!this._hadError&&E(k[0],k[1]));if(this._hadError){throw b}if(w>=i){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+i.toString(16)+" bytes")}let O=Buffer.concat(y,w);c(this);return O};a.inherits(n,o.Inflate);function l(u,d){if(typeof d==="string"){d=Buffer.from(d)}if(!(d instanceof Buffer)){throw new TypeError("Not a string or buffer")}let f=u._finishFlushFlag;if(f==null){f=o.Z_FINISH}return u._processChunk(d,f)}function h(u,d){return l(new n(d),u)}t.exports=e=h;e.Inflate=n;e.createInflate=s;e.inflateSync=h}});var require_sync_reader=__commonJS({"../../node_modules/pngjs/lib/sync-reader.js"(e,t){"use strict";var r=t.exports=function(o){this._buffer=o;this._reads=[]};r.prototype.read=function(o,a){this._reads.push({length:Math.abs(o),allowLess:o<0,func:a})};r.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let o=this._reads[0];if(this._buffer.length&&(this._buffer.length>=o.length||o.allowLess)){this._reads.shift();let a=this._buffer;this._buffer=a.slice(o.length);o.func.call(this,a.slice(0,o.length))}else{break}}if(this._reads.length>0){throw new Error("There are some read requests waitng on finished stream")}if(this._buffer.length>0){throw new Error("unrecognised content at end of stream")}}}});var require_filter_parse_sync=__commonJS({"../../node_modules/pngjs/lib/filter-parse-sync.js"(e){"use strict";var t=require_sync_reader();var r=require_filter_parse();e.process=function(o,a){let i=[];let n=new t(o);let s=new r(a,{read:n.read.bind(n),write:function(c){i.push(c)},complete:function(){}});s.start();n.process();return Buffer.concat(i)}}});var require_parser_sync=__commonJS({"../../node_modules/pngjs/lib/parser-sync.js"(e,t){"use strict";var r=true;var o=require("zlib");var a=require_sync_inflate();if(!o.deflateSync){r=false}var i=require_sync_reader();var n=require_filter_parse_sync();var s=require_parser();var c=require_bitmapper();var l=require_format_normaliser();t.exports=function(h,u){if(!r){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let d;function f(M){d=M}let _;function p(M){_=M}function m(M){_.transColor=M}function g(M){_.palette=M}function v(){_.alpha=true}let y;function w(M){y=M}let b=[];function E(M){b.push(M)}let k=new i(h);let O=new s(u,{read:k.read.bind(k),error:f,metadata:p,gamma:w,palette:g,transColor:m,inflateData:E,simpleTransparency:v});O.start();k.process();if(d){throw d}let T=Buffer.concat(b);b.length=0;let C;if(_.interlace){C=o.inflateSync(T)}else{let M=(_.width*_.bpp*_.depth+7>>3)+1;let R=M*_.height;C=a(T,{chunkSize:R,maxLength:R})}T=null;if(!C||!C.length){throw new Error("bad png - invalid inflate data response")}let A=n.process(C,_);T=null;let S=c.dataToBitMap(A,_);A=null;let I=l(S,_,u.skipRescale);_.data=I;_.gamma=y||0;return _}}});var require_packer_sync=__commonJS({"../../node_modules/pngjs/lib/packer-sync.js"(e,t){"use strict";var r=true;var o=require("zlib");if(!o.deflateSync){r=false}var a=require_constants();var i=require_packer();t.exports=function(n,s){if(!r){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let c=s||{};let l=new i(c);let h=[];h.push(Buffer.from(a.PNG_SIGNATURE));h.push(l.packIHDR(n.width,n.height));if(n.gamma){h.push(l.packGAMA(n.gamma))}let u=l.filterData(n.data,n.width,n.height);let d=o.deflateSync(u,l.getDeflateOptions());u=null;if(!d||!d.length){throw new Error("bad png - invalid compressed data response")}h.push(l.packIDAT(d));h.push(l.packIEND());return Buffer.concat(h)}}});var require_png_sync=__commonJS({"../../node_modules/pngjs/lib/png-sync.js"(e){"use strict";var t=require_parser_sync();var r=require_packer_sync();e.read=function(o,a){return t(o,a||{})};e.write=function(o,a){return r(o,a)}}});var require_png=__commonJS({"../../node_modules/pngjs/lib/png.js"(e){"use strict";var t=require("util");var r=require("stream");var o=require_parser_async();var a=require_packer_async();var i=require_png_sync();var n=e.PNG=function(s){r.call(this);s=s||{};this.width=s.width|0;this.height=s.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(s.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new o(s);this._parser.on("error",this.emit.bind(this,"error"));this._parser.on("close",this._handleClose.bind(this));this._parser.on("metadata",this._metadata.bind(this));this._parser.on("gamma",this._gamma.bind(this));this._parser.on("parsed",function(c){this.data=c;this.emit("parsed",c)}.bind(this));this._packer=new a(s);this._packer.on("data",this.emit.bind(this,"data"));this._packer.on("end",this.emit.bind(this,"end"));this._parser.on("close",this._handleClose.bind(this));this._packer.on("error",this.emit.bind(this,"error"))};t.inherits(n,r);n.sync=i;n.prototype.pack=function(){if(!this.data||!this.data.length){this.emit("error","No data provided");return this}process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this));return this};n.prototype.parse=function(s,c){if(c){let l,h;l=function(u){this.removeListener("error",h);this.data=u;c(null,this)}.bind(this);h=function(u){this.removeListener("parsed",l);c(u,null)}.bind(this);this.once("parsed",l);this.once("error",h)}this.end(s);return this};n.prototype.write=function(s){this._parser.write(s);return true};n.prototype.end=function(s){this._parser.end(s)};n.prototype._metadata=function(s){this.width=s.width;this.height=s.height;this.emit("metadata",s)};n.prototype._gamma=function(s){this.gamma=s};n.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};n.bitblt=function(s,c,l,h,u,d,f,_){l|=0;h|=0;u|=0;d|=0;f|=0;_|=0;if(l>s.width||h>s.height||l+u>s.width||h+d>s.height){throw new Error("bitblt reading outside image")}if(f>c.width||_>c.height||f+u>c.width||_+d>c.height){throw new Error("bitblt writing outside image")}for(let p=0;p<d;p++){s.data.copy(c.data,(_+p)*c.width+f<<2,(h+p)*s.width+l<<2,(h+p)*s.width+l+u<<2)}};n.prototype.bitblt=function(s,c,l,h,u,d,f){n.bitblt(this,s,c,l,h,u,d,f);return this};n.adjustGamma=function(s){if(s.gamma){for(let c=0;c<s.height;c++){for(let l=0;l<s.width;l++){let h=s.width*c+l<<2;for(let u=0;u<3;u++){let d=s.data[h+u]/255;d=Math.pow(d,1/2.2/s.gamma);s.data[h+u]=Math.round(d*255)}}}s.gamma=0}};n.prototype.adjustGamma=function(){n.adjustGamma(this)}}});var nativeProfiler_exports={};__export(nativeProfiler_exports,{ProfileService:()=>ProfileService,createNativeProfilerHost:()=>createNativeProfilerHost,getProfileInput:()=>getProfileInput,profileInput:()=>profileInput,simPid:()=>simPid,stopNativeProfiles:()=>stopNativeProfiles});module.exports=__toCommonJS(nativeProfiler_exports);var import_node_fs25=require("fs");var import_node_path24=__toESM(require("path"));var import_node_os14=__toESM(require("os"));var import_node_crypto13=require("crypto");var import_node_child_process2=require("child_process");var import_node_util=require("util");var import_node_fs=require("fs");var import_node_path=__toESM(require("path"));var import_saxes=require("saxes");var MAX_XML=32*1024*1024;function document(e){if(Buffer.byteLength(e)>MAX_XML)throw new Error("Trace XML is too large. Use a shorter run.");const t={tag:"root",attrs:{},text:"",children:[]};const r=[t];const o=new Map;let a=0;const i=new import_saxes.SaxesParser;i.on("doctype",()=>{throw new Error("Trace XML must not use a DTD.")});i.on("opentag",h=>{if(++a>5e5||r.length>64)throw new Error("Trace XML is too deep or too large.");const u={tag:h.name,attrs:h.attributes,text:"",children:[]};r[r.length-1].children.push(u);r.push(u);if(u.attrs.id){if(o.has(u.attrs.id))throw new Error("Trace XML has a repeated ID.");o.set(u.attrs.id,u)}});i.on("text",h=>{r[r.length-1].text+=h});i.on("closetag",()=>{r.pop()});i.write(e).close();function n(h){const u=new Set;while(h.attrs.ref){if(u.has(h))throw new Error("Trace XML has a ref loop.");u.add(h);const d=o.get(h.attrs.ref);if(!d)throw new Error("Trace XML has a missing ref.");h=d}return h}function s(h,u,d=0){if(d>64)throw new Error("Trace XML has a ref loop.");h=n(h);return[...h.tag===u?[h]:[],...h.children.flatMap(f=>s(f,u,d+1))]}const c=h=>{if(!h)throw new Error("Trace XML lacks a number.");const u=Number(n(h).text);if(!Number.isFinite(u)||!n(h).text.trim())throw new Error("Trace XML has a bad number.");return u};const l=s(t,"node");return{nodes:l,resolve:n,descendants:s,num:c}}function parseCpuSamples(e,t){const{nodes:r,resolve:o,descendants:a,num:i}=document(e);const n=[];for(const s of r){const c=s.children.find(h=>h.tag==="schema");if(c?.attrs.name!=="time-profile")continue;const l=c.children.map(h=>h.children.find(u=>u.tag==="mnemonic")?.text);for(const h of s.children.filter(u=>u.tag==="row")){const u=v=>h.children[l.indexOf(v)];const d=u("thread");const f=u("process");if(!d||!f||i(a(f,"pid")[0])!==t)continue;const _=i(a(d,"tid")[0]);const p=u("stack")?a(u("stack"),"frame").map(v=>({symbol:(v.attrs.name||v.attrs.addr||"Unknown").slice(0,180),image:(a(v,"binary")[0]?.attrs.name||"Unknown").slice(0,100)})):[];const m=i(u("time"))/1e6;const g=i(u("weight"))/1e6;if(m<0||g<=0||g>1e3)throw new Error("Trace sample timing is invalid.");n.push({timeMs:m,weightMs:g,tid:_,main:/Main Thread/i.test(o(d).attrs.fmt||""),running:o(u("thread-state")).text==="Running",frames:p})}}return n.sort((s,c)=>s.timeMs-c.timeMs)}function parseOsHangs(e,t,r){const{nodes:o,descendants:a,num:i}=document(e);const n=[];for(const s of o){const c=s.children.find(h=>h.tag==="schema");if(c?.attrs.name!=="potential-hangs")continue;const l=c.children.map(h=>h.children.find(u=>u.tag==="mnemonic")?.text);for(const h of s.children.filter(u=>u.tag==="row")){const u=f=>h.children[l.indexOf(f)];if(!u("process")||i(a(u("process"),"pid")[0])!==t)continue;const d=i(u("duration"))/1e6;if(d>=r)n.push({startMs:i(u("start"))/1e6,durationMs:d,method:"os-hang",topSymbols:[],sampleCount:0})}}return n}var import_node_child_process=require("child_process");function memorySummary(e,t){const r=e.filter(o=>Number.isFinite(o)&&o>0);if(!r.length)return null;return{source:t,samples:r.length,startBytes:r[0],peakBytes:Math.max(...r),endBytes:r[r.length-1],growthBytes:r[r.length-1]-r[0]}}function sampleRss(e){const t=[];let r;let o=false;let a;const i=new Promise(c=>{a=c});const n=()=>{if(r||o)return;r=new Promise(c=>{(0,import_node_child_process.execFile)("ps",["-o","rss=","-p",String(e)],{timeout:1e3,maxBuffer:1024},(l,h)=>{const u=Number(h.trim());if(!l&&Number.isFinite(u)&&u>0)t.push(u*1024);c()})}).finally(()=>{r=void 0})};n();const s=setInterval(n,250);return{result:i,stop(){if(o)return;o=true;clearInterval(s);void Promise.resolve(r).then(()=>a(memorySummary(t,"host-ps-rss")))}}}function attachHelp(e){const t=e.udid;const r=e.appId;return new Error(`xctrace did not attach. Both tries hit the 45 second cap. This is an Xcode/CoreSimulator attach issue. First, close and open this app. Then try the trace again:
|
|
2
|
+
xcrun simctl terminate ${t} ${r}
|
|
3
|
+
xcrun simctl launch ${t} ${r}
|
|
4
|
+
If it still fails, reboot just this sim. Then open the app and try again:
|
|
5
|
+
xcrun simctl shutdown ${t}
|
|
6
|
+
xcrun simctl boot ${t}
|
|
7
|
+
xcrun simctl bootstatus ${t} -b
|
|
8
|
+
xcrun simctl launch ${t} ${r}`)}var AttachTimeout=class extends Error{constructor(){super(...arguments);this.name="AttachTimeout"}};function retryAttach(e,t,r){let o=e();let a=0;let i=false;let n;let s;const c=new Promise((h,u)=>{n=h;s=u});void c.catch(()=>{});const l=(async()=>{while(true){try{await o.ready}catch(h){await o.result.catch(()=>{});if(!i&&a===0&&h?.name==="AttachTimeout"){await t();if(i)throw h;a++;o=e();continue}if(!i&&a===1&&h?.name==="AttachTimeout"&&r)throw r();throw h}n();return await o.result}})().catch(h=>{s(h);throw h});void l.catch(()=>{});return{get pid(){return o.pid},get attachRetries(){return a},ready:c,result:l,stop(){i=true;o.stop()},cancel(){i=true;o.cancel()}}}var exec=(0,import_node_util.promisify)(import_node_child_process2.execFile);async function simPid(e,t){if(process.platform!=="darwin")throw new Error("Native Profiler needs macOS with Xcode.");if(!/^[A-Fa-f0-9-]{36}$/.test(e)||!/^[A-Za-z0-9_.-]+$/.test(t))throw new Error("Bad app or sim ID.");const{stdout:r}=await exec("xcrun",["simctl","spawn",e,"launchctl","list"],{timeout:1e4});const o=r.split("\n").filter(a=>a.includes(`UIKitApplication:${t}[`));if(o.length!==1||!/^\d+\s/.test(o[0]))throw new Error("Open the app on the chosen sim first.");return Number(o[0].split(/\s/)[0])}async function size(e){let t=0;for(const r of await import_node_fs.promises.readdir(e,{withFileTypes:true})){const o=import_node_path.default.join(e,r.name);if(r.isDirectory())t+=await size(o);else if(r.isFile())t+=(await import_node_fs.promises.stat(o)).size}return t}var captureIosOnce=(e,t,r,o,a)=>{const i=import_node_path.default.join(t,"capture.trace");const n=new AbortController;const s=(0,import_node_child_process2.spawn)("xcrun",["xctrace","record","--device",e.udid,"--attach",String(e.pid),"--instrument","Time Profiler","--time-limit",`${r}ms`,"--no-prompt","--output",i],{stdio:["ignore","pipe","pipe"]});let c;let l;let h;let u;const d=new Promise((A,S)=>{h=A;u=S});void d.catch(()=>{});let f="";let _=false;let p=false;let m;let g;const v=()=>{if(p)return;c?.stop();s.kill("SIGINT");if(!g)g=setTimeout(()=>{m??=new Error("Xcode did not save the trace within 45 seconds of stop.");s.kill("SIGKILL")},45e3)};const y=()=>{n.abort();if(p)return;m??=new Error("Trace was stopped before it could finish.");s.kill("SIGKILL")};const w=setTimeout(()=>{m??=new AttachTimeout("Xcode did not start the trace within 45 seconds.");v()},45e3);const b=setTimeout(()=>{m??=new Error("Xcode took too long to finish the trace.");v()},r+6e4);let E=false;const k=setInterval(()=>{if(E)return;E=true;void size(t).then(A=>{if(A>256*1024*1024){m??=new Error("Trace reached the 256 MiB cap.");v()}},()=>{}).finally(()=>{E=false})},2e3);const O=A=>{f=(f+A.toString()).slice(-16e3);if(!_&&!m&&f.includes("Ctrl-C to stop the recording")){_=true;clearTimeout(w);c=sampleRss(e.pid);l=setTimeout(()=>c?.stop(),r);h()}};s.stdout.on("data",O);s.stderr.on("data",O);const T=new Promise((A,S)=>{const I=M=>{m=M};s.once("error",I);s.once("close",M=>{p=true;c?.stop();clearTimeout(l);clearTimeout(w);clearTimeout(b);clearTimeout(g);clearInterval(k);if(m||!_||M!==0&&!f.includes("Output file saved")){const R=m?Object.assign(new Error(`${m.message} ${f.slice(-1e3)}`),{name:m.name}):new Error(`Xcode could not save the trace. ${f.slice(-1e3)}`);u(R);S(R)}else A()})});const C=T.then(async()=>{const A=async L=>{const{stdout:B}=await exec("xcrun",["xctrace","export","--input",i,"--xpath",`/trace-toc/run[@number="1"]/data/table[@schema="${L}"]`],{signal:n.signal,timeout:45e3,maxBuffer:32*1024*1024});return B};const{stdout:S}=await exec("xcrun",["xctrace","export","--input",i,"--toc"],{signal:n.signal,timeout:3e4,maxBuffer:1024*1024});const I=Number(/<duration>([\d.]+)<\/duration>/.exec(S)?.[1])*1e3;if(!Number.isFinite(I)||I<=0)throw new Error("Xcode did not return a valid trace span.");if(!S.includes('schema="time-profile"'))throw new Error("This Xcode trace has no CPU sample table.");const M=await A("time-profile");const R=parseCpuSamples(M,e.pid);const P=["Busy spans from samples are estimates. They do not find sleeping or blocked hangs.","Frame data is not captured on iOS."];let D=[];if(!S.includes('schema="potential-hangs"'))P.push("No OS hang rows were captured. Busy spans use CPU samples.");if(S.includes('schema="potential-hangs"')){try{D=parseOsHangs(await A("potential-hangs"),e.pid,o)}catch{P.push("OS hang rows could not be read. Used CPU samples.")}}if(f.includes("[Warning]"))P.push("Xcode warned of a trace source gap. CPU rows were checked on their own.");const N=await c?.result??null;if(!N)P.push("Host RSS could not be read. Memory use is unknown.");return{samples:R,hangs:D,durationMs:I,warnings:P,memory:N}});void C.catch(()=>{});try{a?.(s.pid)}catch(A){m=A;y()}return{pid:s.pid,ready:d,result:C,stop:v,cancel:y}};var captureIos=(e,t,r,o,a)=>retryAttach(()=>captureIosOnce(e,t,r,o,a),()=>import_node_fs.promises.rm(import_node_path.default.join(t,"capture.trace"),{recursive:true,force:true}),()=>attachHelp(e));var import_node_fs24=require("fs");var import_node_path23=__toESM(require("path"));var import_node_child_process13=require("child_process");var import_node_util6=require("util");var import_node_child_process11=require("child_process");var import_node_util4=require("util");var import_node_crypto=require("crypto");var import_node_fs10=require("fs");var import_node_path10=__toESM(require("path"));var import_node_async_hooks=require("async_hooks");var import_node_crypto7=require("crypto");var import_node_fs2=require("fs");var import_node_path2=__toESM(require("path"));var import_node_crypto2=require("crypto");var import_node_child_process3=require("child_process");var DISABLED_STORE_ROOT=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp";var import_node_fs3=require("fs");var import_node_path3=__toESM(require("path"));var import_node_crypto3=require("crypto");var KEEP_MS=2*60*6e4;var import_node_child_process4=require("child_process");var import_node_crypto6=require("crypto");var import_node_fs8=require("fs");var import_node_net=__toESM(require("net"));var import_node_path8=__toESM(require("path"));var import_node_crypto4=require("crypto");var import_node_fs4=require("fs");var import_node_os=__toESM(require("os"));var import_node_path4=__toESM(require("path"));var import_node_stream=require("stream");var import_promises=require("stream/promises");var DEFAULT_IMAGE={api:36,tag:"aosp_atd",abi:hostAbi()};function hostAbi(){return import_node_os.default.arch()==="arm64"?"arm64-v8a":"x86_64"}var import_node_fs5=require("fs");var import_node_path5=__toESM(require("path"));var import_node_fs7=require("fs");var import_node_os3=__toESM(require("os"));var import_node_path7=__toESM(require("path"));var import_node_fs6=require("fs");var import_node_os2=__toESM(require("os"));var import_node_path6=__toESM(require("path"));var import_node_crypto5=require("crypto");function farmHome(){return process.env.BUOY_FARM_HOME||import_node_path6.default.join(import_node_os2.default.homedir(),".buoy","farm")}var paths=(e=farmHome())=>({home:e,lock:import_node_path6.default.join(e,"owner.lock"),lockOwner:import_node_path6.default.join(e,"owner.lock","owner.json"),socket:import_node_path6.default.join(e,"farmd.sock"),token:import_node_path6.default.join(e,"token"),state:import_node_path6.default.join(e,"state.json"),journal:import_node_path6.default.join(e,"journal.ndjson"),log:import_node_path6.default.join(e,"farmd.log"),shots:import_node_path6.default.join(e,"shots")});var ANDROID_ADB_PORT=Number(process.env.BUOY_FARM_ADB_PORT)||5137;function androidHome(e=farmHome()){return import_node_path7.default.join(e,"android")}function farmAdbTarget(e,t){return farmAdbTargets(t).get(e)??null}function farmAdbTargets(e){const t=new Map;const r=n=>{try{return JSON.parse((0,import_node_fs7.readFileSync)(n,"utf8"))}catch{return null}};const o=(n,s)=>{for(const c of Object.values(s??{})){const l=n?.[c.templateId];if(!l?.sdkRoot||!alive(c.pid)||t.has(c.serial))continue;t.set(c.serial,{adb:import_node_path7.default.join(l.sdkRoot,"platform-tools","adb"),port:ANDROID_ADB_PORT})}};const a=r(paths(e??farmHome()).state);o(a?.androidTemplates,a?.androidCopies);const i=r(import_node_path7.default.join(androidHome(e),"state.json"));if(!a?.androidImported)o(i?.templates,i?.copies);return t}function alive(e){try{process.kill(e,0);return true}catch(t){return t.code==="EPERM"}}var BROKER_PORT=Number(process.env.BUOY_BROKER_PORT)||42831;var import_node_child_process5=require("child_process");var import_node_fs9=require("fs");var import_node_os4=__toESM(require("os"));var import_node_path9=__toESM(require("path"));var import_node_util2=require("util");var execFileAsync=(0,import_node_util2.promisify)(import_node_child_process5.execFile);var GB=1024**3;var TRIM_EVERY_MS=10*6e4;var STALE_TEMPLATE_MS=7*24*36e5;var PHONE_RETRY_MS=10*6e4;var import_node_fs11=require("fs");var import_node_os5=__toESM(require("os"));var import_node_path11=__toESM(require("path"));var import_node_net2=__toESM(require("net"));var import_node_fs12=require("fs");var import_node_crypto8=require("crypto");var import_node_net3=__toESM(require("net"));var import_node_fs13=require("fs");var import_node_child_process6=require("child_process");var import_node_crypto9=require("crypto");var import_node_path12=__toESM(require("path"));var import_node_os6=__toESM(require("os"));var import_node_fs14=require("fs");var import_node_path13=__toESM(require("path"));var import_node_path21=__toESM(require("path"));var import_node_fs22=require("fs");var import_node_os13=__toESM(require("os"));var import_node_child_process7=require("child_process");var import_node_crypto10=require("crypto");var import_node_fs15=require("fs");var import_node_os7=__toESM(require("os"));var import_node_path14=__toESM(require("path"));var import_node_util3=require("util");var execFileAsync2=(0,import_node_util3.promisify)(import_node_child_process7.execFile);var MB=1024*1024;var import_promises2=require("fs/promises");var import_node_os8=__toESM(require("os"));var import_node_path15=__toESM(require("path"));var PERSON_ID=`p-${import_node_os8.default.userInfo().username}`;var import_node_child_process10=require("child_process");var import_node_fs21=require("fs");var import_node_os12=__toESM(require("os"));var import_node_path20=__toESM(require("path"));var import_node_fs16=require("fs");var import_node_os9=__toESM(require("os"));var import_node_path16=__toESM(require("path"));var import_node_stream2=require("stream");var import_promises3=require("stream/promises");var import_node_child_process8=require("child_process");var import_node_fs18=require("fs");var import_node_os10=__toESM(require("os"));var import_node_path18=__toESM(require("path"));var import_node_fs19=require("fs");var import_node_crypto11=require("crypto");var import_node_fs17=require("fs");var import_node_net4=__toESM(require("net"));var import_node_path17=__toESM(require("path"));var SOURCE=String.raw`#include <mach/mach.h>
|
|
9
|
+
#include <mach/thread_policy.h>
|
|
10
|
+
#include <pthread.h>
|
|
11
|
+
#include <stdlib.h>
|
|
12
|
+
#include <string.h>
|
|
13
|
+
#include <fcntl.h>
|
|
14
|
+
#include <unistd.h>
|
|
15
|
+
#include <crt_externs.h>
|
|
16
|
+
|
|
17
|
+
static int is_renderer(void) {
|
|
18
|
+
char **argv = *_NSGetArgv();
|
|
19
|
+
for (int i = 0; argv && argv[i]; i++) if (!strcmp(argv[i], "--type=renderer")) return 1;
|
|
20
|
+
return 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
static void set_mains(integer_t importance) {
|
|
24
|
+
thread_act_array_t list;
|
|
25
|
+
mach_msg_type_number_t n;
|
|
26
|
+
if (task_threads(mach_task_self(), &list, &n) != KERN_SUCCESS) return;
|
|
27
|
+
for (mach_msg_type_number_t i = 0; i < n; i++) {
|
|
28
|
+
thread_extended_info_data_t info;
|
|
29
|
+
mach_msg_type_number_t cnt = THREAD_EXTENDED_INFO_COUNT;
|
|
30
|
+
if (thread_info(list[i], THREAD_EXTENDED_INFO, (thread_info_t)&info, &cnt) == KERN_SUCCESS &&
|
|
31
|
+
(!strcmp(info.pth_name, "CrRendererMain") || !strcmp(info.pth_name, "Compositor"))) {
|
|
32
|
+
thread_precedence_policy_data_t p = {.importance = importance};
|
|
33
|
+
thread_policy_set(list[i], THREAD_PRECEDENCE_POLICY, (thread_policy_t)&p, THREAD_PRECEDENCE_POLICY_COUNT);
|
|
34
|
+
}
|
|
35
|
+
mach_port_deallocate(mach_task_self(), list[i]);
|
|
36
|
+
}
|
|
37
|
+
vm_deallocate(mach_task_self(), (vm_address_t)list, n * sizeof(thread_act_t));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static int fd = -1;
|
|
41
|
+
static void *watch(void *arg) {
|
|
42
|
+
(void)arg;
|
|
43
|
+
pthread_setname_np("buoy-boost");
|
|
44
|
+
// Between steps the page sits a little lower, so the instances that are acting win the top cores.
|
|
45
|
+
// Raising alone did nothing measurable; lowering the idle ones did (LEDGER 44, 47).
|
|
46
|
+
set_mains(-10);
|
|
47
|
+
char c;
|
|
48
|
+
while (read(fd, &c, 1) == 1) set_mains(c == '1' ? 63 : -10);
|
|
49
|
+
close(fd);
|
|
50
|
+
return NULL;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
__attribute__((constructor)) static void start(void) {
|
|
54
|
+
const char *fifo = getenv("BUOY_BOOST_FIFO"); // read once here; never call getenv later
|
|
55
|
+
if (!fifo || !is_renderer()) return;
|
|
56
|
+
// Open now, before the renderer's sandbox starts; O_RDWR so read() blocks instead of hitting EOF.
|
|
57
|
+
fd = open(fifo, O_RDWR);
|
|
58
|
+
if (fd < 0) return;
|
|
59
|
+
pthread_t t;
|
|
60
|
+
pthread_attr_t a;
|
|
61
|
+
pthread_attr_init(&a);
|
|
62
|
+
pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
|
|
63
|
+
pthread_create(&t, &a, watch, NULL);
|
|
64
|
+
}
|
|
65
|
+
`;var import_node_http=__toESM(require("http"));var import_node_child_process9=require("child_process");var import_node_fs20=require("fs");var import_node_os11=__toESM(require("os"));var import_node_path19=__toESM(require("path"));var SOURCE2=String.raw`#include <libproc.h>
|
|
66
|
+
#include <mach/mach_time.h>
|
|
67
|
+
#include <stdio.h>
|
|
68
|
+
#include <stdlib.h>
|
|
69
|
+
#include <sys/resource.h>
|
|
70
|
+
int main(int argc, char **argv) {
|
|
71
|
+
mach_timebase_info_data_t tb; mach_timebase_info(&tb);
|
|
72
|
+
double ns = (double)tb.numer / tb.denom;
|
|
73
|
+
printf("{");
|
|
74
|
+
int first = 1;
|
|
75
|
+
for (int i = 1; i < argc; i++) {
|
|
76
|
+
struct rusage_info_v6 r;
|
|
77
|
+
if (proc_pid_rusage(atoi(argv[i]), RUSAGE_INFO_V6, (rusage_info_t *)&r) != 0) continue;
|
|
78
|
+
printf("%s\"%s\":{\"cpuNs\":%.0f,\"topNs\":%.0f,\"instr\":%llu,\"cycles\":%llu,\"topInstr\":%llu,\"topCycles\":%llu,\"footprint\":%llu}",
|
|
79
|
+
first ? "" : ",", argv[i], (r.ri_user_time + r.ri_system_time) * ns, (r.ri_user_ptime + r.ri_system_ptime) * ns,
|
|
80
|
+
r.ri_instructions, r.ri_cycles, r.ri_pinstructions, r.ri_pcycles, r.ri_phys_footprint);
|
|
81
|
+
first = 0;
|
|
82
|
+
}
|
|
83
|
+
printf("}\n");
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
`;var IDLE_EXIT_MS=10*6e4;var farmHelp=e=>`Usage: ${e} <command>
|
|
87
|
+
|
|
88
|
+
status [--outside] Pool, budgets, sims, leases, recent events
|
|
89
|
+
setup [options] Make a template (the sim clones are made from)
|
|
90
|
+
--app <path.app> App build (default: example-dev-build Debug build)
|
|
91
|
+
--no-seed Skip the seed
|
|
92
|
+
--launch-url <url> Open this URL after each app launch. iOS asks
|
|
93
|
+
"Open in \u2026?" for a custom scheme, so a dev-client
|
|
94
|
+
app is better seeded with Preferences/ (it reopens
|
|
95
|
+
its last Metro URL by itself)
|
|
96
|
+
--seed <dir> Seed folder (default: example-dev-build/artifacts/pool-seed)
|
|
97
|
+
--device <type id> Default: iPhone 17 Pro
|
|
98
|
+
--runtime <runtime id> Default: iOS 26.3
|
|
99
|
+
--profile slim|stock Default: slim
|
|
100
|
+
--metro <port> Default: 8802
|
|
101
|
+
--dry-run Show what it would do and what it costs
|
|
102
|
+
grow <n> [--template id] Add n sims
|
|
103
|
+
shrink <n> [--template id] Remove n idle sims
|
|
104
|
+
remove-template <id> Delete a template and all its sims (none may be in use)
|
|
105
|
+
acquire <n> [--template id] [--purpose text] [--launch]
|
|
106
|
+
Take n sims and hold them until Ctrl-C
|
|
107
|
+
(24 hours at most)
|
|
108
|
+
park|wake|reset|rebuild|delete <udid>
|
|
109
|
+
end-lease <leaseId> Force-end a lease (its sims are rebuilt)
|
|
110
|
+
settings [key=value ...] Show or change settings
|
|
111
|
+
phone list Phones a sim can act like (RAM, CPUs, memory limit)
|
|
112
|
+
phone use <id|off> Launch apps as this phone (default: iphone-se-2nd-gen)
|
|
113
|
+
phone measure [--device <udid>]
|
|
114
|
+
Read the iPhone plugged into this Mac and add it
|
|
115
|
+
doctor Check Xcode, disk, memory, the farm service
|
|
116
|
+
android <command> Slim Android phones from one snapshot
|
|
117
|
+
(see: android help)
|
|
118
|
+
chrome <command> Many slim Chromes for web apps
|
|
119
|
+
(see: chrome help)
|
|
120
|
+
stop [--now] Stop the farm service and park free sims
|
|
121
|
+
--now Stop even if leases are still held
|
|
122
|
+
farmd Run the farm service in this process
|
|
123
|
+
`;var HELP=farmHelp("pnpm farm");var CLI_HOLD_MS=24*36e5;var MIN_SECRET_LENGTH=6;var used=new Map;function knownSecrets(e=process.env){const t=new Map(used);for(const[r,o]of Object.entries(e))if(r.startsWith("BUOY_SECRET_")&&o)t.set(r.slice("BUOY_SECRET_".length),o);return t}var escapeRe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function scrubSecrets(e){const t=new Map;for(const[a,i]of knownSecrets()){if(i.length<MIN_SECRET_LENGTH)continue;for(const n of[i,JSON.stringify(i).slice(1,-1),encodeURIComponent(i)])t.set(n,a);for(let n=i.length-1;n>=MIN_SECRET_LENGTH;n--){t.set(`${i.slice(0,n)}\u2026`,a);t.set(`${i.slice(0,n)}...`,a);if(n>=8)t.set(i.slice(0,n),a)}}if(t.size===0)return e;const r=[...t.keys()].sort((a,i)=>i.length-a.length);const o=new RegExp(r.map(escapeRe).join("|"),"g");return e.replace(o,(a,i,n)=>{if(/^\d+$/.test(a)){const s=n.slice(Math.max(0,i-8),i);const c=n.slice(i+a.length,i+a.length+8);if(/(\d|\d\.)$/.test(s)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return a;if(/[:[,]\s*$/.test(s)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(n,i))return`"{{secret:${t.get(a)}}}"`}return`{{secret:${t.get(a)}}}`})}function insideJsonString(e,t){let r=false;for(let o=0;o<t;o++){if(e[o]==="\\")o++;else if(e[o]==='"')r=!r}return r}var execFileAsync3=(0,import_node_util4.promisify)(import_node_child_process11.execFile);var ADB_MISSING="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH.";function q(e){return`'${e.replace(/'/g,`'\\''`)}'`}function assertPackage(e){if(!/^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/.test(e))throw new Error(`"${e}" is not a valid Android package name.`);return e}function adbFor(e,t){const r=e?farmAdbTarget(e):null;if(r)return{bin:r.adb,args:["-P",String(r.port),"-s",e,...t]};return{bin:"adb",args:e?["-s",e,...t]:t}}async function adb(e,t,r=15e3){try{const o=adbFor(e,t);const{stdout:a}=await execFileAsync3(o.bin,o.args,{timeout:r,maxBuffer:32*1024*1024});return a}catch(o){const a=o;if(a.code==="ENOENT")throw new Error(ADB_MISSING);const i=t[0]==="shell"?`shell ${(t[1]??"").split(" ")[0]}`:t.slice(0,2).join(" ");const n=t[0]==="shell"?a.stderr||(a.killed?"timed out":"no error text"):a.stderr||a.message||"";const s=scrubSecrets(n.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${i} failed: ${s}`)}}function adbShell(e,t,r=15e3){return adb(e,["shell",t],r)}async function adbBytes(e,t,r=15e3){try{const o=adbFor(e,t);const{stdout:a}=await execFileAsync3(o.bin,o.args,{timeout:r,encoding:"buffer",maxBuffer:64*1024*1024});return a}catch(o){const a=o;if(a.code==="ENOENT")throw new Error(ADB_MISSING);throw new Error(`adb ${t.slice(0,2).join(" ")} failed: ${a.message.slice(0,300)}`)}}async function adbSerials(){const e=[...farmAdbTargets().keys()];try{const t=parseAdbDevices(await adb(null,["devices"]));return[...t,...e.filter(r=>!t.includes(r))]}catch(t){if(e.length&&t.message===ADB_MISSING)return e;throw t}}function parseAdbDevices(e){return e.split("\n").slice(1).map(t=>t.trim().split(/\s+/)).filter(t=>t[1]==="device").map(t=>t[0])}async function adbForegroundPackage(e){return parseForegroundPackage(await adbShell(e,"dumpsys activity activities"))}function parseForegroundPackage(e){const t=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return t?t[1]:null}async function adbUserPackages(e){const t=await adbShell(e,"pm list packages -3");return t.split("\n").map(r=>r.trim().replace(/^package:/,"")).filter(r=>/^[A-Za-z][\w.]+$/.test(r))}async function adbInstallId(e,t){assertPackage(t);const r=await adbShell(e,`run-as ${q(t)} cat files/react-buoy/@react_buoy_sync_device_id.json 2>/dev/null`,5e3).catch(()=>"");const o=r.trim().replace(/^"|"$/g,"");if(/^[\w-]{4,64}$/.test(o))return o;const a=await adbBytes(e,["exec-out",`run-as ${q(t)} sh -c 'cat app_webview/Default/"Local Storage"/leveldb/*.log app_webview/Default/"Local Storage"/leveldb/*.ldb 2>/dev/null'`],5e3).catch(()=>null);return a?webViewLevelDbInstallId(a):null}function webViewLevelDbInstallId(e){const t=e.toString("latin1");const r=/@react_buoy_sync_device_id([\s\S])\x01([\w-]{4,64})/g;let o=null;for(let a=r.exec(t);a;a=r.exec(t)){const i=a[1].charCodeAt(0)-1;if(i>=4&&i<=a[2].length)o=a[2].slice(0,i)}return o}var import_node_fs23=require("fs");var import_node_path22=__toESM(require("path"));var import_node_crypto12=require("crypto");var import_node_child_process12=require("child_process");var import_node_util5=require("util");var exec2=(0,import_node_util5.promisify)(import_node_child_process12.execFile);var PROCESSOR_VERSION="v52.0";var builds={"darwin-arm64":["mac-arm64","5d7d89fb2472c2ef40413141d5e8f3603d4a500a645d35aa57cb023b9d635b31"],"darwin-x64":["mac-amd64","0ce16fc3e2add79cd66c6596a04ec61eb3b2b8d5507496c5d325f57cb89dc5e8"],"linux-x64":["linux-amd64","411402424f34f2ac1fafa819493c13827ae5a10e335d9387a483c4b696b7f6e1"],"linux-arm64":["linux-arm64","e52888ab9b7d4f3d2620a6f803402e60a11230536d048d0ece4f33b78dd7c368"]};async function traceProcessor(e,t){const r=builds[`${process.platform}-${process.arch}`];if(!r)throw new Error("Perfetto needs a Mac or Linux host for now.");const[o,a]=r;const i=import_node_path22.default.join(e,PROCESSOR_VERSION,o);const n=import_node_path22.default.join(i,"trace_processor_shell");const s=m=>(0,import_node_crypto12.createHash)("sha256").update(m).digest("hex")===a;const c=await import_node_fs23.promises.stat(n).catch(()=>null);const l=c&&c.size<=40*1024*1024?await import_node_fs23.promises.readFile(n).catch(()=>null):null;if(l&&s(l))return n;const h=await fetch(`https://commondatastorage.googleapis.com/perfetto-luci-artifacts/${PROCESSOR_VERSION}/${o}/trace_processor_shell`,{signal:t?AbortSignal.any([t,AbortSignal.timeout(6e4)]):AbortSignal.timeout(6e4)});if(!h.ok||Number(h.headers.get("content-length"))>40*1024*1024)throw new Error("The pinned Perfetto tool could not be fetched.");if(!h.body)throw new Error("The Perfetto download was empty.");const u=h.body.getReader();const d=[];let f=0;try{while(true){const m=await u.read();if(m.done)break;f+=m.value.length;if(f>40*1024*1024)throw new Error("The Perfetto download is too large.");d.push(Buffer.from(m.value))}}finally{await u.cancel()}const _=Buffer.concat(d);if(!s(_))throw new Error("The Perfetto checksum did not match.");await import_node_fs23.promises.mkdir(i,{recursive:true,mode:448});const p=`${n}.${(0,import_node_crypto12.randomUUID)()}.tmp`;try{await import_node_fs23.promises.writeFile(p,_,{mode:448});await import_node_fs23.promises.rename(p,n)}finally{await import_node_fs23.promises.rm(p,{force:true})}return n}function parseCsv(e){const t=[];let r=[];let o="";let a=false;for(let n=0;n<e.length;n++){const s=e[n];if(s==='"'){if(a&&e[n+1]==='"'){o+='"';n++}else a=!a}else if(!a&&(s===","||s==="\n")){r.push(o);o="";if(s==="\n"){if(r.some(Boolean))t.push(r);r=[]}}else if(s!=="\r"||a)o+=s}if(a)throw new Error("Perfetto returned a broken data row.");if(o||r.length){r.push(o);t.push(r)}const i=t.shift()??[];return t.map(n=>{if(n.length!==i.length)throw new Error("Perfetto returned a short data row.");return Object.fromEntries(i.map((s,c)=>[s,n[c]]))})}async function queryTrace(e,t,r,o){const{stdout:a}=await exec2(e,["-Q",r,t],{signal:o,timeout:45e3,maxBuffer:32*1024*1024});return parseCsv(a)}async function androidRows(e,t,r,o,a){if(!Number.isSafeInteger(r)||r<1||!/^[\w.]+$/.test(o))throw new Error("Bad trace app ID.");const i=m=>queryTrace(e,t,m,a);const n=await i(`SELECT upid FROM process WHERE pid=${r} AND (name='${o}' OR cmdline='${o}')`);if(n.length!==1||!/^\d+$/.test(n[0].upid))throw new Error("The trace does not name one matching app process.");const s=`SELECT ${n[0].upid}`;const c=await i("SELECT start_ts, end_ts FROM trace_bounds");const l=Number(c[0]?.start_ts);const h=(Number(c[0]?.end_ts)-l)/1e6;if(!Number.isFinite(h)||h<=0)throw new Error("Perfetto has no valid trace span.");const u=await i(`SELECT (s.ts-${l})/1e6 AS timeMs, s.dur/1e6 AS durationMs, t.tid, t.name, t.is_main_thread AS main
|
|
124
|
+
FROM sched s JOIN thread t USING(utid) WHERE t.upid IN (${s}) AND s.dur>0 ORDER BY s.ts LIMIT 200001`);if(u.length>2e5)throw new Error("The trace has too many CPU rows. Try a shorter run.");const d=await i(`SELECT (s.ts-${l})/1e6 AS timeMs, t.tid,
|
|
125
|
+
COALESCE(NULLIF(f.deobfuscated_name,''), NULLIF(f.name,''), '[unknown]') AS symbol, m.name AS image
|
|
126
|
+
FROM perf_sample s JOIN thread t USING(utid) JOIN stack_profile_callsite c ON c.id=s.callsite_id
|
|
127
|
+
JOIN stack_profile_frame f ON f.id=c.frame_id LEFT JOIN stack_profile_mapping m ON m.id=f.mapping
|
|
128
|
+
WHERE t.upid IN (${s}) ORDER BY s.ts LIMIT 100001`);if(d.length>1e5)throw new Error("The trace has too many stack rows. Try a shorter run.");const f=new Map;for(const m of d){const g=`${m.symbol}\0${m.image}`;const v=f.get(g)??{symbol:m.symbol.slice(0,180),image:m.image.slice(0,100),samples:0,selfMs:0};v.samples++;v.selfMs+=10;f.set(g,v)}const _=await i(`WITH tracks AS (
|
|
129
|
+
SELECT id FROM process_counter_track WHERE upid IN (${s}) AND name IN ('mem.rss.anon','mem.rss.file','mem.rss.shmem')
|
|
130
|
+
), times AS (SELECT DISTINCT ts FROM counter WHERE track_id IN (SELECT id FROM tracks))
|
|
131
|
+
SELECT ts, (SELECT SUM((SELECT value FROM counter c WHERE c.track_id=t.id AND c.ts<=times.ts ORDER BY c.ts DESC LIMIT 1)) FROM tracks t) AS bytes
|
|
132
|
+
FROM times ORDER BY ts`);const p=await i(`WITH frames AS (
|
|
133
|
+
SELECT surface_frame_token,
|
|
134
|
+
MAX(CASE WHEN jank_type NOT IN ('None','Unknown') THEN 1 ELSE 0 END) AS janky,
|
|
135
|
+
MAX(CASE WHEN present_type='Dropped Frame' THEN 1 ELSE 0 END) AS dropped
|
|
136
|
+
FROM actual_frame_timeline_slice WHERE upid IN (${s}) AND dur>=0 GROUP BY surface_frame_token
|
|
137
|
+
) SELECT COUNT(*) AS total, SUM(janky) AS janky, SUM(dropped) AS dropped FROM frames`);return{durationMs:h,sched:u.map(m=>({timeMs:Number(m.timeMs),durationMs:Number(m.durationMs),tid:Number(m.tid),name:m.name,main:m.main==="1"})),functions:[...f.values()].sort((m,g)=>g.selfMs-m.selfMs),symbols:d.map(m=>({timeMs:Number(m.timeMs),tid:Number(m.tid),symbol:m.symbol.slice(0,180)})),rss:_.map(m=>Number(m.bytes)),frames:Number(p[0]?.total)>0?{source:"frame-timeline",total:Number(p[0].total),janky:Number(p[0].janky),dropped:Number(p[0].dropped)}:null}}function summarizeAndroid(e,t){const r=new Map;const o=e.sched.filter(u=>u.durationMs>0&&u.timeMs>=0&&u.timeMs<e.durationMs).map(u=>({...u,durationMs:Math.min(u.durationMs,e.durationMs-u.timeMs)}));for(const u of o){const d=r.get(u.tid)??{tid:u.tid,name:u.name.slice(0,100),cpuMs:0,main:u.main};d.cpuMs+=u.durationMs;r.set(u.tid,d)}const a=o.filter(u=>u.main).sort((u,d)=>u.timeMs-d.timeMs);const i=[];let n=[];let s=-1;const c=()=>{if(!n.length)return;const u=n[0].timeMs;const d=s-u;const f=n.reduce((_,p)=>_+p.durationMs,0);if(d>=t&&f/d>=.6){const _=new Map;for(const p of e.symbols??[])if(p.tid===n[0].tid&&p.timeMs>=u&&p.timeMs<s){_.set(p.symbol,(_.get(p.symbol)??0)+1)}i.push({startMs:u,durationMs:d,method:"sched-busy",sampleCount:n.length,topSymbols:[..._].sort((p,m)=>m[1]-p[1]).slice(0,3).map(p=>p[0])})}n=[]};for(const u of a){if(s>=0&&u.timeMs-s>10)c();n.push(u);s=u.timeMs+u.durationMs}c();i.sort((u,d)=>d.durationMs-u.durationMs);const l=memorySummary(e.rss,"perfetto-process-stats");const h=!e.frames?null:e.frames.total<30?{source:"frame-timeline",total:e.frames.total,minimum:30,status:"too-few-frames",janky:null,dropped:null}:{...e.frames,minimum:30,status:"captured"};return{sampleCount:o.length,mainThreadBusyPct:o.length?Math.min(100,a.reduce((u,d)=>u+d.durationMs,0)/e.durationMs*100):null,hotFunctions:e.functions.slice(0,10),hotThreads:[...r.values()].sort((u,d)=>d.cpuMs-u.cpuMs).slice(0,10),stalls:i.slice(0,10),totals:{hotFunctions:e.functions.length,stalls:i.length},memory:l,frames:h,coverage:{cpu:e.functions.length?"perf-samples":o.length?"sched":"unavailable",stalls:o.length?"sched-busy":"unavailable",memory:l?.source??"unavailable",frames:e.frames?"frame-timeline":"unavailable"}}}var exec3=(0,import_node_util6.promisify)(import_node_child_process13.execFile);var sleep2=e=>new Promise(t=>setTimeout(t,e));async function androidPid(e,t){const r=(await adbShell(e,`pidof ${q(assertPackage(t))}`)).trim();if(!/^\d+$/.test(r))throw new Error("Open the chosen Android app first.");return Number(r)}function perfettoConfig(e,t){assertPackage(e);return`duration_ms: ${t}
|
|
138
|
+
buffers { size_kb: 32768 fill_policy: DISCARD }
|
|
139
|
+
write_into_file: true
|
|
140
|
+
file_write_period_ms: 250
|
|
141
|
+
max_file_size_bytes: 268435456
|
|
142
|
+
data_sources { config { name: "linux.ftrace" ftrace_config {
|
|
143
|
+
ftrace_events: "sched/sched_switch" ftrace_events: "sched/sched_waking"
|
|
144
|
+
ftrace_events: "power/cpu_frequency" ftrace_events: "power/cpu_idle"
|
|
145
|
+
atrace_categories: "gfx" atrace_categories: "view" atrace_categories: "am" atrace_categories: "dalvik"
|
|
146
|
+
atrace_apps: "${e}"
|
|
147
|
+
} } }
|
|
148
|
+
data_sources { config { name: "linux.process_stats" process_stats_config {
|
|
149
|
+
scan_all_processes_on_start: true proc_stats_poll_ms: 250
|
|
150
|
+
} } }
|
|
151
|
+
data_sources { config { name: "android.surfaceflinger.frametimeline" } }
|
|
152
|
+
data_sources { config { name: "linux.perf" perf_event_config {
|
|
153
|
+
timebase { counter: SW_CPU_CLOCK frequency: 100 timestamp_clock: PERF_CLOCK_MONOTONIC }
|
|
154
|
+
callstack_sampling { scope { target_cmdline: "${e}" } }
|
|
155
|
+
} } }
|
|
156
|
+
`}var captureAndroid=(e,t,r,o)=>{const a=e.serial;const i=import_node_path23.default.basename(t);if(!/^[a-f0-9-]{36}$/.test(i))throw new Error("Bad trace folder ID.");const n=`/data/misc/perfetto-traces/buoy-${i}.perfetto-trace`;const s=import_node_path23.default.join(t,"capture.perfetto-trace");let c;let l;const h=new Promise((v,y)=>{c=v;l=y});void h.catch(()=>{});let u;let d=false;let f=false;let _=false;const p=new AbortController;const m=async()=>{if(u&&!_)await adbShell(a,`kill -TERM ${u}`).catch(()=>{})};const g=(async()=>{const v=await traceProcessor(process.env.BUOY_TRACE_PROCESSOR_CACHE||import_node_path23.default.join(import_node_path23.default.dirname(t),".tools"),p.signal);if(f)throw new Error("Trace was stopped before it could start.");const y=import_node_path23.default.join(t,"capture.pbtxt");await import_node_fs24.promises.writeFile(y,perfettoConfig(e.appId,r),{mode:384});try{try{const T=exec3("adb",["-s",a,"shell","perfetto","--background-wait","--txt","-c","-","-o",n],{timeout:35e3,maxBuffer:65536});T.child.stdin.on("error",()=>{});T.child.stdin.end(perfettoConfig(e.appId,r));const{stdout:C}=await T;u=Number(/^\s*(\d+)\s*$/m.exec(C)?.[1])}catch(T){u=Number(/^\s*(\d+)\s*$/m.exec(T.stdout??"")?.[1])||void 0;throw new Error(`Perfetto could not start: ${String(T.stderr??"start timed out after 35 seconds").slice(-1e3)}`)}if(!u||!Number.isSafeInteger(u))throw new Error("Perfetto did not return its process ID.");if(d||f)await m();c();const w=Date.now()+r+15e3;while(true){const T=await adbShell(a,`ps -p ${u} -o NAME 2>&1; echo BUOY_PS_EXIT:$?`);const C=T.trim().split(/\r?\n/).map(I=>I.trim());const A=C.pop();const S=C.shift();if(S!=="NAME"||A!=="BUOY_PS_EXIT:0"&&!(A==="BUOY_PS_EXIT:1"&&!C.length)){throw new Error("Android could not read the trace process.")}if(!C.includes("perfetto"))break;if(Date.now()>w)throw new Error("Perfetto took too long to stop.");await sleep2(250)}_=true;if(f)throw new Error("Trace was stopped before it could finish.");const b=Number((await adbShell(a,`stat -c %s ${q(n)}`)).trim());if(!Number.isFinite(b)||b<=0||b>256*1024*1024)throw new Error("Perfetto trace is empty or too large.");await adb(a,["pull",n,s],3e4);await import_node_fs24.promises.chmod(s,384);const E=await androidRows(v,s,e.pid,e.appId,p.signal);const k=summarizeAndroid(E,o);const O=["UI busy spans use scheduler CPU time. Sleeping or blocked hangs are not counted."];if(!E.functions.length)O.push("No call stacks were captured. Hot threads show scheduler CPU time.");else O.push("Function self time uses 100 Hz samples. Some symbols may be missing.");if(!k.memory)O.push("No RSS rows were found. Memory use is unknown.");if(k.frames?.status==="too-few-frames")O.push(`Too few frames to judge: ${k.frames.total}. Need at least 30 app frame rows.`);if(!E.frames)O.push("No app frame rows were found. Frame counts are unknown.");return{samples:[],hangs:[],durationMs:E.durationMs,warnings:O,memory:k.memory,summary:k}}finally{await m();await adbShell(a,`rm -f ${q(n)}`).catch(()=>{})}})().catch(v=>{l(v);throw v});void g.catch(()=>{});return{ready:h,result:g,stop(){d=true;void m()},cancel(){f=true;p.abort();void m()}}};function summarize2(e,t,r,o=[]){const a=e.filter(d=>d.running&&d.timeMs>=0&&d.timeMs<t);const i=new Map;for(const d of a){const f=d.frames[0];if(!f)continue;const _=`${f.image}\0${f.symbol}`;const p=i.get(_)??{...f,selfMs:0,samples:0};p.selfMs+=Math.min(d.weightMs,t-d.timeMs);p.samples++;i.set(_,p)}const n=[...i.values()].sort((d,f)=>f.selfMs-d.selfMs);const s=new Map;for(const d of a.filter(f=>f.main)){const f=s.get(d.tid)??[];f.push(d);s.set(d.tid,f)}const c=[];let l=0;for(const d of s.values()){d.sort((m,g)=>m.timeMs-g.timeMs);let f=[];let _=-1;const p=()=>{if(!f.length)return;const m=f[0].timeMs;const g=Math.min(_,t)-m;let v=0;let y=-1;for(const w of f){const b=Math.min(t,w.timeMs+Math.min(w.weightMs,10));v+=Math.max(0,b-Math.max(y,w.timeMs));y=Math.max(y,b)}if(g>=r&&f.length>=Math.ceil(r/10)&&v/g>=.6){const w=new Map;for(const b of f)for(const E of b.frames.slice(0,4))w.set(E.symbol,(w.get(E.symbol)??0)+b.weightMs);c.push({startMs:m,durationMs:g,method:"sample-density",sampleCount:f.length,topSymbols:[...w].sort((b,E)=>E[1]-b[1]).slice(0,3).map(b=>b[0])})}f=[]};for(const m of d){if(_>=0&&m.timeMs-_>10)p();l+=Math.max(0,Math.min(m.timeMs+m.weightMs,t)-Math.max(m.timeMs,_));f.push(m);_=Math.max(_,m.timeMs+m.weightMs)}p()}const h=o.filter(d=>d.startMs>=0&&d.startMs<t).map(d=>({...d,durationMs:Math.min(d.durationMs,t-d.startMs)}));const u=[...h,...c.filter(d=>!h.some(f=>d.startMs<f.startMs+f.durationMs&&f.startMs<d.startMs+d.durationMs))].sort((d,f)=>f.durationMs-d.durationMs);return{sampleCount:a.length,mainThreadBusyPct:a.length?Math.min(100,l/t*100):null,hotFunctions:n.slice(0,10),stalls:u.slice(0,10),totals:{hotFunctions:n.length,stalls:u.length},coverage:{cpu:a.length?"captured":"unavailable",stalls:h.length?"os-hang":a.length?"sample-density":"unavailable",memory:"unavailable",frames:"unavailable"}}}var services=new Set;var alive2=e=>{if(!e||!Number.isInteger(e)||e<1)return false;try{process.kill(e,0);return true}catch(t){return t.code!=="ESRCH"}};var terminal=e=>e.state==="ready"||e.state==="failed";var ProfileService=class{constructor(e=process.env.BUOY_NATIVE_PROFILE_DIR||import_node_path24.default.join(import_node_os14.default.homedir(),".buoy","native-profiles"),t=(r,...o)=>(r.platform==="android"?captureAndroid:captureIos)(r,...o)){this.root=e;this.factory=t;this.disposed=false;this.starts=new Set;this.captures=new Set;this.writes=Promise.resolve();this.runs=new Map;services.add(this)}start(e,t={}){if(this.disposed)return Promise.reject(new Error("This trace host is closed."));const r=this.startRun(e,t);this.starts.add(r);void r.finally(()=>this.starts.delete(r)).catch(()=>{});return r}async startRun(e,t){const r=t.durationMs??6e4;const o=t.thresholdMs??250;if(!Number.isInteger(r)||r<1e3||r>6e4||!Number.isInteger(o)||o<100||o>5e3)throw new Error("Trace time or stall limit is out of range.");await import_node_fs25.promises.mkdir(this.root,{recursive:true,mode:448});const a=import_node_path24.default.join(this.root,`lock-${(0,import_node_crypto13.createHash)("sha256").update(e.serial??e.udid??"").digest("hex").slice(0,24)}`);const i=()=>import_node_fs25.promises.open(a,"wx",384);let n;try{n=await i()}catch{const f=`${a}.recover`;try{await import_node_fs25.promises.mkdir(f);try{const _=JSON.parse(await import_node_fs25.promises.readFile(a,"utf8"));if(alive2(_.ownerPid)||alive2(_.recorderPid))throw new Error("live");await import_node_fs25.promises.unlink(a);n=await i()}finally{await import_node_fs25.promises.rmdir(f)}}catch{throw new Error("A trace already owns this sim. Stop it in the host that started it.")}}let s=false;const c=async()=>{if(s)return;s=true;await import_node_fs25.promises.unlink(a).catch(()=>{})};const l=(0,import_node_crypto13.randomUUID)();const h=import_node_path24.default.join(this.root,l);let u;let d;try{await n.writeFile(JSON.stringify({ownerPid:process.pid,profileId:l}));await n.close();await import_node_fs25.promises.mkdir(h,{mode:448});const f={schemaVersion:1,profileId:l,state:"starting",target:{...e},startedAt:new Date().toISOString(),durationMs:0,thresholdMs:o,attachRetries:0,memory:null,frames:null,hotThreads:[],sampleCount:0,mainThreadBusyPct:null,hotFunctions:[],stalls:[],totals:{hotFunctions:0,stalls:0},coverage:{cpu:"unavailable",stalls:"unavailable",memory:"unavailable",frames:"unavailable"},warnings:[],artifacts:{tracePath:import_node_path24.default.join(h,e.platform==="android"?"capture.perfetto-trace":"capture.trace"),reportPath:import_node_path24.default.join(h,"report.json")}};d=f;await this.save(f);if(this.disposed)throw new Error("This trace host is closed.");u=this.factory(e,h,r,o,p=>{(0,import_node_fs25.writeFileSync)(a,JSON.stringify({ownerPid:process.pid,profileId:l,recorderPid:p}),{mode:384})});this.captures.add(u);await import_node_fs25.promises.writeFile(a,JSON.stringify({ownerPid:process.pid,profileId:l,recorderPid:u.pid}),{mode:384});const _=u.result.then(p=>{f.state="processing";f.durationMs=p.durationMs;Object.assign(f,p.summary??summarize2(p.samples,p.durationMs,o,p.hangs));f.memory=p.memory??null;f.coverage.memory=f.memory?.source??"unavailable";f.attachRetries=u?.attachRetries??0;f.warnings=p.warnings;f.state=f.sampleCount?"ready":"failed";if(!f.sampleCount)f.error="No running CPU samples were captured. This run cannot rule out a stall.";return f}).catch(p=>{f.attachRetries=u?.attachRetries??0;f.state="failed";f.error=String(p instanceof Error?p.message:p).slice(0,1200);return f}).then(async p=>{await this.save(p);return p}).finally(async()=>{this.captures.delete(u);await c();await this.prune()});void _.catch(()=>{});this.runs.set(l,{report:f,capture:u,done:_});try{await u.ready}catch{await _;throw new Error(`${f.error||"Trace did not start."} (profileId: ${l}; attachRetries: ${f.attachRetries})`)}f.attachRetries=u.attachRetries??0;if(!terminal(f)){f.state="recording";await this.save(f)}return structuredClone(f)}catch(f){u?.cancel();await u?.result.catch(()=>{});if(u)this.captures.delete(u);await n.close().catch(()=>{});await c();if(d&&!this.runs.has(l)){d.state="failed";d.error=String(f instanceof Error?f.message:f).slice(0,1200);await this.save(d).catch(()=>{})}throw f}}async stop(e){const t=this.runs.get(e);if(!t){const r=await this.get(e);if(!terminal(r))throw new Error("Stop this trace in the host that started it.");return r}if(!terminal(t.report)&&t.report.state!=="stopping"){t.report.state="stopping";t.capture.stop()}return structuredClone(await t.done)}async wait(e){const t=this.runs.get(e);if(!t)throw new Error("This host does not own that trace.");return structuredClone(await t.done)}async get(e){if(!/^[a-f0-9-]{36}$/.test(e))throw new Error("Bad profile ID.");const t=this.runs.get(e);if(t)return structuredClone(t.report);const r=import_node_path24.default.join(this.root,e,"report.json");const o=await import_node_fs25.promises.stat(r).catch(()=>null);if(!o||o.size>16384)throw new Error("That profile was not found or is too large.");const a=JSON.parse(await import_node_fs25.promises.readFile(r,"utf8"));if(a.schemaVersion!==1||a.profileId!==e||!a.target?.deviceId)throw new Error("That profile is not valid.");return a}async dispose(){this.disposed=true;this.captures.forEach(e=>e.cancel());await Promise.allSettled([...this.starts]);await Promise.allSettled([...this.runs.values()].map(e=>e.done));services.delete(this)}async save(e){let t=JSON.stringify(e);if(Buffer.byteLength(t)>16384&&(e.hotFunctions.length||e.stalls.length)){e.warnings.push("Some rows were left out to fit the report size cap.");while(Buffer.byteLength(t)>16384&&(e.hotFunctions.length||e.stalls.length)){if(JSON.stringify(e.hotFunctions).length>JSON.stringify(e.stalls).length)e.hotFunctions.pop();else e.stalls.pop();t=JSON.stringify(e)}}if(Buffer.byteLength(t)>16384)throw new Error("Profile report is too large.");const r=`${e.artifacts.reportPath}.${(0,import_node_crypto13.randomUUID)()}.tmp`;const o=this.writes.then(async()=>{try{await import_node_fs25.promises.writeFile(r,t,{mode:384});await import_node_fs25.promises.rename(r,e.artifacts.reportPath)}finally{await import_node_fs25.promises.rm(r,{force:true})}});this.writes=o.catch(()=>{});await o}async prune(){const e=[];for(const t of await import_node_fs25.promises.readdir(this.root)){if(!/^[a-f0-9-]{36}$/.test(t))continue;try{const r=await this.get(t);if(terminal(r))e.push({id:t,at:Date.parse(r.startedAt)})}catch{}}e.sort((t,r)=>r.at-t.at);for(const[t,r]of e.entries())if(t>=10||Date.now()-r.at>864e5){await import_node_fs25.promises.rm(import_node_path24.default.join(this.root,r.id),{recursive:true,force:true});this.runs.delete(r.id)}}};async function stopNativeProfiles(){await Promise.allSettled([...services].map(e=>e.dispose()))}var import_node_fs26=require("fs");var import_node_path25=require("path");var import_node_os15=require("os");var import_node_crypto14=require("crypto");var import_headless=require("@buoy-gg/license/headless");var KEY_NAMES=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","NEXT_PUBLIC_BUOY_KEY","REACT_APP_BUOY_KEY"];function readProjectKey(e,t=process.env){for(const r of KEY_NAMES)if(t[r]!==void 0)return(0,import_headless.normalizeLicenseKey)(t[r])||null;for(const r of[".env.development.local",".env.local",".env"]){let o;try{o=(0,import_node_fs26.readFileSync)((0,import_node_path25.join)(e,r),"utf8")}catch{continue}const a=new Map;for(const i of o.split(/\r?\n/)){const n=i.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!n)continue;const s=n[2].trim();const c=s.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);a.set(n[1],c?c[2]:s.split("#")[0].trim())}for(const i of KEY_NAMES)if(a.has(i))return(0,import_headless.normalizeLicenseKey)(a.get(i))||null}return null}var NodeAccount=class{constructor(e,t={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.unsubscribeSession=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>this.hasKeyAccess()||this.session?.getStatus().state==="active";this.lastSessionSync=0;this.projectDir=(0,import_node_path25.resolve)(t.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const r=(0,import_node_crypto14.createHash)("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=t.cacheFile??(0,import_node_path25.join)((0,import_node_os15.homedir)(),".buoy",`account-${r}.json`);this.session=t.session!==void 0?t.session:(0,import_headless.createNodeSession)({audience:import_headless.CLI_AUDIENCE,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx --package=@buoy-gg/core buoy login`.")}})}hasKeyAccess(){return(0,import_headless.resolveAccountAccess)({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted"}start(){if(this.timer)return;if(this.session){this.unsubscribeSession=this.session.subscribe(()=>this.notify());void this.session.load().then(()=>this.notify(),()=>{})}try{const e=JSON.parse((0,import_node_fs26.readFileSync)(this.cacheFile,"utf8"));if(e.valid&&(0,import_headless.verifyCacheSignature)(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;this.unsubscribeSession?.();this.unsubscribeSession=null;if(this.timer)clearInterval(this.timer);this.timer=null;this.key=null;this.cache=null;this.notify()}notify(){const e=this.hasAccess();if(e===this.lastAdmission)return;this.lastAdmission=e;this.changed()}async tick(){if(this.session&&Date.now()-this.lastSessionSync>15e3){this.lastSessionSync=Date.now();void this.session.sync().catch(()=>{})}const e=readProjectKey(this.projectDir);if(e!==this.key){++this.generation;this.key=e;if(this.cache?.licenseKey!==e)this.cache=null;this.nextCheck=0;this.retry=0;if(!e)this.removeCache()}this.notify();if(!e||this.busy||Date.now()<this.nextCheck)return;if(this.cache&&this.hasKeyAccess()&&Date.now()-this.cache.lastValidatedAt<import_headless.LICENSE_LAUNCH_VALIDATION_TTL&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+import_headless.LICENSE_LAUNCH_VALIDATION_TTL;return}this.busy=true;const t=this.generation;try{if((0,import_headless.isDevToken)(e)){const s=(0,import_headless.checkDevToken)(e);if(!s.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),s.claims.iat*1e3);const l=s.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${s.claims.sid}`,valid:true,tier:l,isPro:l==="pro",expiresAt:new Date(s.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}if((0,import_headless.isServiceKey)(e)){const s=await(0,import_headless.exchangeServiceKey)(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(t!==this.generation||readProjectKey(this.projectDir)!==e)return;if(!s.ok){if(s.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL}else{this.nextCheck=Date.now()+(import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]??import_headless.LICENSE_REVALIDATION_INTERVAL)}return}const c=Date.now();const l=s.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${s.claims.sid}`,valid:true,tier:"pro",isPro:true,expiresAt:new Date(l).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,l-60*60*1e3);return}if((0,import_headless.isBuoyToken)(e)){const s=(0,import_headless.verifyFreeToken)(e);if(!s){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${s.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const r=await(0,import_headless.validateLicense)(e);if(t!==this.generation||readProjectKey(this.projectDir)!==e)return;const o=r.data?.relationships?.product?.data?.id;const a=r.meta.code==="EXPIRED"&&((0,import_headless.isRecognizedAccount)(r.data)||this.cache?.licenseKey===e);if(o&&o!==import_headless.KEYGEN_CONFIG.productId||!a&&!(0,import_headless.isAcceptedValidation)(r)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const i=a?"free":(0,import_headless.resolveTier)(r.data);const n=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:r.data?.id??"",valid:true,tier:i,isPro:i==="pro",expiresAt:a?null:r.data.attributes.expiry,cachedAt:n,lastValidatedAt:n});this.persistCache();this.retry=0;this.nextCheck=n+import_headless.LICENSE_REVALIDATION_INTERVAL}catch(r){if(t!==this.generation)return;const o=(0,import_headless.isTransientLicenseError)(r)?import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]:void 0;this.nextCheck=Date.now()+(o??import_headless.LICENSE_REVALIDATION_INTERVAL)}finally{this.busy=false;this.notify()}}persistCache(){try{(0,import_node_fs26.mkdirSync)((0,import_node_path25.dirname)(this.cacheFile),{recursive:true,mode:448});(0,import_node_fs26.writeFileSync)(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});(0,import_node_fs26.renameSync)(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{(0,import_node_fs26.unlinkSync)(this.cacheFile)}catch{}}};var import_node_http2=__toESM(require("http"));var import_node_crypto15=require("crypto");var import_socket=require("socket.io-client");var import_sync_broker2=require("@buoy-gg/sync-broker");var import_sync_broker=require("@buoy-gg/sync-broker");var BROKER_PORT2=import_sync_broker.DEFAULT_BROKER_PORT;var BROKER_URL=`http://localhost:${BROKER_PORT2}`;var DEFAULT_ACTION_TIMEOUT_MS=15e3;var UNRESPONSIVE_ACTION_TIMEOUT_MS=2500;var UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS=1200;var RECOVERY_PROBE_MS=2e4;var UNRESPONSIVE_AFTER_MS=3e4;var DEFAULT_SNAPSHOT_TIMEOUT_MS=5e3;var DEVICE_RETENTION_MS=15*6e4;var DASHBOARD_NAME="Dashboard";var ALL_DEVICES="All";var import_node_child_process14=require("child_process");var import_node_util7=require("util");var import_node_path26=__toESM(require("path"));var import_node_os16=__toESM(require("os"));var execFileAsync4=(0,import_node_util7.promisify)(import_node_child_process14.execFile);async function devServerRoot(e){let t;try{t=new URL(e)}catch{return null}if(!isLocalHost(t.hostname))return null;const r=t.port||(t.protocol==="https:"?"443":"80");try{const{stdout:o}=await execFileAsync4("lsof",["-nP",`-iTCP:${r}`,"-sTCP:LISTEN","-t"],{timeout:3e3});const a=o.split("\n").map(s=>s.trim()).find(Boolean);if(!a)return null;const{stdout:i}=await execFileAsync4("lsof",["-a","-p",a,"-d","cwd","-Fn"],{timeout:3e3});const n=i.split("\n").find(s=>s.startsWith("n"));return n?import_node_path26.default.resolve(n.slice(1)):null}catch{return null}}function isLocalHost(e,t=import_node_os16.default.networkInterfaces()){const r=e.replace(/^\[|\]$/g,"").toLowerCase();if(r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="10.0.2.2"||r==="10.0.3.2")return true;return Object.values(t).flat().some(o=>o?.address?.toLowerCase()===r)}function pickByProject(e,t){const r=import_node_path26.default.resolve(t);const o=e.map(n=>({deviceId:n.deviceId,score:n.root?closeness(import_node_path26.default.resolve(n.root),r):-1})).filter(n=>n.score>=0);if(o.length===0)return null;const a=Math.min(...o.map(n=>n.score));const i=o.filter(n=>n.score===a);return i.length===1?i[0].deviceId:null}function closeness(e,t){if(e===t)return 0;const r=import_node_path26.default.relative(e,t);const o=import_node_path26.default.relative(t,e);const a=i=>i&&!i.startsWith("..")&&!import_node_path26.default.isAbsolute(i);if(a(r))return r.split(import_node_path26.default.sep).length;if(a(o))return o.split(import_node_path26.default.sep).length;return-1}var import_node_async_hooks2=require("async_hooks");var FREE_APP_CALLS={"highlight-updates":["describeScreen","tapElement","hitTest","readMaps","setSilentTracking"],"route-events":["@snapshot","getCurrentRoute","navigate"],app:["@snapshot","ping","reloadApp"],console:["@snapshot"],network:["@snapshot"],storage:["async.getAllKeys","secure.keys"],"perf-monitor":["@snapshot","getAutomationConfig","setAutomationConfig","acknowledgeAutomation","setEnabled","refreshIndex","startAutomation","loadReport"],"js-top":["sample"]};function isFreeAppCall(e,t){return Object.prototype.hasOwnProperty.call(FREE_APP_CALLS,e)&&FREE_APP_CALLS[e].includes(t)}var clock=()=>new Date;function isWeekendPass(e=clock()){const t=e.getDay();return t===0||t===6}function weekendNow(){return scope.getStore()?.weekend??isWeekendPass()}function hasProAccess(e){if(!e)return false;if(e.isPro===true)return true;return e.tier==="free"&&weekendNow()}var scope=new import_node_async_hooks2.AsyncLocalStorage;function outsideCalls(e){return scope.exit(e)}function currentAccess(){return scope.getStore()??{tool:"",level:"pro"}}function meetsAccess(e,t){if(!e)return false;if(hasProAccess(e))return true;return t==="free"&&e.tier==="free"}var FREE_SUMMARY="Free covers reading the screen, taps, swipes and typing, run_flow, screenshots, screen recording, device_control, reload_app, navigate, get_routes, get_console, the request list and get_triage. It also covers Buoy Optimize and the Sim Farm: benchmark batches, reports, web benchmarks and JS thread totals, without the render names, script names and JS origins that say why. Every Saturday and Sunday a free account gets everything Pro does.";function proRequiredMessage(e,t){const r=e.proOption?`\`${e.tool}\` with \`${e.proOption}\` needs Buoy Pro.`:e.tool?`\`${e.tool}\` needs Buoy Pro.`:"This needs Buoy Pro.";return`${r}${t} ${FREE_SUMMARY} Tell the user Pro unlocks the rest (https://buoy.gg/pricing). After upgrading, the user runs \`npx --package=@buoy-gg/core buoy login\` again, or signs in again in the app. An app with no on-device UI can take a Pro key through \`licenseKey\`. No setting, argument or other tool turns Pro on, so don't try to work around it.`}function isRecoveryAction(e,t){return e==="app"&&(t==="ping"||t==="reloadApp")}function isUnresponsive(e){return e>=2}function actionTimeoutMs(e){if(isRecoveryAction(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!isUnresponsive(e.consecutiveTimeouts)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(e.now-e.lastFullBudgetAt>e.recoveryProbeMs){return{timeoutMs:e.fullMs,usedFullBudget:true}}return{timeoutMs:e.shortMs,usedFullBudget:false}}function diagnoseCrashed(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var WAIT_FOR_MAX_MS=3e4;var WAIT_FOR_MARGIN_MS=5e3;function selfTimedBudgetMs(e,t,r){if(e!=="highlight-updates"||t!=="waitFor")return 0;const o=Number(r?.timeoutMs);if(!Number.isFinite(o)||o<=0)return 0;return Math.min(o,WAIT_FOR_MAX_MS)+WAIT_FOR_MARGIN_MS}var NOT_READY_MARK="Not ready:";var SyncClient=class{constructor(e={}){this.socket=null;this.admitted=false;this.createdAt=Date.now();this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.sessionDevice=null;this.snapshots=new Map;this.watching=new Map;this.pendingActions=new Map;this.snapshotWaiters=new Map;this.snapshotAt=new Map;this.health=new Map;this.devServerOrigins=new Map;this.crashSeen=new Map;this.rootLookups=new Set;this.devServerRoots=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.transportLost=false;this.deviceConnections=new Map;if(e.dashboardToken!==void 0&&!e.dashboardToken.trim())throw new Error("The host token must not be empty.");this.dashboardToken=e.dashboardToken;this.port=e.port??BROKER_PORT2;this.url=e.url??(e.port?`http://localhost:${e.port}`:BROKER_URL);this.actionTimeoutMs=e.actionTimeoutMs??DEFAULT_ACTION_TIMEOUT_MS;this.log=e.log??(t=>process.stderr.write(`[buoy-mcp] ${t}
|
|
157
|
+
`));this.autoSpawn=e.dashboardToken?false:e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let t="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let r=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:o=>{if(o.code==="EADDRINUSE")r=true;this.log(`broker error: ${o.code??o.message}`)}});await waitForBroker(this.url).catch(o=>{if(!r)throw o});if(!this.broker.httpServer.listening)r=true;if(r){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(o){this.log(`could not write the broker token file: ${o.message}`)}t="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return t}connectSocket(){return outsideCalls(()=>new Promise((e,t)=>{const r=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:s=>{const c=this.dashboardToken??this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));s(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=r;let o=false;const a=()=>{if(o)return;o=true;this.log("connected to broker");e()};const i=setTimeout(()=>{if(o)return;o=true;t(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx --package=@buoy-gg/core buoy login for standalone MCP."))},5e3);r.on("buoy:access",s=>{const c=!!s&&typeof s==="object"&&s.protocol===1&&s.ready===true;this.setAdmission(c);if(c){clearTimeout(i);this.rearmWatches();a()}});r.on("connect",()=>{r.emit("buoy:access:request")});r.on("disconnect",()=>this.setAdmission(false,true));const n=s=>s.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;r.once("connect_error",s=>{if(o)return;o=true;clearTimeout(i);t(new Error(n(s)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${s.message}`))});r.on("connect_error",s=>{if(!n(s)||r.active)return;setTimeout(()=>{if(this.socket===r&&!r.connected)r.connect()},1e3).unref?.()});r.on("devtool-capabilities",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;this.capabilities.set(s.persistentDeviceId,s);this.trackRootLookup(this.learnDevServerOrigin(s.persistentDeviceId));if(s.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",s.persistentDeviceId)});r.on("all-devices-update",s=>{if(!this.admitted)return;if(!Array.isArray(s))return;let c=false;for(const h of s){if(h.deviceId&&(h.tier==="locked"||h.tier==="checking"))this.lockDevice(String(h.deviceId),h.tier==="checking");else if(h.deviceId&&(h.tier==="free"||h.tier==="pro")){c=this.lockedDevices.delete(String(h.deviceId))||c}}this.devices=s;const l=Date.now();for(const h of s)if(h.deviceId)this.lastSeen.set(h.deviceId,l);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(s)});r.on("devtool-sync",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;const c=snapKey(s.persistentDeviceId,s.toolId);this.snapshots.set(c,s.payload);this.snapshotAt.set(c,Date.now());if(s.toolId==="console")this.noteCrashReport(s.persistentDeviceId,s.payload);const l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const h of l)h(s.payload)}});r.on("devtool-action-result",s=>{if(!this.admitted)return;const c=this.pendingActions.get(s.requestId);if(!c)return;this.pendingActions.delete(s.requestId);clearTimeout(c.timer);c.resolve(s)})}))}isAdmitted(){return this.admitted}requireAdmission(){if(this.transportLost)throw new Error("The broker link was lost. Wait for it to reconnect.");if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx --package=@buoy-gg/core buoy login for standalone MCP.")}setAdmission(e,t=false){this.transportLost=!e&&t;this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!t)this.watching.clear();for(const r of this.pendingActions.values()){clearTimeout(r.timer);r.reject(new Error(t?"The broker link was lost during the call. Its result is unknown.":"Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const r of this.snapshotWaiters.values())for(const o of r)o(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.devices.some(t=>t.deviceId===e&&t.tier==="checking"))throw new Error(`${NOT_READY_MARK} The new app link is still checking access.`);if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e,t=false){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const r=`${e}::`;for(const o of this.snapshots.keys())if(o.startsWith(r)){this.snapshots.delete(o);this.snapshotAt.delete(o)}for(const[o,a]of this.snapshotWaiters)if(o.startsWith(r)){this.snapshotWaiters.delete(o);for(const i of a)i(void 0)}for(const[o,a]of this.pendingActions)if(a.target===e||a.target===ALL_DEVICES){clearTimeout(a.timer);this.pendingActions.delete(o);a.reject(new Error(t?"The app link changed during the call. Its result is unknown.":"Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[t,r]of this.lastSeen){if(r>e)continue;if(this.devices.some(a=>a.deviceId===t))continue;this.lastSeen.delete(t);this.capabilities.delete(t);this.health.delete(t);this.devServerOrigins.delete(t);this.devServerRoots.delete(t);this.originProbed.delete(t);const o=`${t}::`;for(const a of[...this.snapshots.keys()]){if(a.startsWith(o)){this.snapshots.delete(a);this.snapshotAt.delete(a)}}for(const a of[...this.watching.keys()]){if(a.startsWith(o))this.watching.delete(a)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const t of e)t(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const t=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"||e.tier==="checking"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:t?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(t=>{const r=t.tools.find(o=>o.toolId===e);return r?{deviceId:t.deviceId,deviceName:t.deviceName,actions:r.actions}:null}).filter(t=>t!==null)}peekProjectDevice(){if(!this.admitted)return null;if(this.sessionDevice)return this.sessionDevice;const e=this.connectedDevices().filter(r=>!this.lockedDevices.has(r.deviceId)&&r.tools.length>0);const t=process.env.BUOY_PROJECT_ROOT||process.cwd();return pickByProject(e.map(r=>({deviceId:r.deviceId,root:this.devServerRoots.get(r.deviceId)})),t)??null}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const t=(l,h)=>new Error(`${NOT_READY_MARK} "${l}" (${h}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const l=this.devices.find(h=>h.deviceId===this.sessionDevice);if(l&&l.isConnected!==false)return this.sessionDevice;throw t(this.sessionDevice,"the device this session was using")}const r=this.connectedDevices();const o=r.filter(l=>!this.lockedDevices.has(l.deviceId));const a=o.filter(l=>l.tools.length>0);const i=process.env.BUOY_PROJECT_ROOT||process.cwd();const n=pickByProject(a.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),i);if(n)return this.sessionDevice=n;const s=pickByProject(this.devices.filter(l=>l.deviceId&&l.isConnected===false&&!this.lockedDevices.has(l.deviceId)).map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),i);if(s)throw t(s,"this project's app");if(o.length===0){if(r.length>0){throw new Error(`Devices are connected (${r.map(l=>l.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(o.length===1)return this.sessionDevice=o[0].deviceId;if(a.length===1)return this.sessionDevice=a[0].deviceId;if(a.length===0){const l=o.map(h=>h.deviceName).join(", ");throw new Error(`Connected devices (${l}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=a.map(l=>`${l.deviceName} (${l.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();const t=currentAccess();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const r=n=>{if(!n)return"";return n.tier==="locked"?` The broker has not confirmed account access for "${n.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${n.deviceName}" is on the ${n.tier} tier.`};const o=n=>t.level==="pro"?proRequiredMessage(t,r(n)):`The Buoy MCP needs an app on a Buoy account.${r(n)} Run \`npx --package=@buoy-gg/core buoy login\` in the project (free), restart the dev server with its cache cleared, then run \`list_devices\` to check.`;if(e===ALL_DEVICES){const n=this.connectedDevices().filter(c=>c.isPro||c.tier==="free");const s=n.find(c=>!meetsAccess(c,t.level));if(n.length===0)throw new Error(o());if(s)throw new Error(o(s));return ALL_DEVICES}const a=this.resolveDevice(e);const i=this.connectedDevices().find(n=>n.deviceId===a);if(!meetsAccess(i,t.level)){const n=this.accessState(a,t.level);if(n==="offline")throw new Error(`${NOT_READY_MARK} "${a}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(n==="pending")throw new Error(`${NOT_READY_MARK} account access for "${a}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(o(i))}return a}checkAppCall(e,t,r){const o=currentAccess();if(!o.tool)return;const a=r===ALL_DEVICES?this.connectedDevices().find(i=>i.tier==="free"&&!hasProAccess(i)):this.listDevices().find(i=>i.deviceId===r&&!hasProAccess(i));if(!a)return;if(o.level==="free"&&isFreeAppCall(e,t))return;throw new Error(proRequiredMessage({...o,level:"pro"},` The app "${a.deviceName}" is on the ${a.tier} tier${o.level==="free"?`, and this part of \`${o.tool}\` reads its ${e} data, which is Pro`:""}.`))}refuseBuoyPanelTap(e,t,r,o){if(e!=="highlight-updates"||t!=="tapElement")return null;const a=currentAccess();if(!a.tool||a.level!=="free")return null;const i=r??{};const n=typeof i.nativeTag==="number"?i.nativeTag:null;const s=typeof i.testID==="string"&&i.testID?i.testID.toLowerCase():null;const c=n!=null||s!=null||!!i.includeBuoy;if(o===ALL_DEVICES){if(!c||!this.connectedDevices().some(u=>u.tier==="free"&&!hasProAccess(u)))return null;return Promise.reject(new Error(proRequiredMessage({...a,level:"pro"},' On a free app, tap one app at a time (not "All") when tapping by testID or nativeTag.')))}const l=this.listDevices().find(u=>u.deviceId===o);if(!l||hasProAccess(l)||!c)return null;const h=u=>new Error(proRequiredMessage({...a,level:"pro"},u));if(i.includeBuoy)return Promise.reject(h(" That reaches Buoy's own panel, not the app."));return(async()=>{let u;try{u=await this.callAction("highlight-updates","describeScreen",{includeBuoy:false,includeHidden:true},o,{timeoutMs:4e3,silent:true})}catch(f){throw new Error(`Could not check that target before tapping (${f instanceof Error?f.message:String(f)}). On a free app, tap by query, or retry once the screen settles.`)}const d=(u?.elements??[]).some(f=>n!=null?f.nativeTag===n:f.testID?.toLowerCase()===s);if(!d&&n==null&&typeof i.query==="string"){const{testID:f,..._}=i;return _}if(!d){throw new Error(`"${n??String(i.testID)}" is not on the app's screen right now. On a free app, a tap by testID or nativeTag must hit an element describe_screen lists, and Buoy's own panels are Pro. Swipe it into view first, or tap by query.`)}})()}fullResultsFor(e){if(e===ALL_DEVICES){const t=this.connectedDevices();return t.length>0&&t.every(r=>hasProAccess(r))}return hasProAccess(this.listDevices().find(t=>t.deviceId===e))}deviceWasAllowed(e){return meetsAccess(this.listDevices().find(t=>t.deviceId===e),currentAccess().level)}accessState(e,t=currentAccess().level){const r=this.devices.find(o=>o.deviceId===e);if(!r||r.isConnected===false)return"offline";if(hasProAccess(r)||t==="free"&&r.tier==="free")return"ready";return r.tier===void 0||r.tier==="checking"?"pending":"denied"}healthOf(e){let t=this.health.get(e);if(!t){t={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,t)}return t}noteOk(e){const t=this.healthOf(e);t.consecutiveTimeouts=0;t.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,t,r){const o=this.healthOf(e);const{timeoutMs:a,usedFullBudget:i}=actionTimeoutMs({consecutiveTimeouts:o.consecutiveTimeouts,lastFullBudgetAt:o.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:t,action:r});if(i)o.lastFullBudgetAt=Date.now();return a}unresponsiveNote(e){const t=this.healthOf(e);const r=t.lastOkAt?Math.round((Date.now()-t.lastOkAt)/1e3):null;const o=diagnoseCrashed({consecutiveTimeouts:t.consecutiveTimeouts,lastOkAt:t.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const a=[`The app on "${e}" is not responding (${t.consecutiveTimeouts} call${t.consecutiveTimeouts===1?"":"s"} unanswered${r!=null?`, last answered ${r}s ago`:""}).`,o?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const i=this.lastFatalFor(e);if(i)a.push(`Last captured error: ${i}`);a.push(i?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return a.join(" ")}noteCrashReport(e,t){const r=t?.entries;if(!Array.isArray(r)||r.length===0)return;const o=Math.max(...r.map(n=>typeof n?.timestamp==="number"?n.timestamp:-Infinity));const a=this.crashSeen.get(e)??new Set;let i=false;for(const n of r){const s=n?.fatal||/^\[(RENDER ERROR|FATAL)/.test(n?.message??"");if(!s||typeof n.timestamp!=="number")continue;const c=`${n.id??""}|${n.timestamp}|${(n.message??"").slice(0,120)}`;if(a.has(c))continue;a.add(c);if(o-n.timestamp<3e4)i=true}if(a.size>200)for(const n of[...a].slice(0,a.size-200))a.delete(n);this.crashSeen.set(e,a);if(!i)return;if(![...this.pendingActions.values()].some(n=>n.target===e&&n.expire&&!n.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const n=Date.now();for(const s of this.pendingActions.values()){if(s.target!==e||!s.expire||s.cut)continue;s.cut=true;if(s.deadline!==void 0&&s.deadline-n<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(s.timer);s.timer=setTimeout(s.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const t=this.snapshots.get(snapKey(e,"console"));const r=t?.entries;if(!Array.isArray(r))return null;for(let o=r.length-1;o>=0;o--){const a=r[o];if(a?.fatal||a?.level==="error"){const i=(a.message??"").split("\n")[0];if(i)return i.length>300?`${i.slice(0,300)}\u2026`:i}}return null}snapshotAgeMs(e,t){this.requireAdmission();const r=this.snapshotAt.get(snapKey(t,e));return r?Date.now()-r:null}noteDevServerOrigin(e,t){if(typeof t==="string"&&/^https?:\/\//.test(t)){const r=this.devServerOrigins.get(e)!==t;this.devServerOrigins.set(e,t);if(r)this.devServerRoots.delete(e);if(r||!this.devServerRoots.has(e)){const o=devServerRoot(t).then(a=>{if(a&&this.devServerOrigins.get(e)===t)this.devServerRoots.set(e,a)});this.trackRootLookup(o)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const t=this.capabilities.get(e)?.tools?.some(r=>r.toolId==="app");if(!t)return;try{const{payload:r}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,r?.devServerOrigin)}catch{}}trackRootLookup(e){const t=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(t));this.rootLookups.add(t)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(t=>setTimeout(t,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(t=>setTimeout(t,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(t=>setTimeout(t,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(t=>setTimeout(t,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const t=this.devServerOrigins.get(e);if(t)return t;const r=this.snapshots.get(snapKey(e,"app"));if(typeof r?.devServerOrigin==="string")return r.devServerOrigin;return null}ensureWatching(e,t){const r=snapKey(t,e);if(this.watching.has(r))return;this.watching.set(r,{toolId:e,targetDeviceId:t});this.sendWatch(e,t)}sendWatch(e,t){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(t))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:t,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:t}of this.watching.values()){this.sendWatch(e,t)}}rearmReconnectedDevices(e){for(const t of e){if(!t.deviceId||t.isConnected===false)continue;const r=String(t.deviceId);const o=`${t.id}|${t.connectionNonce??""}`;const a=this.deviceConnections.get(r);this.deviceConnections.set(r,o);if(a===void 0||a===o)continue;for(const{toolId:i,targetDeviceId:n}of this.watching.values()){if(n===r)this.sendWatch(i,n)}}}unwatch(e,t){const r=snapKey(t,e);if(!this.watching.delete(r))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:t,watching:false})}cachedSnapshot(e,t){this.requireAdmission();this.requireDeviceAccount(t);this.checkAppCall(e,"@snapshot",t);return this.snapshots.get(snapKey(t,e))}async getSnapshot(e,t,r={}){const o=this.resolveDevice(t);this.checkAppCall(e,"@snapshot",o);const a=this.connectedDevices().find(h=>h.deviceId===o)?.tools??[];if(!r.silent&&a.length>0&&!a.some(h=>h.toolId===e)){throw new Error(`This app doesn't have the "${e}" tool installed, so there is no state to read. The app itself is fine.`)}const i=snapKey(o,e);this.ensureWatching(e,o);let n=r.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(r.timeoutMs===void 0&&this.isUnresponsive(o)){const h=this.healthOf(o);if(Date.now()-h.lastFullBudgetAt>RECOVERY_PROBE_MS){h.lastFullBudgetAt=Date.now()}else{n=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const s=this.waitForSnapshot(i,n);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:o});const c=await s;this.requireAdmission();this.requireDeviceAccount(o);if(c!==void 0){if(!r.silent)this.noteOk(o);return{deviceId:o,payload:c}}if(!r.silent)this.noteTimeout(o);const l=this.snapshots.get(i);if(l!==void 0){return{deviceId:o,payload:l,stale:this.staleNote(e,o)}}throw new Error(`Timed out waiting for "${e}" state from ${o} (is the tool active?). ${this.unresponsiveNote(o)}`)}lastSync(e,t){this.checkAppCall(t,"@snapshot",e);const r=this.snapshots.get(snapKey(e,t));return r===void 0?void 0:{payload:r,ageMs:this.snapshotAgeMs(t,e)}}staleNote(e,t){const r=this.snapshotAgeMs(e,t);const o=r==null?"an earlier sync":`${Math.round(r/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${o}) \u2014 ${this.unresponsiveNote(t)}`}waitForSnapshot(e,t){return new Promise(r=>{const o=this.snapshotWaiters.get(e)??[];const a=setTimeout(()=>{const n=(this.snapshotWaiters.get(e)??[]).filter(s=>s!==i);this.snapshotWaiters.set(e,n);r(void 0)},t);const i=n=>{clearTimeout(a);r(n)};o.push(i);this.snapshotWaiters.set(e,o)})}async callAction(e,t,r,o,a={}){this.requireAdmission();const i=o===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(o);this.checkAppCall(e,t,i);const n=this.refuseBuoyPanelTap(e,t,r,i);if(n)r=await n??r;if(!this.socket)throw new Error("SyncClient is not connected");const s=(0,import_node_crypto15.randomUUID)();const c=a.timeoutMs??Math.max(this.timeoutFor(i,e,t),selfTimedBudgetMs(e,t,r));const l=await new Promise((h,u)=>{const d=Date.now();const f=()=>{this.pendingActions.delete(s);if(i!==ALL_DEVICES&&!a.silent)this.noteTimeout(i);u(new Error(`Action "${e}.${t}" got no answer in ${Date.now()-d}ms. `+(i===ALL_DEVICES?"No device responded.":this.unresponsiveNote(i))))};const _=setTimeout(f,c);this.pendingActions.set(s,{resolve:h,reject:u,timer:_,target:i,expire:f,deadline:d+c});this.socket.emit("devtool-action",{requestId:s,toolId:e,targetDeviceId:i,action:t,params:r??{}})});if(i!==ALL_DEVICES&&!a.silent)this.noteOk(i);if(!l.ok){throw new Error(l.error||`Action "${e}.${t}" failed on device`)}return l.result}};var snapKey=(e,t)=>`${e}::${t}`;function probeBroker(e,t=800){return new Promise(r=>{const o=import_node_http2.default.get(e,a=>{a.resume();r((a.statusCode??0)>0)});o.setTimeout(t,()=>{o.destroy();r(false)});o.on("error",()=>r(false))})}async function waitForBroker(e,t=20){for(let r=0;r<t;r++){if(await probeBroker(e,300))return;await delay(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var delay=e=>new Promise(t=>setTimeout(t,e));var import_zod=require("zod");var profileInput=import_zod.z.object({action:import_zod.z.enum(["start","stop","record"]),deviceId:import_zod.z.string().optional(),udid:import_zod.z.string().uuid().optional(),serial:import_zod.z.string().regex(/^[A-Za-z0-9_.:-]+$/).optional(),profileId:import_zod.z.string().uuid().optional(),durationMs:import_zod.z.number().int().min(1e3).max(6e4).optional(),thresholdMs:import_zod.z.number().int().min(100).max(5e3).optional()}).strict();var getProfileInput=import_zod.z.object({profileId:import_zod.z.string().uuid()}).strict();var import_node_child_process18=require("child_process");var import_node_util11=require("util");var import_node_child_process17=require("child_process");var import_node_util10=require("util");var import_node_fs29=require("fs");var import_node_os19=__toESM(require("os"));var import_node_path29=__toESM(require("path"));var import_node_crypto18=require("crypto");var import_pngjs2=__toESM(require_png());var import_node_child_process15=require("child_process");var import_node_util8=require("util");var import_node_fs27=require("fs");var import_node_os17=__toESM(require("os"));var import_node_path27=__toESM(require("path"));var import_node_crypto16=require("crypto");var execFileAsync5=(0,import_node_util8.promisify)(import_node_child_process15.execFile);function humanizeSimctlError(e){const t=e;if(t?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const r=String(t?.stderr||t?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(r)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return r.trim()||"Failed to capture the iOS Simulator."}var WEBVIEW_ID_KEY="@react_buoy_sync_device_id";async function listDir(e){try{return await import_node_fs27.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const t=[];for(const r of await listDir(e))t.push(...await containerWebViewInstallIds(import_node_path27.default.join(e,r)));return t}async function containerWebViewInstallIds(e){const t=[];const r=import_node_path27.default.join(e,"Library","WebKit");for(const o of await listDir(r)){const a=import_node_path27.default.join(r,o,"WebsiteData","Default");for(const i of await listDir(a)){for(const n of await listDir(import_node_path27.default.join(a,i))){const s=import_node_path27.default.join(a,i,n,"LocalStorage","localstorage.sqlite3");try{await import_node_fs27.promises.access(s);const{stdout:c}=await execFileAsync5("sqlite3",["-readonly",s,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const l=c.trim();if(l)t.push(Buffer.from(l,"hex").toString("utf16le").trim())}catch{}}}}return t}var webViewLookups=new Map;var WEBVIEW_MISS_MS=3e4;async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let t=[];try{const{stdout:o}=await execFileAsync5("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const a=JSON.parse(o).devices;t=Object.entries(a).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(n=>n.state==="Booted"))}catch(o){return{ok:false,error:humanizeSimctlError(o)}}if(t.length===0)return{ok:false,error:"No iOS Simulator is booted."};const r=e?.split("-").pop();if(r){for(const o of t){if(!o.dataPath)continue;const a=import_node_path27.default.join(o.dataPath,"Containers","Data","Application");let i=[];try{i=await import_node_fs27.promises.readdir(a)}catch{continue}for(const n of i){try{const s=(await import_node_fs27.promises.readFile(import_node_path27.default.join(a,n,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(s===r)return{ok:true,udid:o.udid,how:`matched ${e} to "${o.name}"`}}catch{}}}}if(r&&e){const o=t.map(c=>c.udid).sort().join(",");const a=webViewLookups.get(e);const i=a?.booted===o&&(a.udid!==null||Date.now()-a.at<WEBVIEW_MISS_MS);const n=i&&a?.udid?t.find(c=>c.udid===a.udid):void 0;if(n)return{ok:true,udid:n.udid,how:`matched ${e} to "${n.name}" (WebView storage)`};const s=[];if(!i){const c=await Promise.all(t.map(l=>l.dataPath?webViewInstallIds(import_node_path27.default.join(l.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((l,h)=>{if(l.includes(r))s.push(t[h])});webViewLookups.set(e,{booted:o,udid:s.length===1?s[0].udid:null,at:Date.now()})}if(s.length===1){return{ok:true,udid:s[0].udid,how:`matched ${e} to "${s[0].name}" (WebView storage)`}}if(s.length>1){return{ok:false,error:`${s.length} booted simulators (${s.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(t.length===1)return{ok:true,udid:t[0].udid,how:`only booted simulator "${t[0].name}"`};return{ok:false,error:`${t.length} iOS Simulators are booted (${t.map(o=>o.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}var import_node_child_process16=require("child_process");var import_node_util9=require("util");var import_node_fs28=require("fs");var import_node_os18=__toESM(require("os"));var import_node_path28=__toESM(require("path"));var import_node_crypto17=require("crypto");var import_pngjs=__toESM(require_png());var execFileAsync6=(0,import_node_util9.promisify)(import_node_child_process16.execFile);async function devicectl(e,t=3e4){const r=import_node_path28.default.join(import_node_os18.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto17.randomUUID)()}.json`);try{await execFileAsync6("xcrun",["devicectl",...e,"--quiet","--json-output",r],{timeout:t,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs28.promises.readFile(r,"utf8"))}catch(o){const a=o;let i=(a.stderr||a.stdout||a.message||"").trim();try{const n=JSON.parse(await import_node_fs28.promises.readFile(r,"utf8"));i=n.error?.userInfo?.NSLocalizedDescription?.string??i}catch{}if(/locked/i.test(i))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${i.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await import_node_fs28.promises.unlink(r).catch(()=>void 0)}}async function physicalPhones(){if(process.platform!=="darwin")return[];return parsePhones(await devicectl(["list","devices"],15e3).catch(()=>null))}function parsePhones(e){const t=e;return(t?.result?.devices??[]).filter(r=>r.hardwareProperties?.reality==="physical"&&r.hardwareProperties?.platform==="iOS"&&r.connectionProperties?.pairingState==="paired"&&r.connectionProperties?.tunnelState!=="unavailable").map(r=>({udid:r.hardwareProperties.udid,name:r.deviceProperties?.name??"iPhone"})).filter(r=>!!r.udid)}async function developerApps(e){const t=await devicectl(["device","info","apps","--device",e]);return(t.result?.apps??[]).filter(r=>r.bundleIdentifier&&!r.bundleIdentifier.startsWith("com.apple.")&&r.builtByDeveloper!==false).map(r=>({bundleId:r.bundleIdentifier,name:r.name??r.bundleIdentifier,path:r.url?.replace(/^file:\/\//,"")}))}async function readAppFile(e,t,r){const o=await devicectl(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",t],2e4);const a=new Set((o.result?.files??[]).map(n=>n.relativePath??n.name??""));if(!a.has(r))return null;const i=import_node_path28.default.join(import_node_os18.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto17.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",t,"--source",r,"--destination",i],2e4);return await import_node_fs28.promises.readFile(i)}finally{await import_node_fs28.promises.rm(i,{recursive:true,force:true}).catch(()=>void 0)}}async function phoneInstallId(e,t){const r=await readAppFile(e,t,"Documents/react-buoy/@react_buoy_sync_device_id.json").catch(()=>null);const o=r?.toString("utf8").trim().replace(/^"|"$/g,"")??"";return/^[\w-]{4,64}$/.test(o)?o:null}var SIMULATOR=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;var PHONE=/^[0-9A-F]{8}-[0-9A-F]{16}$/i;var OLD_PHONE=/^[0-9A-F]{40}$/i;function isDeviceUdid(e){return typeof e==="string"&&(SIMULATOR.test(e)||PHONE.test(e)||OLD_PHONE.test(e))}function assertUdid(e,t="udid"){if(isDeviceUdid(e))return e;const r=typeof e==="string"?e.slice(0,60):typeof e;throw new Error(`"${r}" is not a ${t}. A simulator udid looks like 1B2C3D4E-5F60-4718-9A2B-3C4D5E6F7A8B (xcrun simctl list devices).`)}var execFileAsync7=(0,import_node_util10.promisify)(import_node_child_process17.execFile);var hosts=new Map;function rememberedHost(e){return hosts.get(e)}async function sh(e,t,r=2e4,o){try{const{stdout:a}=await execFileAsync7(e,t,{timeout:r,maxBuffer:16*1024*1024,env:o?{...process.env,...o}:void 0});return a}catch(a){const i=a;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${t.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}var simctl=(e,t)=>sh("xcrun",["simctl",...e],t);var tailOf=e=>e.split("-").pop()??"";async function simsHolding(e,t){if(!t){const r=await simsHoldingOf(e,["rn"]);return r.length?r:simsHoldingOf(e,["webview"])}return simsHoldingOf(e,t)}async function simsHoldingOf(e,t){let r=[];try{const a=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;r=Object.entries(a).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(n=>n.state==="Booted"))}catch{return[]}const o=await Promise.all(r.map(a=>findIosContainer(e,a.udid,a.dataPath,t)));return r.flatMap((a,i)=>o[i]?[{udid:a.udid,name:a.name,found:o[i]}]:[])}function cloneError(e,t){return new Error(`${t.length} booted simulators hold "${e}" (one is probably a clone): ${t.map(r=>`${r.name} (${r.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,t,r,o){const a=tailOf(e);if(!a)return null;if(!r){try{const c=JSON.parse(await simctl(["list","devices","-j"])).devices;r=Object.values(c).flat().find(l=>l.udid===t)?.dataPath}catch{return null}}if(!r)return null;const i=import_node_path29.default.join(r,"Containers","Data","Application");let n=[];try{n=await import_node_fs29.promises.readdir(i)}catch{return null}const s=await Promise.all(n.map(c=>iosContainerHolds(import_node_path29.default.join(i,c),a,o)));for(const[c,l]of n.entries()){const h=import_node_path29.default.join(i,l);if(!s[c])continue;let u=null;try{u=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path29.default.join(h,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:h,bundleId:u,kind:s[c]}}return null}async function iosContainerHolds(e,t,r=["rn","webview"]){if(r.includes("rn")){try{if((await import_node_fs29.promises.readFile(import_node_path29.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===t)return"rn"}catch{}}if(!r.includes("webview"))return null;return(await containerWebViewInstallIds(e).catch(()=>[])).includes(t)?"webview":null}async function findAndroid(e,t){const r=tailOf(e);const o=t.serial?[t.serial]:await adbSerials();if(o.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const a of o){const i=await adbForegroundPackage(a).catch(()=>null);const n=await adbUserPackages(a).catch(()=>[]);const s=[t.bundleId,i,...n].filter((c,l,h)=>!!c&&h.indexOf(c)===l).slice(0,80);for(const c of s){if(await adbInstallId(a,c).catch(()=>null)===r)return{platform:"android",serial:a,packageName:c}}}return null}async function findPhone(e){const t=tailOf(e);for(const r of await physicalPhones()){for(const o of await developerApps(r.udid).catch(()=>[])){if(await phoneInstallId(r.udid,o.bundleId)===t)return{platform:"ios-device",udid:r.udid,name:r.name,bundleId:o.bundleId}}}return null}var finding=new Map;function findHost(e,t,r={}){if(r.udid||r.serial||r.bundleId)return findHostNow(e,t,r);const o=`${e}|${t??""}`;const a=finding.get(o);if(a)return a;const i=findHostNow(e,t,r).finally(()=>finding.delete(o));finding.set(o,i);return i}async function findHostNow(e,t,r={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const o=hosts.get(e);if(o&&!r.udid&&!r.serial&&await stillHolds(e,o)){if(o.platform==="ios"&&!o.picked){const l=await simsHolding(e,o.idKind?[o.idKind]:void 0);if(l.length>1)throw cloneError(e,l);if(!l.some(h=>h.udid===o.udid)){hosts.delete(e);throw new Error(`The sim no longer holds "${e}". Try the host scan again.`)}}return o}if(o)hosts.delete(e);if(t==="android"){const l=await findAndroid(e,r);if(!l){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${r.serial?` (looked on ${r.serial})`:""}.`)}hosts.set(e,l);return l}if(t&&t!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${t}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let a=r.udid===void 0?void 0:assertUdid(r.udid,"simulator udid");let i=a??"";let n=null;if(!a){const l=await simsHolding(e);n=l.length===1?l[0]:null;if(l.length>1)throw cloneError(e,l);const h=l.length===1?{ok:true,udid:l[0].udid,how:`matched ${e} to "${l[0].name}"`}:await resolveSimUdid(e);if(!h.ok||!/^matched /.test(h.how)){const u=await findPhone(e).catch(()=>null);if(u){hosts.set(e,u);return u}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}a=h.udid;i=/"([^"]+)"/.exec(h.how)?.[1]??a}const s=n?.udid===a?await iosContainerHolds(n.found.container,tailOf(e),[n.found.kind])?n.found:null:await findIosContainer(e,a);if(!s)throw new Error(`Simulator ${a} does not hold "${e}".`);const c={platform:"ios",udid:a,name:i,bundleId:r.bundleId??s?.bundleId??null,container:s?.container??null,picked:!!r.udid,idKind:s.kind};hosts.set(e,c);return c}async function verifyHost(e,t){if(t.platform==="ios"&&!t.picked){const r=await simsHolding(e);if(r.length>1)throw cloneError(e,r)}if(await stillHolds(e,t))return t;hosts.delete(e);return findHost(e,t.platform==="android"?"android":"ios",t.platform==="ios"&&t.picked?{udid:t.udid}:{})}async function stillHolds(e,t){const r=tailOf(e);if(t.platform==="android")return await adbInstallId(t.serial,t.packageName).catch(()=>null)===r;if(t.platform==="ios-device")return await phoneInstallId(t.udid,t.bundleId).catch(()=>null)===r;if(t.container)return!!await iosContainerHolds(t.container,r);const o=await resolveSimUdid(e);return o.ok&&o.udid===t.udid&&/^matched /.test(o.how)}var execFileAsync8=(0,import_node_util11.promisify)(import_node_child_process18.execFile);async function hostTarget(e,t,r={},o={}){if(t==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let a;let i=true;try{a=e.requireProDevice(t)}catch(c){const l=c instanceof Error?c.message:String(c);const h=l.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(l)?/"([^"]+)"/.exec(l)?.[1]:void 0;const u=h?e.deviceWasAllowed(h):false;if(!o.allowOffline||!h||!u)throw c;a=h;i=false}const n=e.listDevices().find(c=>c.deviceId===a)?.platform;let s=await findHost(a,n,r);if(o.changesApp&&rememberedHost(a)===s)s=await verifyHost(a,s);return{id:a,host:s,online:i}}function profileActions(e,t){const r=async a=>{const{profileId:i}=getProfileInput.parse(a);const n=await t.get(i);await hostTarget(e,n.target.deviceId,{udid:n.target.udid,serial:n.target.serial},{allowOffline:true});return n};const o=async a=>{const i=profileInput.parse(a);if(i.udid&&i.serial)throw new Error("Choose a sim ID or an Android serial, not both.");if(i.action==="stop"){if(!i.profileId)throw new Error("Stop needs a profileId.");if(i.deviceId||i.udid||i.serial||i.durationMs||i.thresholdMs)throw new Error("Stop takes only a profileId.");await r({profileId:i.profileId});return t.stop(i.profileId)}if(i.profileId)throw new Error("Start a new run without a profileId.");const{id:n,host:s}=await hostTarget(e,i.deviceId,{udid:i.udid,serial:i.serial},{changesApp:true});if(s.platform==="android"){if(i.udid)throw new Error("Use a serial for an Android trace.");const h=await androidPid(s.serial,s.packageName);const u=await t.start({platform:"android",deviceId:n,serial:s.serial,appId:s.packageName,pid:h},{durationMs:i.durationMs??(i.action==="record"?1e4:6e4),thresholdMs:i.thresholdMs});return i.action==="record"?t.wait(u.profileId):u}if(s.platform!=="ios"||!s.bundleId)throw new Error("Choose an iOS Simulator or an Android app.");if(i.serial)throw new Error("Use a sim ID for an iOS trace.");const c=await simPid(s.udid,s.bundleId);const l=await t.start({deviceId:n,udid:s.udid,appId:s.bundleId,pid:c},{durationMs:i.durationMs??(i.action==="record"?1e4:6e4),thresholdMs:i.thresholdMs});return i.action==="record"?t.wait(l.profileId):l};return{get:r,run:o}}function createNativeProfilerHost(e){const t=new SyncClient({port:e.port,dashboardToken:e.dashboardToken,autoSpawnBroker:false});const r=new ProfileService(e.stateRoot);return{...profileActions(t,r),connect:()=>t.start(),close:async()=>{await r.dispose();await t.stop()}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as i}from"module";const u=i(import.meta.url);import{ProfileService as o,SyncClient as a,getProfileInput as s,profileActions as n,profileInput as c,simPid as p,stopNativeProfiles as f}from"./chunk-TMN3LXKB.mjs";import"./chunk-FYJWWTAC.mjs";import"./chunk-D5K6WO6B.mjs";import"./chunk-MTTWR4T7.mjs";function l(e){const r=new a({port:e.port,dashboardToken:e.dashboardToken,autoSpawnBroker:false});const t=new o(e.stateRoot);return{...n(r,t),connect:()=>r.start(),close:async()=>{await t.dispose();await r.stop()}}}export{o as ProfileService,l as createNativeProfilerHost,s as getProfileInput,c as profileInput,p as simPid,f as stopNativeProfiles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as r}from"module";const t=r(import.meta.url);import{farmFairness as e,registerSimFarmTools as m,runFarmd as o}from"./chunk-
|
|
1
|
+
import{createRequire as r}from"module";const t=r(import.meta.url);import{farmFairness as e,registerSimFarmTools as m,runFarmd as o}from"./chunk-5XATNNKY.mjs";import"./chunk-FYJWWTAC.mjs";import"./chunk-5NOZVPWB.mjs";import"./chunk-D5K6WO6B.mjs";import"./chunk-MTTWR4T7.mjs";export{e as farmFairness,m as registerSimFarmTools,o as runFarmd};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as e}from"module";const Be=e(import.meta.url);import{ALWAYS_ENABLED as r,ANDROID_ADB_PORT as a,BUILT_IN_ANDROID_PHONES as o,BUILT_IN_PHONES as n,ChromeFarm as i,DEFAULT_ANDROID_PHONE as t,DEFAULT_CAP_MB as l,DEFAULT_PHONE as m,DEFAULT_SETTINGS as s,DESKTOP_VIEWPORT as d,EmulatorHost as E,Engine as u,FarmClient as p,FarmError as _,LoadMeter as O,LocalDylibBuilder as L,PHONE_OFF as f,PHONE_VIEWPORT as h,PINNED_VERSION as D,PROTOCOL_VERSION as I,PipeCdp as N,SLIM_CATEGORIES as P,STATE_VERSION as A,SimctlHost as c,Store as S,agentLabel as T,androidHelp as C,androidHome as F,bootEnv as R,buildDylib as H,chromeFarmDir as B,chromeHelp as b,classifyBootLog as g,connectFarm as v,copyCostGB as y,coreInfo as U,crashLoop as V,defaultCapMB as M,defaultSeedDir as G,detectAgent as q,ensureKeeper as x,eventsFilePath as W,farmAdbTarget as k,farmAdbTargets as w,farmDefaults as K,farmHelp as j,farmHome as z,farmOwnedUdids as Y,findDataContainer as J,findExampleBuild as Q,findRepoRoot as X,findShell as Z,installShell as $,joinInsertList as ee,keeperAlive as re,keeperCall as ae,launchFilePath as oe,loadAndroidPhones as ne,loadPhones as ie,measurePhone as te,nodeLauncher as le,parseCpuTime as me,parseEvents as se,parseGfxinfo as de,paths as Ee,phoneDir as ue,profileHash as pe,profileLabels as _e,profileVars as Oe,readBuoyInstallId as Le,readLaunchFile as fe,readSummary as he,removeLaunchFile as De,runAndroidCommand as Ie,runChromeCommand as Ne,runFarmCommand as Pe,savePhone as Ae,simLaunchEnv as ce,slimLabels as Se,startFarmd as Te,suggestCounts as Ce,summarize as Fe,writeLaunchFile as Re}from"./chunk-
|
|
1
|
+
import{createRequire as e}from"module";const Be=e(import.meta.url);import{ALWAYS_ENABLED as r,ANDROID_ADB_PORT as a,BUILT_IN_ANDROID_PHONES as o,BUILT_IN_PHONES as n,ChromeFarm as i,DEFAULT_ANDROID_PHONE as t,DEFAULT_CAP_MB as l,DEFAULT_PHONE as m,DEFAULT_SETTINGS as s,DESKTOP_VIEWPORT as d,EmulatorHost as E,Engine as u,FarmClient as p,FarmError as _,LoadMeter as O,LocalDylibBuilder as L,PHONE_OFF as f,PHONE_VIEWPORT as h,PINNED_VERSION as D,PROTOCOL_VERSION as I,PipeCdp as N,SLIM_CATEGORIES as P,STATE_VERSION as A,SimctlHost as c,Store as S,agentLabel as T,androidHelp as C,androidHome as F,bootEnv as R,buildDylib as H,chromeFarmDir as B,chromeHelp as b,classifyBootLog as g,connectFarm as v,copyCostGB as y,coreInfo as U,crashLoop as V,defaultCapMB as M,defaultSeedDir as G,detectAgent as q,ensureKeeper as x,eventsFilePath as W,farmAdbTarget as k,farmAdbTargets as w,farmDefaults as K,farmHelp as j,farmHome as z,farmOwnedUdids as Y,findDataContainer as J,findExampleBuild as Q,findRepoRoot as X,findShell as Z,installShell as $,joinInsertList as ee,keeperAlive as re,keeperCall as ae,launchFilePath as oe,loadAndroidPhones as ne,loadPhones as ie,measurePhone as te,nodeLauncher as le,parseCpuTime as me,parseEvents as se,parseGfxinfo as de,paths as Ee,phoneDir as ue,profileHash as pe,profileLabels as _e,profileVars as Oe,readBuoyInstallId as Le,readLaunchFile as fe,readSummary as he,removeLaunchFile as De,runAndroidCommand as Ie,runChromeCommand as Ne,runFarmCommand as Pe,savePhone as Ae,simLaunchEnv as ce,slimLabels as Se,startFarmd as Te,suggestCounts as Ce,summarize as Fe,writeLaunchFile as Re}from"./chunk-FYJWWTAC.mjs";import"./chunk-MTTWR4T7.mjs";export{r as ALWAYS_ENABLED,a as ANDROID_ADB_PORT,o as BUILT_IN_ANDROID_PHONES,n as BUILT_IN_PHONES,D as CHROME_PINNED_VERSION,i as ChromeFarm,t as DEFAULT_ANDROID_PHONE,l as DEFAULT_CAP_MB,m as DEFAULT_PHONE,s as DEFAULT_SETTINGS,d as DESKTOP_VIEWPORT,E as EmulatorHost,u as Engine,p as FarmClient,_ as FarmError,O as LoadMeter,L as LocalDylibBuilder,f as PHONE_OFF,h as PHONE_VIEWPORT,I as PROTOCOL_VERSION,N as PipeCdp,P as SLIM_CATEGORIES,A as STATE_VERSION,c as SimctlHost,S as Store,T as agentLabel,C as androidHelp,F as androidHome,R as bootEnv,H as buildDylib,B as chromeFarmDir,b as chromeHelp,g as classifyBootLog,v as connectFarm,y as copyCostGB,U as coreInfo,V as crashLoop,M as defaultCapMB,G as defaultSeedDir,q as detectAgent,x as ensureKeeper,W as eventsFilePath,k as farmAdbTarget,w as farmAdbTargets,K as farmDefaults,j as farmHelp,z as farmHome,Y as farmOwnedUdids,J as findDataContainer,Q as findExampleBuild,X as findRepoRoot,Z as findShell,$ as installShell,ee as joinInsertList,re as keeperAlive,ae as keeperCall,oe as launchFilePath,ne as loadAndroidPhones,ie as loadPhones,te as measurePhone,le as nodeLauncher,me as parseCpuTime,se as parseEvents,de as parseGfxinfo,Ee as paths,ue as phoneDir,pe as profileHash,_e as profileLabels,Oe as profileVars,Le as readBuoyInstallId,fe as readLaunchFile,he as readSummary,De as removeLaunchFile,Ie as runAndroidCommand,Ne as runChromeCommand,Pe as runFarmCommand,Ae as savePhone,ce as simLaunchEnv,Se as slimLabels,Te as startFarmd,Ce as suggestCounts,Fe as summarize,Re as writeLaunchFile};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buoy-gg/mcp",
|
|
3
3
|
"mcpName": "io.github.Buoy-gg/mcp",
|
|
4
|
-
"version": "7.0.
|
|
4
|
+
"version": "7.0.79",
|
|
5
5
|
"buoy": {
|
|
6
6
|
"dashboardAuthVersion": 1
|
|
7
7
|
},
|
|
@@ -23,7 +23,17 @@
|
|
|
23
23
|
"default": "./dist/index.js"
|
|
24
24
|
}
|
|
25
25
|
},
|
|
26
|
-
"./package.json": "./package.json"
|
|
26
|
+
"./package.json": "./package.json",
|
|
27
|
+
"./native-profiler": {
|
|
28
|
+
"import": {
|
|
29
|
+
"types": "./dist/nativeProfiler.d.ts",
|
|
30
|
+
"default": "./dist/nativeProfiler.mjs"
|
|
31
|
+
},
|
|
32
|
+
"require": {
|
|
33
|
+
"types": "./dist/nativeProfiler.d.ts",
|
|
34
|
+
"default": "./dist/nativeProfiler.js"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
27
37
|
},
|
|
28
38
|
"files": [
|
|
29
39
|
"dist",
|
|
@@ -33,11 +43,12 @@
|
|
|
33
43
|
"dependencies": {
|
|
34
44
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
35
45
|
"playwright-core": "1.62.1",
|
|
46
|
+
"saxes": "^6.0.0",
|
|
36
47
|
"socket.io-client": "^4.8.4",
|
|
37
48
|
"ws": "^8.22.0",
|
|
38
49
|
"zod": "^3.25.0",
|
|
39
|
-
"@buoy-gg/
|
|
40
|
-
"@buoy-gg/
|
|
50
|
+
"@buoy-gg/license": "^7.0.79",
|
|
51
|
+
"@buoy-gg/sync-broker": "^7.0.79"
|
|
41
52
|
},
|
|
42
53
|
"devDependencies": {
|
|
43
54
|
"@types/node": "^22.0.0",
|
|
@@ -48,7 +59,7 @@
|
|
|
48
59
|
"rimraf": "^5.0.0",
|
|
49
60
|
"tsup": "^8.5.1",
|
|
50
61
|
"typescript": "~5.8.3",
|
|
51
|
-
"@buoy-gg/sim-farm": "7.0.
|
|
62
|
+
"@buoy-gg/sim-farm": "7.0.79"
|
|
52
63
|
},
|
|
53
64
|
"engines": {
|
|
54
65
|
"node": ">=18"
|